repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
viaembedded/vab1000-kernel-bsp | arch/microblaze/kernel/module.c | 4785 | 3117 | /*
* Copyright (C) 2007-2009 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2007-2009 PetaLogix
*
* 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/moduleloader.h>
#include <linux/kernel.h>
#include <linux/elf.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <asm/pgtable.h>
#include <asm/cacheflush.h>
int apply_relocate_add(Elf32_Shdr *sechdrs, const char *strtab,
unsigned int symindex, unsigned int relsec, struct module *module)
{
unsigned int i;
Elf32_Rela *rela = (void *)sechdrs[relsec].sh_addr;
Elf32_Sym *sym;
unsigned long int *location;
unsigned long int value;
#if __GNUC__ < 4
unsigned long int old_value;
#endif
pr_debug("Applying add relocation section %u to %u\n",
relsec, sechdrs[relsec].sh_info);
for (i = 0; i < sechdrs[relsec].sh_size / sizeof(*rela); i++) {
location = (void *)sechdrs[sechdrs[relsec].sh_info].sh_addr +
rela[i].r_offset;
sym = (Elf32_Sym *)sechdrs[symindex].sh_addr +
ELF32_R_SYM(rela[i].r_info);
value = sym->st_value + rela[i].r_addend;
switch (ELF32_R_TYPE(rela[i].r_info)) {
/*
* Be careful! mb-gcc / mb-ld splits the relocs between the
* text and the reloc table. In general this means we must
* read the current contents of (*location), add any offset
* then store the result back in
*/
case R_MICROBLAZE_32:
#if __GNUC__ < 4
old_value = *location;
*location = value + old_value;
pr_debug("R_MICROBLAZE_32 (%08lx->%08lx)\n",
old_value, value);
#else
*location = value;
#endif
break;
case R_MICROBLAZE_64:
#if __GNUC__ < 4
/* Split relocs only required/used pre gcc4.1.1 */
old_value = ((location[0] & 0x0000FFFF) << 16) |
(location[1] & 0x0000FFFF);
value += old_value;
#endif
location[0] = (location[0] & 0xFFFF0000) |
(value >> 16);
location[1] = (location[1] & 0xFFFF0000) |
(value & 0xFFFF);
#if __GNUC__ < 4
pr_debug("R_MICROBLAZE_64 (%08lx->%08lx)\n",
old_value, value);
#endif
break;
case R_MICROBLAZE_64_PCREL:
#if __GNUC__ < 4
old_value = (location[0] & 0xFFFF) << 16 |
(location[1] & 0xFFFF);
value -= old_value;
#endif
value -= (unsigned long int)(location) + 4;
location[0] = (location[0] & 0xFFFF0000) |
(value >> 16);
location[1] = (location[1] & 0xFFFF0000) |
(value & 0xFFFF);
pr_debug("R_MICROBLAZE_64_PCREL (%08lx)\n",
value);
break;
case R_MICROBLAZE_32_PCREL_LO:
pr_debug("R_MICROBLAZE_32_PCREL_LO\n");
break;
case R_MICROBLAZE_64_NONE:
pr_debug("R_MICROBLAZE_64_NONE\n");
break;
case R_MICROBLAZE_NONE:
pr_debug("R_MICROBLAZE_NONE\n");
break;
default:
printk(KERN_ERR "module %s: "
"Unknown relocation: %u\n",
module->name,
ELF32_R_TYPE(rela[i].r_info));
return -ENOEXEC;
}
}
return 0;
}
int module_finalize(const Elf32_Ehdr *hdr, const Elf_Shdr *sechdrs,
struct module *module)
{
flush_dcache();
return 0;
}
| gpl-2.0 |
javelinanddart/android_kernel_3.10_ville | arch/powerpc/platforms/ps3/interrupt.c | 7601 | 20118 | /*
* PS3 interrupt routines.
*
* Copyright (C) 2006 Sony Computer Entertainment Inc.
* Copyright 2006 Sony 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; 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/export.h>
#include <linux/irq.h>
#include <asm/machdep.h>
#include <asm/udbg.h>
#include <asm/lv1call.h>
#include <asm/smp.h>
#include "platform.h"
#if defined(DEBUG)
#define DBG udbg_printf
#define FAIL udbg_printf
#else
#define DBG pr_devel
#define FAIL pr_debug
#endif
/**
* struct ps3_bmp - a per cpu irq status and mask bitmap structure
* @status: 256 bit status bitmap indexed by plug
* @unused_1: Alignment
* @mask: 256 bit mask bitmap indexed by plug
* @unused_2: Alignment
*
* The HV maintains per SMT thread mappings of HV outlet to HV plug on
* behalf of the guest. These mappings are implemented as 256 bit guest
* supplied bitmaps indexed by plug number. The addresses of the bitmaps
* are registered with the HV through lv1_configure_irq_state_bitmap().
* The HV requires that the 512 bits of status + mask not cross a page
* boundary. PS3_BMP_MINALIGN is used to define this minimal 64 byte
* alignment.
*
* The HV supports 256 plugs per thread, assigned as {0..255}, for a total
* of 512 plugs supported on a processor. To simplify the logic this
* implementation equates HV plug value to Linux virq value, constrains each
* interrupt to have a system wide unique plug number, and limits the range
* of the plug values to map into the first dword of the bitmaps. This
* gives a usable range of plug values of {NUM_ISA_INTERRUPTS..63}. Note
* that there is no constraint on how many in this set an individual thread
* can acquire.
*
* The mask is declared as unsigned long so we can use set/clear_bit on it.
*/
#define PS3_BMP_MINALIGN 64
struct ps3_bmp {
struct {
u64 status;
u64 unused_1[3];
unsigned long mask;
u64 unused_2[3];
};
};
/**
* struct ps3_private - a per cpu data structure
* @bmp: ps3_bmp structure
* @bmp_lock: Syncronize access to bmp.
* @ipi_debug_brk_mask: Mask for debug break IPIs
* @ppe_id: HV logical_ppe_id
* @thread_id: HV thread_id
* @ipi_mask: Mask of IPI virqs
*/
struct ps3_private {
struct ps3_bmp bmp __attribute__ ((aligned (PS3_BMP_MINALIGN)));
spinlock_t bmp_lock;
u64 ppe_id;
u64 thread_id;
unsigned long ipi_debug_brk_mask;
unsigned long ipi_mask;
};
static DEFINE_PER_CPU(struct ps3_private, ps3_private);
/**
* ps3_chip_mask - Set an interrupt mask bit in ps3_bmp.
* @virq: The assigned Linux virq.
*
* Sets ps3_bmp.mask and calls lv1_did_update_interrupt_mask().
*/
static void ps3_chip_mask(struct irq_data *d)
{
struct ps3_private *pd = irq_data_get_irq_chip_data(d);
unsigned long flags;
DBG("%s:%d: thread_id %llu, virq %d\n", __func__, __LINE__,
pd->thread_id, d->irq);
local_irq_save(flags);
clear_bit(63 - d->irq, &pd->bmp.mask);
lv1_did_update_interrupt_mask(pd->ppe_id, pd->thread_id);
local_irq_restore(flags);
}
/**
* ps3_chip_unmask - Clear an interrupt mask bit in ps3_bmp.
* @virq: The assigned Linux virq.
*
* Clears ps3_bmp.mask and calls lv1_did_update_interrupt_mask().
*/
static void ps3_chip_unmask(struct irq_data *d)
{
struct ps3_private *pd = irq_data_get_irq_chip_data(d);
unsigned long flags;
DBG("%s:%d: thread_id %llu, virq %d\n", __func__, __LINE__,
pd->thread_id, d->irq);
local_irq_save(flags);
set_bit(63 - d->irq, &pd->bmp.mask);
lv1_did_update_interrupt_mask(pd->ppe_id, pd->thread_id);
local_irq_restore(flags);
}
/**
* ps3_chip_eoi - HV end-of-interrupt.
* @virq: The assigned Linux virq.
*
* Calls lv1_end_of_interrupt_ext().
*/
static void ps3_chip_eoi(struct irq_data *d)
{
const struct ps3_private *pd = irq_data_get_irq_chip_data(d);
/* non-IPIs are EOIed here. */
if (!test_bit(63 - d->irq, &pd->ipi_mask))
lv1_end_of_interrupt_ext(pd->ppe_id, pd->thread_id, d->irq);
}
/**
* ps3_irq_chip - Represents the ps3_bmp as a Linux struct irq_chip.
*/
static struct irq_chip ps3_irq_chip = {
.name = "ps3",
.irq_mask = ps3_chip_mask,
.irq_unmask = ps3_chip_unmask,
.irq_eoi = ps3_chip_eoi,
};
/**
* ps3_virq_setup - virq related setup.
* @cpu: enum ps3_cpu_binding indicating the cpu the interrupt should be
* serviced on.
* @outlet: The HV outlet from the various create outlet routines.
* @virq: The assigned Linux virq.
*
* Calls irq_create_mapping() to get a virq and sets the chip data to
* ps3_private data.
*/
static int ps3_virq_setup(enum ps3_cpu_binding cpu, unsigned long outlet,
unsigned int *virq)
{
int result;
struct ps3_private *pd;
/* This defines the default interrupt distribution policy. */
if (cpu == PS3_BINDING_CPU_ANY)
cpu = 0;
pd = &per_cpu(ps3_private, cpu);
*virq = irq_create_mapping(NULL, outlet);
if (*virq == NO_IRQ) {
FAIL("%s:%d: irq_create_mapping failed: outlet %lu\n",
__func__, __LINE__, outlet);
result = -ENOMEM;
goto fail_create;
}
DBG("%s:%d: outlet %lu => cpu %u, virq %u\n", __func__, __LINE__,
outlet, cpu, *virq);
result = irq_set_chip_data(*virq, pd);
if (result) {
FAIL("%s:%d: irq_set_chip_data failed\n",
__func__, __LINE__);
goto fail_set;
}
ps3_chip_mask(irq_get_irq_data(*virq));
return result;
fail_set:
irq_dispose_mapping(*virq);
fail_create:
return result;
}
/**
* ps3_virq_destroy - virq related teardown.
* @virq: The assigned Linux virq.
*
* Clears chip data and calls irq_dispose_mapping() for the virq.
*/
static int ps3_virq_destroy(unsigned int virq)
{
const struct ps3_private *pd = irq_get_chip_data(virq);
DBG("%s:%d: ppe_id %llu, thread_id %llu, virq %u\n", __func__,
__LINE__, pd->ppe_id, pd->thread_id, virq);
irq_set_chip_data(virq, NULL);
irq_dispose_mapping(virq);
DBG("%s:%d <-\n", __func__, __LINE__);
return 0;
}
/**
* ps3_irq_plug_setup - Generic outlet and virq related setup.
* @cpu: enum ps3_cpu_binding indicating the cpu the interrupt should be
* serviced on.
* @outlet: The HV outlet from the various create outlet routines.
* @virq: The assigned Linux virq.
*
* Sets up virq and connects the irq plug.
*/
int ps3_irq_plug_setup(enum ps3_cpu_binding cpu, unsigned long outlet,
unsigned int *virq)
{
int result;
struct ps3_private *pd;
result = ps3_virq_setup(cpu, outlet, virq);
if (result) {
FAIL("%s:%d: ps3_virq_setup failed\n", __func__, __LINE__);
goto fail_setup;
}
pd = irq_get_chip_data(*virq);
/* Binds outlet to cpu + virq. */
result = lv1_connect_irq_plug_ext(pd->ppe_id, pd->thread_id, *virq,
outlet, 0);
if (result) {
FAIL("%s:%d: lv1_connect_irq_plug_ext failed: %s\n",
__func__, __LINE__, ps3_result(result));
result = -EPERM;
goto fail_connect;
}
return result;
fail_connect:
ps3_virq_destroy(*virq);
fail_setup:
return result;
}
EXPORT_SYMBOL_GPL(ps3_irq_plug_setup);
/**
* ps3_irq_plug_destroy - Generic outlet and virq related teardown.
* @virq: The assigned Linux virq.
*
* Disconnects the irq plug and tears down virq.
* Do not call for system bus event interrupts setup with
* ps3_sb_event_receive_port_setup().
*/
int ps3_irq_plug_destroy(unsigned int virq)
{
int result;
const struct ps3_private *pd = irq_get_chip_data(virq);
DBG("%s:%d: ppe_id %llu, thread_id %llu, virq %u\n", __func__,
__LINE__, pd->ppe_id, pd->thread_id, virq);
ps3_chip_mask(irq_get_irq_data(virq));
result = lv1_disconnect_irq_plug_ext(pd->ppe_id, pd->thread_id, virq);
if (result)
FAIL("%s:%d: lv1_disconnect_irq_plug_ext failed: %s\n",
__func__, __LINE__, ps3_result(result));
ps3_virq_destroy(virq);
return result;
}
EXPORT_SYMBOL_GPL(ps3_irq_plug_destroy);
/**
* ps3_event_receive_port_setup - Setup an event receive port.
* @cpu: enum ps3_cpu_binding indicating the cpu the interrupt should be
* serviced on.
* @virq: The assigned Linux virq.
*
* The virq can be used with lv1_connect_interrupt_event_receive_port() to
* arrange to receive interrupts from system-bus devices, or with
* ps3_send_event_locally() to signal events.
*/
int ps3_event_receive_port_setup(enum ps3_cpu_binding cpu, unsigned int *virq)
{
int result;
u64 outlet;
result = lv1_construct_event_receive_port(&outlet);
if (result) {
FAIL("%s:%d: lv1_construct_event_receive_port failed: %s\n",
__func__, __LINE__, ps3_result(result));
*virq = NO_IRQ;
return result;
}
result = ps3_irq_plug_setup(cpu, outlet, virq);
BUG_ON(result);
return result;
}
EXPORT_SYMBOL_GPL(ps3_event_receive_port_setup);
/**
* ps3_event_receive_port_destroy - Destroy an event receive port.
* @virq: The assigned Linux virq.
*
* Since ps3_event_receive_port_destroy destroys the receive port outlet,
* SB devices need to call disconnect_interrupt_event_receive_port() before
* this.
*/
int ps3_event_receive_port_destroy(unsigned int virq)
{
int result;
DBG(" -> %s:%d virq %u\n", __func__, __LINE__, virq);
ps3_chip_mask(irq_get_irq_data(virq));
result = lv1_destruct_event_receive_port(virq_to_hw(virq));
if (result)
FAIL("%s:%d: lv1_destruct_event_receive_port failed: %s\n",
__func__, __LINE__, ps3_result(result));
/*
* Don't call ps3_virq_destroy() here since ps3_smp_cleanup_cpu()
* calls from interrupt context (smp_call_function) when kexecing.
*/
DBG(" <- %s:%d\n", __func__, __LINE__);
return result;
}
int ps3_send_event_locally(unsigned int virq)
{
return lv1_send_event_locally(virq_to_hw(virq));
}
/**
* ps3_sb_event_receive_port_setup - Setup a system bus event receive port.
* @cpu: enum ps3_cpu_binding indicating the cpu the interrupt should be
* serviced on.
* @dev: The system bus device instance.
* @virq: The assigned Linux virq.
*
* An event irq represents a virtual device interrupt. The interrupt_id
* coresponds to the software interrupt number.
*/
int ps3_sb_event_receive_port_setup(struct ps3_system_bus_device *dev,
enum ps3_cpu_binding cpu, unsigned int *virq)
{
/* this should go in system-bus.c */
int result;
result = ps3_event_receive_port_setup(cpu, virq);
if (result)
return result;
result = lv1_connect_interrupt_event_receive_port(dev->bus_id,
dev->dev_id, virq_to_hw(*virq), dev->interrupt_id);
if (result) {
FAIL("%s:%d: lv1_connect_interrupt_event_receive_port"
" failed: %s\n", __func__, __LINE__,
ps3_result(result));
ps3_event_receive_port_destroy(*virq);
*virq = NO_IRQ;
return result;
}
DBG("%s:%d: interrupt_id %u, virq %u\n", __func__, __LINE__,
dev->interrupt_id, *virq);
return 0;
}
EXPORT_SYMBOL(ps3_sb_event_receive_port_setup);
int ps3_sb_event_receive_port_destroy(struct ps3_system_bus_device *dev,
unsigned int virq)
{
/* this should go in system-bus.c */
int result;
DBG(" -> %s:%d: interrupt_id %u, virq %u\n", __func__, __LINE__,
dev->interrupt_id, virq);
result = lv1_disconnect_interrupt_event_receive_port(dev->bus_id,
dev->dev_id, virq_to_hw(virq), dev->interrupt_id);
if (result)
FAIL("%s:%d: lv1_disconnect_interrupt_event_receive_port"
" failed: %s\n", __func__, __LINE__,
ps3_result(result));
result = ps3_event_receive_port_destroy(virq);
BUG_ON(result);
/*
* ps3_event_receive_port_destroy() destroys the IRQ plug,
* so don't call ps3_irq_plug_destroy() here.
*/
result = ps3_virq_destroy(virq);
BUG_ON(result);
DBG(" <- %s:%d\n", __func__, __LINE__);
return result;
}
EXPORT_SYMBOL(ps3_sb_event_receive_port_destroy);
/**
* ps3_io_irq_setup - Setup a system bus io irq.
* @cpu: enum ps3_cpu_binding indicating the cpu the interrupt should be
* serviced on.
* @interrupt_id: The device interrupt id read from the system repository.
* @virq: The assigned Linux virq.
*
* An io irq represents a non-virtualized device interrupt. interrupt_id
* coresponds to the interrupt number of the interrupt controller.
*/
int ps3_io_irq_setup(enum ps3_cpu_binding cpu, unsigned int interrupt_id,
unsigned int *virq)
{
int result;
u64 outlet;
result = lv1_construct_io_irq_outlet(interrupt_id, &outlet);
if (result) {
FAIL("%s:%d: lv1_construct_io_irq_outlet failed: %s\n",
__func__, __LINE__, ps3_result(result));
return result;
}
result = ps3_irq_plug_setup(cpu, outlet, virq);
BUG_ON(result);
return result;
}
EXPORT_SYMBOL_GPL(ps3_io_irq_setup);
int ps3_io_irq_destroy(unsigned int virq)
{
int result;
unsigned long outlet = virq_to_hw(virq);
ps3_chip_mask(irq_get_irq_data(virq));
/*
* lv1_destruct_io_irq_outlet() will destroy the IRQ plug,
* so call ps3_irq_plug_destroy() first.
*/
result = ps3_irq_plug_destroy(virq);
BUG_ON(result);
result = lv1_destruct_io_irq_outlet(outlet);
if (result)
FAIL("%s:%d: lv1_destruct_io_irq_outlet failed: %s\n",
__func__, __LINE__, ps3_result(result));
return result;
}
EXPORT_SYMBOL_GPL(ps3_io_irq_destroy);
/**
* ps3_vuart_irq_setup - Setup the system virtual uart virq.
* @cpu: enum ps3_cpu_binding indicating the cpu the interrupt should be
* serviced on.
* @virt_addr_bmp: The caller supplied virtual uart interrupt bitmap.
* @virq: The assigned Linux virq.
*
* The system supports only a single virtual uart, so multiple calls without
* freeing the interrupt will return a wrong state error.
*/
int ps3_vuart_irq_setup(enum ps3_cpu_binding cpu, void* virt_addr_bmp,
unsigned int *virq)
{
int result;
u64 outlet;
u64 lpar_addr;
BUG_ON(!is_kernel_addr((u64)virt_addr_bmp));
lpar_addr = ps3_mm_phys_to_lpar(__pa(virt_addr_bmp));
result = lv1_configure_virtual_uart_irq(lpar_addr, &outlet);
if (result) {
FAIL("%s:%d: lv1_configure_virtual_uart_irq failed: %s\n",
__func__, __LINE__, ps3_result(result));
return result;
}
result = ps3_irq_plug_setup(cpu, outlet, virq);
BUG_ON(result);
return result;
}
EXPORT_SYMBOL_GPL(ps3_vuart_irq_setup);
int ps3_vuart_irq_destroy(unsigned int virq)
{
int result;
ps3_chip_mask(irq_get_irq_data(virq));
result = lv1_deconfigure_virtual_uart_irq();
if (result) {
FAIL("%s:%d: lv1_configure_virtual_uart_irq failed: %s\n",
__func__, __LINE__, ps3_result(result));
return result;
}
result = ps3_irq_plug_destroy(virq);
BUG_ON(result);
return result;
}
EXPORT_SYMBOL_GPL(ps3_vuart_irq_destroy);
/**
* ps3_spe_irq_setup - Setup an spe virq.
* @cpu: enum ps3_cpu_binding indicating the cpu the interrupt should be
* serviced on.
* @spe_id: The spe_id returned from lv1_construct_logical_spe().
* @class: The spe interrupt class {0,1,2}.
* @virq: The assigned Linux virq.
*
*/
int ps3_spe_irq_setup(enum ps3_cpu_binding cpu, unsigned long spe_id,
unsigned int class, unsigned int *virq)
{
int result;
u64 outlet;
BUG_ON(class > 2);
result = lv1_get_spe_irq_outlet(spe_id, class, &outlet);
if (result) {
FAIL("%s:%d: lv1_get_spe_irq_outlet failed: %s\n",
__func__, __LINE__, ps3_result(result));
return result;
}
result = ps3_irq_plug_setup(cpu, outlet, virq);
BUG_ON(result);
return result;
}
int ps3_spe_irq_destroy(unsigned int virq)
{
int result;
ps3_chip_mask(irq_get_irq_data(virq));
result = ps3_irq_plug_destroy(virq);
BUG_ON(result);
return result;
}
#define PS3_INVALID_OUTLET ((irq_hw_number_t)-1)
#define PS3_PLUG_MAX 63
#if defined(DEBUG)
static void _dump_64_bmp(const char *header, const u64 *p, unsigned cpu,
const char* func, int line)
{
pr_debug("%s:%d: %s %u {%04llx_%04llx_%04llx_%04llx}\n",
func, line, header, cpu,
*p >> 48, (*p >> 32) & 0xffff, (*p >> 16) & 0xffff,
*p & 0xffff);
}
static void __maybe_unused _dump_256_bmp(const char *header,
const u64 *p, unsigned cpu, const char* func, int line)
{
pr_debug("%s:%d: %s %u {%016llx:%016llx:%016llx:%016llx}\n",
func, line, header, cpu, p[0], p[1], p[2], p[3]);
}
#define dump_bmp(_x) _dump_bmp(_x, __func__, __LINE__)
static void _dump_bmp(struct ps3_private* pd, const char* func, int line)
{
unsigned long flags;
spin_lock_irqsave(&pd->bmp_lock, flags);
_dump_64_bmp("stat", &pd->bmp.status, pd->thread_id, func, line);
_dump_64_bmp("mask", (u64*)&pd->bmp.mask, pd->thread_id, func, line);
spin_unlock_irqrestore(&pd->bmp_lock, flags);
}
#define dump_mask(_x) _dump_mask(_x, __func__, __LINE__)
static void __maybe_unused _dump_mask(struct ps3_private *pd,
const char* func, int line)
{
unsigned long flags;
spin_lock_irqsave(&pd->bmp_lock, flags);
_dump_64_bmp("mask", (u64*)&pd->bmp.mask, pd->thread_id, func, line);
spin_unlock_irqrestore(&pd->bmp_lock, flags);
}
#else
static void dump_bmp(struct ps3_private* pd) {};
#endif /* defined(DEBUG) */
static int ps3_host_map(struct irq_domain *h, unsigned int virq,
irq_hw_number_t hwirq)
{
DBG("%s:%d: hwirq %lu, virq %u\n", __func__, __LINE__, hwirq,
virq);
irq_set_chip_and_handler(virq, &ps3_irq_chip, handle_fasteoi_irq);
return 0;
}
static int ps3_host_match(struct irq_domain *h, struct device_node *np)
{
/* Match all */
return 1;
}
static const struct irq_domain_ops ps3_host_ops = {
.map = ps3_host_map,
.match = ps3_host_match,
};
void __init ps3_register_ipi_debug_brk(unsigned int cpu, unsigned int virq)
{
struct ps3_private *pd = &per_cpu(ps3_private, cpu);
set_bit(63 - virq, &pd->ipi_debug_brk_mask);
DBG("%s:%d: cpu %u, virq %u, mask %lxh\n", __func__, __LINE__,
cpu, virq, pd->ipi_debug_brk_mask);
}
void __init ps3_register_ipi_irq(unsigned int cpu, unsigned int virq)
{
struct ps3_private *pd = &per_cpu(ps3_private, cpu);
set_bit(63 - virq, &pd->ipi_mask);
DBG("%s:%d: cpu %u, virq %u, ipi_mask %lxh\n", __func__, __LINE__,
cpu, virq, pd->ipi_mask);
}
static unsigned int ps3_get_irq(void)
{
struct ps3_private *pd = &__get_cpu_var(ps3_private);
u64 x = (pd->bmp.status & pd->bmp.mask);
unsigned int plug;
/* check for ipi break first to stop this cpu ASAP */
if (x & pd->ipi_debug_brk_mask)
x &= pd->ipi_debug_brk_mask;
asm volatile("cntlzd %0,%1" : "=r" (plug) : "r" (x));
plug &= 0x3f;
if (unlikely(plug == NO_IRQ)) {
DBG("%s:%d: no plug found: thread_id %llu\n", __func__,
__LINE__, pd->thread_id);
dump_bmp(&per_cpu(ps3_private, 0));
dump_bmp(&per_cpu(ps3_private, 1));
return NO_IRQ;
}
#if defined(DEBUG)
if (unlikely(plug < NUM_ISA_INTERRUPTS || plug > PS3_PLUG_MAX)) {
dump_bmp(&per_cpu(ps3_private, 0));
dump_bmp(&per_cpu(ps3_private, 1));
BUG();
}
#endif
/* IPIs are EOIed here. */
if (test_bit(63 - plug, &pd->ipi_mask))
lv1_end_of_interrupt_ext(pd->ppe_id, pd->thread_id, plug);
return plug;
}
void __init ps3_init_IRQ(void)
{
int result;
unsigned cpu;
struct irq_domain *host;
host = irq_domain_add_nomap(NULL, PS3_PLUG_MAX + 1, &ps3_host_ops, NULL);
irq_set_default_host(host);
for_each_possible_cpu(cpu) {
struct ps3_private *pd = &per_cpu(ps3_private, cpu);
lv1_get_logical_ppe_id(&pd->ppe_id);
pd->thread_id = get_hard_smp_processor_id(cpu);
spin_lock_init(&pd->bmp_lock);
DBG("%s:%d: ppe_id %llu, thread_id %llu, bmp %lxh\n",
__func__, __LINE__, pd->ppe_id, pd->thread_id,
ps3_mm_phys_to_lpar(__pa(&pd->bmp)));
result = lv1_configure_irq_state_bitmap(pd->ppe_id,
pd->thread_id, ps3_mm_phys_to_lpar(__pa(&pd->bmp)));
if (result)
FAIL("%s:%d: lv1_configure_irq_state_bitmap failed:"
" %s\n", __func__, __LINE__,
ps3_result(result));
}
ppc_md.get_irq = ps3_get_irq;
}
void ps3_shutdown_IRQ(int cpu)
{
int result;
u64 ppe_id;
u64 thread_id = get_hard_smp_processor_id(cpu);
lv1_get_logical_ppe_id(&ppe_id);
result = lv1_configure_irq_state_bitmap(ppe_id, thread_id, 0);
DBG("%s:%d: lv1_configure_irq_state_bitmap (%llu:%llu/%d) %s\n", __func__,
__LINE__, ppe_id, thread_id, cpu, ps3_result(result));
}
| gpl-2.0 |
KlinkOnE/caf-port | drivers/ide/via82cxxx.c | 8113 | 15093 | /*
* VIA IDE driver for Linux. Supported southbridges:
*
* vt82c576, vt82c586, vt82c586a, vt82c586b, vt82c596a, vt82c596b,
* vt82c686, vt82c686a, vt82c686b, vt8231, vt8233, vt8233c, vt8233a,
* vt8235, vt8237, vt8237a
*
* Copyright (c) 2000-2002 Vojtech Pavlik
* Copyright (c) 2007-2010 Bartlomiej Zolnierkiewicz
*
* Based on the work of:
* Michel Aubry
* Jeff Garzik
* Andre Hedrick
*
* Documentation:
* Obsolete device documentation publicly available from via.com.tw
* Current device documentation available under NDA only
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ide.h>
#include <linux/dmi.h>
#ifdef CONFIG_PPC_CHRP
#include <asm/processor.h>
#endif
#define DRV_NAME "via82cxxx"
#define VIA_IDE_ENABLE 0x40
#define VIA_IDE_CONFIG 0x41
#define VIA_FIFO_CONFIG 0x43
#define VIA_MISC_1 0x44
#define VIA_MISC_2 0x45
#define VIA_MISC_3 0x46
#define VIA_DRIVE_TIMING 0x48
#define VIA_8BIT_TIMING 0x4e
#define VIA_ADDRESS_SETUP 0x4c
#define VIA_UDMA_TIMING 0x50
#define VIA_BAD_PREQ 0x01 /* Crashes if PREQ# till DDACK# set */
#define VIA_BAD_CLK66 0x02 /* 66 MHz clock doesn't work correctly */
#define VIA_SET_FIFO 0x04 /* Needs to have FIFO split set */
#define VIA_NO_UNMASK 0x08 /* Doesn't work with IRQ unmasking on */
#define VIA_BAD_ID 0x10 /* Has wrong vendor ID (0x1107) */
#define VIA_BAD_AST 0x20 /* Don't touch Address Setup Timing */
#define VIA_SATA_PATA 0x80 /* SATA/PATA combined configuration */
enum {
VIA_IDFLAG_SINGLE = (1 << 1), /* single channel controller */
};
/*
* VIA SouthBridge chips.
*/
static struct via_isa_bridge {
char *name;
u16 id;
u8 rev_min;
u8 rev_max;
u8 udma_mask;
u8 flags;
} via_isa_bridges[] = {
{ "vx855", PCI_DEVICE_ID_VIA_VX855, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST | VIA_SATA_PATA },
{ "vx800", PCI_DEVICE_ID_VIA_VX800, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST | VIA_SATA_PATA },
{ "cx700", PCI_DEVICE_ID_VIA_CX700, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST | VIA_SATA_PATA },
{ "vt8261", PCI_DEVICE_ID_VIA_8261, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8237s", PCI_DEVICE_ID_VIA_8237S, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt6410", PCI_DEVICE_ID_VIA_6410, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt6415", PCI_DEVICE_ID_VIA_6415, 0x00, 0xff, ATA_UDMA6, VIA_BAD_AST },
{ "vt8251", PCI_DEVICE_ID_VIA_8251, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8237", PCI_DEVICE_ID_VIA_8237, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8237a", PCI_DEVICE_ID_VIA_8237A, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8235", PCI_DEVICE_ID_VIA_8235, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8233a", PCI_DEVICE_ID_VIA_8233A, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8233c", PCI_DEVICE_ID_VIA_8233C_0, 0x00, 0x2f, ATA_UDMA5, },
{ "vt8233", PCI_DEVICE_ID_VIA_8233_0, 0x00, 0x2f, ATA_UDMA5, },
{ "vt8231", PCI_DEVICE_ID_VIA_8231, 0x00, 0x2f, ATA_UDMA5, },
{ "vt82c686b", PCI_DEVICE_ID_VIA_82C686, 0x40, 0x4f, ATA_UDMA5, },
{ "vt82c686a", PCI_DEVICE_ID_VIA_82C686, 0x10, 0x2f, ATA_UDMA4, },
{ "vt82c686", PCI_DEVICE_ID_VIA_82C686, 0x00, 0x0f, ATA_UDMA2, VIA_BAD_CLK66 },
{ "vt82c596b", PCI_DEVICE_ID_VIA_82C596, 0x10, 0x2f, ATA_UDMA4, },
{ "vt82c596a", PCI_DEVICE_ID_VIA_82C596, 0x00, 0x0f, ATA_UDMA2, VIA_BAD_CLK66 },
{ "vt82c586b", PCI_DEVICE_ID_VIA_82C586_0, 0x47, 0x4f, ATA_UDMA2, VIA_SET_FIFO },
{ "vt82c586b", PCI_DEVICE_ID_VIA_82C586_0, 0x40, 0x46, ATA_UDMA2, VIA_SET_FIFO | VIA_BAD_PREQ },
{ "vt82c586b", PCI_DEVICE_ID_VIA_82C586_0, 0x30, 0x3f, ATA_UDMA2, VIA_SET_FIFO },
{ "vt82c586a", PCI_DEVICE_ID_VIA_82C586_0, 0x20, 0x2f, ATA_UDMA2, VIA_SET_FIFO },
{ "vt82c586", PCI_DEVICE_ID_VIA_82C586_0, 0x00, 0x0f, 0x00, VIA_SET_FIFO },
{ "vt82c576", PCI_DEVICE_ID_VIA_82C576, 0x00, 0x2f, 0x00, VIA_SET_FIFO | VIA_NO_UNMASK },
{ "vt82c576", PCI_DEVICE_ID_VIA_82C576, 0x00, 0x2f, 0x00, VIA_SET_FIFO | VIA_NO_UNMASK | VIA_BAD_ID },
{ "vtxxxx", PCI_DEVICE_ID_VIA_ANON, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ NULL }
};
static unsigned int via_clock;
static char *via_dma[] = { "16", "25", "33", "44", "66", "100", "133" };
struct via82cxxx_dev
{
struct via_isa_bridge *via_config;
unsigned int via_80w;
};
/**
* via_set_speed - write timing registers
* @dev: PCI device
* @dn: device
* @timing: IDE timing data to use
*
* via_set_speed writes timing values to the chipset registers
*/
static void via_set_speed(ide_hwif_t *hwif, u8 dn, struct ide_timing *timing)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct ide_host *host = pci_get_drvdata(dev);
struct via82cxxx_dev *vdev = host->host_priv;
u8 t;
if (~vdev->via_config->flags & VIA_BAD_AST) {
pci_read_config_byte(dev, VIA_ADDRESS_SETUP, &t);
t = (t & ~(3 << ((3 - dn) << 1))) | ((clamp_val(timing->setup, 1, 4) - 1) << ((3 - dn) << 1));
pci_write_config_byte(dev, VIA_ADDRESS_SETUP, t);
}
pci_write_config_byte(dev, VIA_8BIT_TIMING + (1 - (dn >> 1)),
((clamp_val(timing->act8b, 1, 16) - 1) << 4) | (clamp_val(timing->rec8b, 1, 16) - 1));
pci_write_config_byte(dev, VIA_DRIVE_TIMING + (3 - dn),
((clamp_val(timing->active, 1, 16) - 1) << 4) | (clamp_val(timing->recover, 1, 16) - 1));
switch (vdev->via_config->udma_mask) {
case ATA_UDMA2: t = timing->udma ? (0xe0 | (clamp_val(timing->udma, 2, 5) - 2)) : 0x03; break;
case ATA_UDMA4: t = timing->udma ? (0xe8 | (clamp_val(timing->udma, 2, 9) - 2)) : 0x0f; break;
case ATA_UDMA5: t = timing->udma ? (0xe0 | (clamp_val(timing->udma, 2, 9) - 2)) : 0x07; break;
case ATA_UDMA6: t = timing->udma ? (0xe0 | (clamp_val(timing->udma, 2, 9) - 2)) : 0x07; break;
}
/* Set UDMA unless device is not UDMA capable */
if (vdev->via_config->udma_mask) {
u8 udma_etc;
pci_read_config_byte(dev, VIA_UDMA_TIMING + 3 - dn, &udma_etc);
/* clear transfer mode bit */
udma_etc &= ~0x20;
if (timing->udma) {
/* preserve 80-wire cable detection bit */
udma_etc &= 0x10;
udma_etc |= t;
}
pci_write_config_byte(dev, VIA_UDMA_TIMING + 3 - dn, udma_etc);
}
}
/**
* via_set_drive - configure transfer mode
* @hwif: port
* @drive: Drive to set up
*
* via_set_drive() computes timing values configures the chipset to
* a desired transfer mode. It also can be called by upper layers.
*/
static void via_set_drive(ide_hwif_t *hwif, ide_drive_t *drive)
{
ide_drive_t *peer = ide_get_pair_dev(drive);
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct ide_host *host = pci_get_drvdata(dev);
struct via82cxxx_dev *vdev = host->host_priv;
struct ide_timing t, p;
unsigned int T, UT;
const u8 speed = drive->dma_mode;
T = 1000000000 / via_clock;
switch (vdev->via_config->udma_mask) {
case ATA_UDMA2: UT = T; break;
case ATA_UDMA4: UT = T/2; break;
case ATA_UDMA5: UT = T/3; break;
case ATA_UDMA6: UT = T/4; break;
default: UT = T;
}
ide_timing_compute(drive, speed, &t, T, UT);
if (peer) {
ide_timing_compute(peer, peer->pio_mode, &p, T, UT);
ide_timing_merge(&p, &t, &t, IDE_TIMING_8BIT);
}
via_set_speed(hwif, drive->dn, &t);
}
/**
* via_set_pio_mode - set host controller for PIO mode
* @hwif: port
* @drive: drive
*
* A callback from the upper layers for PIO-only tuning.
*/
static void via_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
drive->dma_mode = drive->pio_mode;
via_set_drive(hwif, drive);
}
static struct via_isa_bridge *via_config_find(struct pci_dev **isa)
{
struct via_isa_bridge *via_config;
for (via_config = via_isa_bridges;
via_config->id != PCI_DEVICE_ID_VIA_ANON; via_config++)
if ((*isa = pci_get_device(PCI_VENDOR_ID_VIA +
!!(via_config->flags & VIA_BAD_ID),
via_config->id, NULL))) {
if ((*isa)->revision >= via_config->rev_min &&
(*isa)->revision <= via_config->rev_max)
break;
pci_dev_put(*isa);
}
return via_config;
}
/*
* Check and handle 80-wire cable presence
*/
static void via_cable_detect(struct via82cxxx_dev *vdev, u32 u)
{
int i;
switch (vdev->via_config->udma_mask) {
case ATA_UDMA4:
for (i = 24; i >= 0; i -= 8)
if (((u >> (i & 16)) & 8) &&
((u >> i) & 0x20) &&
(((u >> i) & 7) < 2)) {
/*
* 2x PCI clock and
* UDMA w/ < 3T/cycle
*/
vdev->via_80w |= (1 << (1 - (i >> 4)));
}
break;
case ATA_UDMA5:
for (i = 24; i >= 0; i -= 8)
if (((u >> i) & 0x10) ||
(((u >> i) & 0x20) &&
(((u >> i) & 7) < 4))) {
/* BIOS 80-wire bit or
* UDMA w/ < 60ns/cycle
*/
vdev->via_80w |= (1 << (1 - (i >> 4)));
}
break;
case ATA_UDMA6:
for (i = 24; i >= 0; i -= 8)
if (((u >> i) & 0x10) ||
(((u >> i) & 0x20) &&
(((u >> i) & 7) < 6))) {
/* BIOS 80-wire bit or
* UDMA w/ < 60ns/cycle
*/
vdev->via_80w |= (1 << (1 - (i >> 4)));
}
break;
}
}
/**
* init_chipset_via82cxxx - initialization handler
* @dev: PCI device
*
* The initialization callback. Here we determine the IDE chip type
* and initialize its drive independent registers.
*/
static int init_chipset_via82cxxx(struct pci_dev *dev)
{
struct ide_host *host = pci_get_drvdata(dev);
struct via82cxxx_dev *vdev = host->host_priv;
struct via_isa_bridge *via_config = vdev->via_config;
u8 t, v;
u32 u;
/*
* Detect cable and configure Clk66
*/
pci_read_config_dword(dev, VIA_UDMA_TIMING, &u);
via_cable_detect(vdev, u);
if (via_config->udma_mask == ATA_UDMA4) {
/* Enable Clk66 */
pci_write_config_dword(dev, VIA_UDMA_TIMING, u|0x80008);
} else if (via_config->flags & VIA_BAD_CLK66) {
/* Would cause trouble on 596a and 686 */
pci_write_config_dword(dev, VIA_UDMA_TIMING, u & ~0x80008);
}
/*
* Check whether interfaces are enabled.
*/
pci_read_config_byte(dev, VIA_IDE_ENABLE, &v);
/*
* Set up FIFO sizes and thresholds.
*/
pci_read_config_byte(dev, VIA_FIFO_CONFIG, &t);
/* Disable PREQ# till DDACK# */
if (via_config->flags & VIA_BAD_PREQ) {
/* Would crash on 586b rev 41 */
t &= 0x7f;
}
/* Fix FIFO split between channels */
if (via_config->flags & VIA_SET_FIFO) {
t &= (t & 0x9f);
switch (v & 3) {
case 2: t |= 0x00; break; /* 16 on primary */
case 1: t |= 0x60; break; /* 16 on secondary */
case 3: t |= 0x20; break; /* 8 pri 8 sec */
}
}
pci_write_config_byte(dev, VIA_FIFO_CONFIG, t);
return 0;
}
/*
* Cable special cases
*/
static const struct dmi_system_id cable_dmi_table[] = {
{
.ident = "Acer Ferrari 3400",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Acer,Inc."),
DMI_MATCH(DMI_BOARD_NAME, "Ferrari 3400"),
},
},
{ }
};
static int via_cable_override(struct pci_dev *pdev)
{
/* Systems by DMI */
if (dmi_check_system(cable_dmi_table))
return 1;
/* Arima W730-K8/Targa Visionary 811/... */
if (pdev->subsystem_vendor == 0x161F &&
pdev->subsystem_device == 0x2032)
return 1;
return 0;
}
static u8 via82cxxx_cable_detect(ide_hwif_t *hwif)
{
struct pci_dev *pdev = to_pci_dev(hwif->dev);
struct ide_host *host = pci_get_drvdata(pdev);
struct via82cxxx_dev *vdev = host->host_priv;
if (via_cable_override(pdev))
return ATA_CBL_PATA40_SHORT;
if ((vdev->via_config->flags & VIA_SATA_PATA) && hwif->channel == 0)
return ATA_CBL_SATA;
if ((vdev->via_80w >> hwif->channel) & 1)
return ATA_CBL_PATA80;
else
return ATA_CBL_PATA40;
}
static const struct ide_port_ops via_port_ops = {
.set_pio_mode = via_set_pio_mode,
.set_dma_mode = via_set_drive,
.cable_detect = via82cxxx_cable_detect,
};
static const struct ide_port_info via82cxxx_chipset __devinitdata = {
.name = DRV_NAME,
.init_chipset = init_chipset_via82cxxx,
.enablebits = { { 0x40, 0x02, 0x02 }, { 0x40, 0x01, 0x01 } },
.port_ops = &via_port_ops,
.host_flags = IDE_HFLAG_PIO_NO_BLACKLIST |
IDE_HFLAG_POST_SET_MODE |
IDE_HFLAG_IO_32BIT,
.pio_mask = ATA_PIO5,
.swdma_mask = ATA_SWDMA2,
.mwdma_mask = ATA_MWDMA2,
};
static int __devinit via_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
struct pci_dev *isa = NULL;
struct via_isa_bridge *via_config;
struct via82cxxx_dev *vdev;
int rc;
u8 idx = id->driver_data;
struct ide_port_info d;
d = via82cxxx_chipset;
/*
* Find the ISA bridge and check we know what it is.
*/
via_config = via_config_find(&isa);
/*
* Print the boot message.
*/
printk(KERN_INFO DRV_NAME " %s: VIA %s (rev %02x) IDE %sDMA%s\n",
pci_name(dev), via_config->name, isa->revision,
via_config->udma_mask ? "U" : "MW",
via_dma[via_config->udma_mask ?
(fls(via_config->udma_mask) - 1) : 0]);
pci_dev_put(isa);
/*
* Determine system bus clock.
*/
via_clock = (ide_pci_clk ? ide_pci_clk : 33) * 1000;
switch (via_clock) {
case 33000: via_clock = 33333; break;
case 37000: via_clock = 37500; break;
case 41000: via_clock = 41666; break;
}
if (via_clock < 20000 || via_clock > 50000) {
printk(KERN_WARNING DRV_NAME ": User given PCI clock speed "
"impossible (%d), using 33 MHz instead.\n", via_clock);
via_clock = 33333;
}
if (idx == 1)
d.enablebits[1].reg = d.enablebits[0].reg = 0;
else
d.host_flags |= IDE_HFLAG_NO_AUTODMA;
if (idx == VIA_IDFLAG_SINGLE)
d.host_flags |= IDE_HFLAG_SINGLE;
if ((via_config->flags & VIA_NO_UNMASK) == 0)
d.host_flags |= IDE_HFLAG_UNMASK_IRQS;
d.udma_mask = via_config->udma_mask;
vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
if (!vdev) {
printk(KERN_ERR DRV_NAME " %s: out of memory :(\n",
pci_name(dev));
return -ENOMEM;
}
vdev->via_config = via_config;
rc = ide_pci_init_one(dev, &d, vdev);
if (rc)
kfree(vdev);
return rc;
}
static void __devexit via_remove(struct pci_dev *dev)
{
struct ide_host *host = pci_get_drvdata(dev);
struct via82cxxx_dev *vdev = host->host_priv;
ide_pci_remove(dev);
kfree(vdev);
}
static const struct pci_device_id via_pci_tbl[] = {
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_82C576_1), 0 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_82C586_1), 0 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_CX700_IDE), 0 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_VX855_IDE), VIA_IDFLAG_SINGLE },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_6410), 1 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_6415), 1 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_SATA_EIDE), 1 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, via_pci_tbl);
static struct pci_driver via_pci_driver = {
.name = "VIA_IDE",
.id_table = via_pci_tbl,
.probe = via_init_one,
.remove = __devexit_p(via_remove),
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init via_ide_init(void)
{
return ide_pci_register_driver(&via_pci_driver);
}
static void __exit via_ide_exit(void)
{
pci_unregister_driver(&via_pci_driver);
}
module_init(via_ide_init);
module_exit(via_ide_exit);
MODULE_AUTHOR("Vojtech Pavlik, Bartlomiej Zolnierkiewicz, Michel Aubry, Jeff Garzik, Andre Hedrick");
MODULE_DESCRIPTION("PCI driver module for VIA IDE");
MODULE_LICENSE("GPL");
| gpl-2.0 |
CyanideL/android_kernel_samsung_klte | drivers/ide/via82cxxx.c | 8113 | 15093 | /*
* VIA IDE driver for Linux. Supported southbridges:
*
* vt82c576, vt82c586, vt82c586a, vt82c586b, vt82c596a, vt82c596b,
* vt82c686, vt82c686a, vt82c686b, vt8231, vt8233, vt8233c, vt8233a,
* vt8235, vt8237, vt8237a
*
* Copyright (c) 2000-2002 Vojtech Pavlik
* Copyright (c) 2007-2010 Bartlomiej Zolnierkiewicz
*
* Based on the work of:
* Michel Aubry
* Jeff Garzik
* Andre Hedrick
*
* Documentation:
* Obsolete device documentation publicly available from via.com.tw
* Current device documentation available under NDA only
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ide.h>
#include <linux/dmi.h>
#ifdef CONFIG_PPC_CHRP
#include <asm/processor.h>
#endif
#define DRV_NAME "via82cxxx"
#define VIA_IDE_ENABLE 0x40
#define VIA_IDE_CONFIG 0x41
#define VIA_FIFO_CONFIG 0x43
#define VIA_MISC_1 0x44
#define VIA_MISC_2 0x45
#define VIA_MISC_3 0x46
#define VIA_DRIVE_TIMING 0x48
#define VIA_8BIT_TIMING 0x4e
#define VIA_ADDRESS_SETUP 0x4c
#define VIA_UDMA_TIMING 0x50
#define VIA_BAD_PREQ 0x01 /* Crashes if PREQ# till DDACK# set */
#define VIA_BAD_CLK66 0x02 /* 66 MHz clock doesn't work correctly */
#define VIA_SET_FIFO 0x04 /* Needs to have FIFO split set */
#define VIA_NO_UNMASK 0x08 /* Doesn't work with IRQ unmasking on */
#define VIA_BAD_ID 0x10 /* Has wrong vendor ID (0x1107) */
#define VIA_BAD_AST 0x20 /* Don't touch Address Setup Timing */
#define VIA_SATA_PATA 0x80 /* SATA/PATA combined configuration */
enum {
VIA_IDFLAG_SINGLE = (1 << 1), /* single channel controller */
};
/*
* VIA SouthBridge chips.
*/
static struct via_isa_bridge {
char *name;
u16 id;
u8 rev_min;
u8 rev_max;
u8 udma_mask;
u8 flags;
} via_isa_bridges[] = {
{ "vx855", PCI_DEVICE_ID_VIA_VX855, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST | VIA_SATA_PATA },
{ "vx800", PCI_DEVICE_ID_VIA_VX800, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST | VIA_SATA_PATA },
{ "cx700", PCI_DEVICE_ID_VIA_CX700, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST | VIA_SATA_PATA },
{ "vt8261", PCI_DEVICE_ID_VIA_8261, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8237s", PCI_DEVICE_ID_VIA_8237S, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt6410", PCI_DEVICE_ID_VIA_6410, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt6415", PCI_DEVICE_ID_VIA_6415, 0x00, 0xff, ATA_UDMA6, VIA_BAD_AST },
{ "vt8251", PCI_DEVICE_ID_VIA_8251, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8237", PCI_DEVICE_ID_VIA_8237, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8237a", PCI_DEVICE_ID_VIA_8237A, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8235", PCI_DEVICE_ID_VIA_8235, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8233a", PCI_DEVICE_ID_VIA_8233A, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ "vt8233c", PCI_DEVICE_ID_VIA_8233C_0, 0x00, 0x2f, ATA_UDMA5, },
{ "vt8233", PCI_DEVICE_ID_VIA_8233_0, 0x00, 0x2f, ATA_UDMA5, },
{ "vt8231", PCI_DEVICE_ID_VIA_8231, 0x00, 0x2f, ATA_UDMA5, },
{ "vt82c686b", PCI_DEVICE_ID_VIA_82C686, 0x40, 0x4f, ATA_UDMA5, },
{ "vt82c686a", PCI_DEVICE_ID_VIA_82C686, 0x10, 0x2f, ATA_UDMA4, },
{ "vt82c686", PCI_DEVICE_ID_VIA_82C686, 0x00, 0x0f, ATA_UDMA2, VIA_BAD_CLK66 },
{ "vt82c596b", PCI_DEVICE_ID_VIA_82C596, 0x10, 0x2f, ATA_UDMA4, },
{ "vt82c596a", PCI_DEVICE_ID_VIA_82C596, 0x00, 0x0f, ATA_UDMA2, VIA_BAD_CLK66 },
{ "vt82c586b", PCI_DEVICE_ID_VIA_82C586_0, 0x47, 0x4f, ATA_UDMA2, VIA_SET_FIFO },
{ "vt82c586b", PCI_DEVICE_ID_VIA_82C586_0, 0x40, 0x46, ATA_UDMA2, VIA_SET_FIFO | VIA_BAD_PREQ },
{ "vt82c586b", PCI_DEVICE_ID_VIA_82C586_0, 0x30, 0x3f, ATA_UDMA2, VIA_SET_FIFO },
{ "vt82c586a", PCI_DEVICE_ID_VIA_82C586_0, 0x20, 0x2f, ATA_UDMA2, VIA_SET_FIFO },
{ "vt82c586", PCI_DEVICE_ID_VIA_82C586_0, 0x00, 0x0f, 0x00, VIA_SET_FIFO },
{ "vt82c576", PCI_DEVICE_ID_VIA_82C576, 0x00, 0x2f, 0x00, VIA_SET_FIFO | VIA_NO_UNMASK },
{ "vt82c576", PCI_DEVICE_ID_VIA_82C576, 0x00, 0x2f, 0x00, VIA_SET_FIFO | VIA_NO_UNMASK | VIA_BAD_ID },
{ "vtxxxx", PCI_DEVICE_ID_VIA_ANON, 0x00, 0x2f, ATA_UDMA6, VIA_BAD_AST },
{ NULL }
};
static unsigned int via_clock;
static char *via_dma[] = { "16", "25", "33", "44", "66", "100", "133" };
struct via82cxxx_dev
{
struct via_isa_bridge *via_config;
unsigned int via_80w;
};
/**
* via_set_speed - write timing registers
* @dev: PCI device
* @dn: device
* @timing: IDE timing data to use
*
* via_set_speed writes timing values to the chipset registers
*/
static void via_set_speed(ide_hwif_t *hwif, u8 dn, struct ide_timing *timing)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct ide_host *host = pci_get_drvdata(dev);
struct via82cxxx_dev *vdev = host->host_priv;
u8 t;
if (~vdev->via_config->flags & VIA_BAD_AST) {
pci_read_config_byte(dev, VIA_ADDRESS_SETUP, &t);
t = (t & ~(3 << ((3 - dn) << 1))) | ((clamp_val(timing->setup, 1, 4) - 1) << ((3 - dn) << 1));
pci_write_config_byte(dev, VIA_ADDRESS_SETUP, t);
}
pci_write_config_byte(dev, VIA_8BIT_TIMING + (1 - (dn >> 1)),
((clamp_val(timing->act8b, 1, 16) - 1) << 4) | (clamp_val(timing->rec8b, 1, 16) - 1));
pci_write_config_byte(dev, VIA_DRIVE_TIMING + (3 - dn),
((clamp_val(timing->active, 1, 16) - 1) << 4) | (clamp_val(timing->recover, 1, 16) - 1));
switch (vdev->via_config->udma_mask) {
case ATA_UDMA2: t = timing->udma ? (0xe0 | (clamp_val(timing->udma, 2, 5) - 2)) : 0x03; break;
case ATA_UDMA4: t = timing->udma ? (0xe8 | (clamp_val(timing->udma, 2, 9) - 2)) : 0x0f; break;
case ATA_UDMA5: t = timing->udma ? (0xe0 | (clamp_val(timing->udma, 2, 9) - 2)) : 0x07; break;
case ATA_UDMA6: t = timing->udma ? (0xe0 | (clamp_val(timing->udma, 2, 9) - 2)) : 0x07; break;
}
/* Set UDMA unless device is not UDMA capable */
if (vdev->via_config->udma_mask) {
u8 udma_etc;
pci_read_config_byte(dev, VIA_UDMA_TIMING + 3 - dn, &udma_etc);
/* clear transfer mode bit */
udma_etc &= ~0x20;
if (timing->udma) {
/* preserve 80-wire cable detection bit */
udma_etc &= 0x10;
udma_etc |= t;
}
pci_write_config_byte(dev, VIA_UDMA_TIMING + 3 - dn, udma_etc);
}
}
/**
* via_set_drive - configure transfer mode
* @hwif: port
* @drive: Drive to set up
*
* via_set_drive() computes timing values configures the chipset to
* a desired transfer mode. It also can be called by upper layers.
*/
static void via_set_drive(ide_hwif_t *hwif, ide_drive_t *drive)
{
ide_drive_t *peer = ide_get_pair_dev(drive);
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct ide_host *host = pci_get_drvdata(dev);
struct via82cxxx_dev *vdev = host->host_priv;
struct ide_timing t, p;
unsigned int T, UT;
const u8 speed = drive->dma_mode;
T = 1000000000 / via_clock;
switch (vdev->via_config->udma_mask) {
case ATA_UDMA2: UT = T; break;
case ATA_UDMA4: UT = T/2; break;
case ATA_UDMA5: UT = T/3; break;
case ATA_UDMA6: UT = T/4; break;
default: UT = T;
}
ide_timing_compute(drive, speed, &t, T, UT);
if (peer) {
ide_timing_compute(peer, peer->pio_mode, &p, T, UT);
ide_timing_merge(&p, &t, &t, IDE_TIMING_8BIT);
}
via_set_speed(hwif, drive->dn, &t);
}
/**
* via_set_pio_mode - set host controller for PIO mode
* @hwif: port
* @drive: drive
*
* A callback from the upper layers for PIO-only tuning.
*/
static void via_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
drive->dma_mode = drive->pio_mode;
via_set_drive(hwif, drive);
}
static struct via_isa_bridge *via_config_find(struct pci_dev **isa)
{
struct via_isa_bridge *via_config;
for (via_config = via_isa_bridges;
via_config->id != PCI_DEVICE_ID_VIA_ANON; via_config++)
if ((*isa = pci_get_device(PCI_VENDOR_ID_VIA +
!!(via_config->flags & VIA_BAD_ID),
via_config->id, NULL))) {
if ((*isa)->revision >= via_config->rev_min &&
(*isa)->revision <= via_config->rev_max)
break;
pci_dev_put(*isa);
}
return via_config;
}
/*
* Check and handle 80-wire cable presence
*/
static void via_cable_detect(struct via82cxxx_dev *vdev, u32 u)
{
int i;
switch (vdev->via_config->udma_mask) {
case ATA_UDMA4:
for (i = 24; i >= 0; i -= 8)
if (((u >> (i & 16)) & 8) &&
((u >> i) & 0x20) &&
(((u >> i) & 7) < 2)) {
/*
* 2x PCI clock and
* UDMA w/ < 3T/cycle
*/
vdev->via_80w |= (1 << (1 - (i >> 4)));
}
break;
case ATA_UDMA5:
for (i = 24; i >= 0; i -= 8)
if (((u >> i) & 0x10) ||
(((u >> i) & 0x20) &&
(((u >> i) & 7) < 4))) {
/* BIOS 80-wire bit or
* UDMA w/ < 60ns/cycle
*/
vdev->via_80w |= (1 << (1 - (i >> 4)));
}
break;
case ATA_UDMA6:
for (i = 24; i >= 0; i -= 8)
if (((u >> i) & 0x10) ||
(((u >> i) & 0x20) &&
(((u >> i) & 7) < 6))) {
/* BIOS 80-wire bit or
* UDMA w/ < 60ns/cycle
*/
vdev->via_80w |= (1 << (1 - (i >> 4)));
}
break;
}
}
/**
* init_chipset_via82cxxx - initialization handler
* @dev: PCI device
*
* The initialization callback. Here we determine the IDE chip type
* and initialize its drive independent registers.
*/
static int init_chipset_via82cxxx(struct pci_dev *dev)
{
struct ide_host *host = pci_get_drvdata(dev);
struct via82cxxx_dev *vdev = host->host_priv;
struct via_isa_bridge *via_config = vdev->via_config;
u8 t, v;
u32 u;
/*
* Detect cable and configure Clk66
*/
pci_read_config_dword(dev, VIA_UDMA_TIMING, &u);
via_cable_detect(vdev, u);
if (via_config->udma_mask == ATA_UDMA4) {
/* Enable Clk66 */
pci_write_config_dword(dev, VIA_UDMA_TIMING, u|0x80008);
} else if (via_config->flags & VIA_BAD_CLK66) {
/* Would cause trouble on 596a and 686 */
pci_write_config_dword(dev, VIA_UDMA_TIMING, u & ~0x80008);
}
/*
* Check whether interfaces are enabled.
*/
pci_read_config_byte(dev, VIA_IDE_ENABLE, &v);
/*
* Set up FIFO sizes and thresholds.
*/
pci_read_config_byte(dev, VIA_FIFO_CONFIG, &t);
/* Disable PREQ# till DDACK# */
if (via_config->flags & VIA_BAD_PREQ) {
/* Would crash on 586b rev 41 */
t &= 0x7f;
}
/* Fix FIFO split between channels */
if (via_config->flags & VIA_SET_FIFO) {
t &= (t & 0x9f);
switch (v & 3) {
case 2: t |= 0x00; break; /* 16 on primary */
case 1: t |= 0x60; break; /* 16 on secondary */
case 3: t |= 0x20; break; /* 8 pri 8 sec */
}
}
pci_write_config_byte(dev, VIA_FIFO_CONFIG, t);
return 0;
}
/*
* Cable special cases
*/
static const struct dmi_system_id cable_dmi_table[] = {
{
.ident = "Acer Ferrari 3400",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Acer,Inc."),
DMI_MATCH(DMI_BOARD_NAME, "Ferrari 3400"),
},
},
{ }
};
static int via_cable_override(struct pci_dev *pdev)
{
/* Systems by DMI */
if (dmi_check_system(cable_dmi_table))
return 1;
/* Arima W730-K8/Targa Visionary 811/... */
if (pdev->subsystem_vendor == 0x161F &&
pdev->subsystem_device == 0x2032)
return 1;
return 0;
}
static u8 via82cxxx_cable_detect(ide_hwif_t *hwif)
{
struct pci_dev *pdev = to_pci_dev(hwif->dev);
struct ide_host *host = pci_get_drvdata(pdev);
struct via82cxxx_dev *vdev = host->host_priv;
if (via_cable_override(pdev))
return ATA_CBL_PATA40_SHORT;
if ((vdev->via_config->flags & VIA_SATA_PATA) && hwif->channel == 0)
return ATA_CBL_SATA;
if ((vdev->via_80w >> hwif->channel) & 1)
return ATA_CBL_PATA80;
else
return ATA_CBL_PATA40;
}
static const struct ide_port_ops via_port_ops = {
.set_pio_mode = via_set_pio_mode,
.set_dma_mode = via_set_drive,
.cable_detect = via82cxxx_cable_detect,
};
static const struct ide_port_info via82cxxx_chipset __devinitdata = {
.name = DRV_NAME,
.init_chipset = init_chipset_via82cxxx,
.enablebits = { { 0x40, 0x02, 0x02 }, { 0x40, 0x01, 0x01 } },
.port_ops = &via_port_ops,
.host_flags = IDE_HFLAG_PIO_NO_BLACKLIST |
IDE_HFLAG_POST_SET_MODE |
IDE_HFLAG_IO_32BIT,
.pio_mask = ATA_PIO5,
.swdma_mask = ATA_SWDMA2,
.mwdma_mask = ATA_MWDMA2,
};
static int __devinit via_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
struct pci_dev *isa = NULL;
struct via_isa_bridge *via_config;
struct via82cxxx_dev *vdev;
int rc;
u8 idx = id->driver_data;
struct ide_port_info d;
d = via82cxxx_chipset;
/*
* Find the ISA bridge and check we know what it is.
*/
via_config = via_config_find(&isa);
/*
* Print the boot message.
*/
printk(KERN_INFO DRV_NAME " %s: VIA %s (rev %02x) IDE %sDMA%s\n",
pci_name(dev), via_config->name, isa->revision,
via_config->udma_mask ? "U" : "MW",
via_dma[via_config->udma_mask ?
(fls(via_config->udma_mask) - 1) : 0]);
pci_dev_put(isa);
/*
* Determine system bus clock.
*/
via_clock = (ide_pci_clk ? ide_pci_clk : 33) * 1000;
switch (via_clock) {
case 33000: via_clock = 33333; break;
case 37000: via_clock = 37500; break;
case 41000: via_clock = 41666; break;
}
if (via_clock < 20000 || via_clock > 50000) {
printk(KERN_WARNING DRV_NAME ": User given PCI clock speed "
"impossible (%d), using 33 MHz instead.\n", via_clock);
via_clock = 33333;
}
if (idx == 1)
d.enablebits[1].reg = d.enablebits[0].reg = 0;
else
d.host_flags |= IDE_HFLAG_NO_AUTODMA;
if (idx == VIA_IDFLAG_SINGLE)
d.host_flags |= IDE_HFLAG_SINGLE;
if ((via_config->flags & VIA_NO_UNMASK) == 0)
d.host_flags |= IDE_HFLAG_UNMASK_IRQS;
d.udma_mask = via_config->udma_mask;
vdev = kzalloc(sizeof(*vdev), GFP_KERNEL);
if (!vdev) {
printk(KERN_ERR DRV_NAME " %s: out of memory :(\n",
pci_name(dev));
return -ENOMEM;
}
vdev->via_config = via_config;
rc = ide_pci_init_one(dev, &d, vdev);
if (rc)
kfree(vdev);
return rc;
}
static void __devexit via_remove(struct pci_dev *dev)
{
struct ide_host *host = pci_get_drvdata(dev);
struct via82cxxx_dev *vdev = host->host_priv;
ide_pci_remove(dev);
kfree(vdev);
}
static const struct pci_device_id via_pci_tbl[] = {
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_82C576_1), 0 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_82C586_1), 0 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_CX700_IDE), 0 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_VX855_IDE), VIA_IDFLAG_SINGLE },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_6410), 1 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_6415), 1 },
{ PCI_VDEVICE(VIA, PCI_DEVICE_ID_VIA_SATA_EIDE), 1 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, via_pci_tbl);
static struct pci_driver via_pci_driver = {
.name = "VIA_IDE",
.id_table = via_pci_tbl,
.probe = via_init_one,
.remove = __devexit_p(via_remove),
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init via_ide_init(void)
{
return ide_pci_register_driver(&via_pci_driver);
}
static void __exit via_ide_exit(void)
{
pci_unregister_driver(&via_pci_driver);
}
module_init(via_ide_init);
module_exit(via_ide_exit);
MODULE_AUTHOR("Vojtech Pavlik, Bartlomiej Zolnierkiewicz, Michel Aubry, Jeff Garzik, Andre Hedrick");
MODULE_DESCRIPTION("PCI driver module for VIA IDE");
MODULE_LICENSE("GPL");
| gpl-2.0 |
zhuoyang/android_kernel_sony_msm8974 | drivers/staging/vt6655/mac.c | 8369 | 44114 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*
* File: mac.c
*
* Purpose: MAC routines
*
* Author: Tevin Chen
*
* Date: May 21, 1996
*
* Functions:
* MACvReadAllRegs - Read All MAC Registers to buffer
* MACbIsRegBitsOn - Test if All test Bits On
* MACbIsRegBitsOff - Test if All test Bits Off
* MACbIsIntDisable - Test if MAC interrupt disable
* MACbyReadMultiAddr - Read Multicast Address Mask Pattern
* MACvWriteMultiAddr - Write Multicast Address Mask Pattern
* MACvSetMultiAddrByHash - Set Multicast Address Mask by Hash value
* MACvResetMultiAddrByHash - Clear Multicast Address Mask by Hash value
* MACvSetRxThreshold - Set Rx Threshold value
* MACvGetRxThreshold - Get Rx Threshold value
* MACvSetTxThreshold - Set Tx Threshold value
* MACvGetTxThreshold - Get Tx Threshold value
* MACvSetDmaLength - Set Dma Length value
* MACvGetDmaLength - Get Dma Length value
* MACvSetShortRetryLimit - Set 802.11 Short Retry limit
* MACvGetShortRetryLimit - Get 802.11 Short Retry limit
* MACvSetLongRetryLimit - Set 802.11 Long Retry limit
* MACvGetLongRetryLimit - Get 802.11 Long Retry limit
* MACvSetLoopbackMode - Set MAC Loopback Mode
* MACbIsInLoopbackMode - Test if MAC in Loopback mode
* MACvSetPacketFilter - Set MAC Address Filter
* MACvSaveContext - Save Context of MAC Registers
* MACvRestoreContext - Restore Context of MAC Registers
* MACbCompareContext - Compare if values of MAC Registers same as Context
* MACbSoftwareReset - Software Reset MAC
* MACbSafeRxOff - Turn Off MAC Rx
* MACbSafeTxOff - Turn Off MAC Tx
* MACbSafeStop - Stop MAC function
* MACbShutdown - Shut down MAC
* MACvInitialize - Initialize MAC
* MACvSetCurrRxDescAddr - Set Rx Descriptos Address
* MACvSetCurrTx0DescAddr - Set Tx0 Descriptos Address
* MACvSetCurrTx1DescAddr - Set Tx1 Descriptos Address
* MACvTimer0MicroSDelay - Micro Second Delay Loop by MAC
*
* Revision History:
* 08-22-2003 Kyle Hsu : Porting MAC functions from sim53
* 09-03-2003 Bryan YC Fan : Add MACvClearBusSusInd()& MACvEnableBusSusEn()
* 09-18-2003 Jerry Chen : Add MACvSetKeyEntry & MACvDisableKeyEntry
*
*/
#include "tmacro.h"
#include "tether.h"
#include "mac.h"
unsigned short TxRate_iwconfig;//2008-5-8 <add> by chester
/*--------------------- Static Definitions -------------------------*/
//static int msglevel =MSG_LEVEL_DEBUG;
static int msglevel =MSG_LEVEL_INFO;
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
/*--------------------- Static Functions --------------------------*/
/*--------------------- Export Variables --------------------------*/
/*--------------------- Export Functions --------------------------*/
/*
* Description:
* Read All MAC Registers to buffer
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyMacRegs - buffer to read
*
* Return Value: none
*
*/
void MACvReadAllRegs (unsigned long dwIoBase, unsigned char *pbyMacRegs)
{
int ii;
// read page0 register
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE0; ii++) {
VNSvInPortB(dwIoBase + ii, pbyMacRegs);
pbyMacRegs++;
}
MACvSelectPage1(dwIoBase);
// read page1 register
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE1; ii++) {
VNSvInPortB(dwIoBase + ii, pbyMacRegs);
pbyMacRegs++;
}
MACvSelectPage0(dwIoBase);
}
/*
* Description:
* Test if all test bits on
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byRegOfs - Offset of MAC Register
* byTestBits - Test bits
* Out:
* none
*
* Return Value: true if all test bits On; otherwise false
*
*/
bool MACbIsRegBitsOn (unsigned long dwIoBase, unsigned char byRegOfs, unsigned char byTestBits)
{
unsigned char byData;
VNSvInPortB(dwIoBase + byRegOfs, &byData);
return (byData & byTestBits) == byTestBits;
}
/*
* Description:
* Test if all test bits off
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byRegOfs - Offset of MAC Register
* byTestBits - Test bits
* Out:
* none
*
* Return Value: true if all test bits Off; otherwise false
*
*/
bool MACbIsRegBitsOff (unsigned long dwIoBase, unsigned char byRegOfs, unsigned char byTestBits)
{
unsigned char byData;
VNSvInPortB(dwIoBase + byRegOfs, &byData);
return !(byData & byTestBits);
}
/*
* Description:
* Test if MAC interrupt disable
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if interrupt is disable; otherwise false
*
*/
bool MACbIsIntDisable (unsigned long dwIoBase)
{
unsigned long dwData;
VNSvInPortD(dwIoBase + MAC_REG_IMR, &dwData);
if (dwData != 0)
return false;
return true;
}
/*
* Description:
* Read MAC Multicast Address Mask
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uByteidx - Index of Mask
* Out:
* none
*
* Return Value: Mask Value read
*
*/
unsigned char MACbyReadMultiAddr (unsigned long dwIoBase, unsigned int uByteIdx)
{
unsigned char byData;
MACvSelectPage1(dwIoBase);
VNSvInPortB(dwIoBase + MAC_REG_MAR0 + uByteIdx, &byData);
MACvSelectPage0(dwIoBase);
return byData;
}
/*
* Description:
* Write MAC Multicast Address Mask
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uByteidx - Index of Mask
* byData - Mask Value to write
* Out:
* none
*
* Return Value: none
*
*/
void MACvWriteMultiAddr (unsigned long dwIoBase, unsigned int uByteIdx, unsigned char byData)
{
MACvSelectPage1(dwIoBase);
VNSvOutPortB(dwIoBase + MAC_REG_MAR0 + uByteIdx, byData);
MACvSelectPage0(dwIoBase);
}
/*
* Description:
* Set this hash index into multicast address register bit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byHashIdx - Hash index to set
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetMultiAddrByHash (unsigned long dwIoBase, unsigned char byHashIdx)
{
unsigned int uByteIdx;
unsigned char byBitMask;
unsigned char byOrgValue;
// calculate byte position
uByteIdx = byHashIdx / 8;
ASSERT(uByteIdx < 8);
// calculate bit position
byBitMask = 1;
byBitMask <<= (byHashIdx % 8);
// turn on the bit
byOrgValue = MACbyReadMultiAddr(dwIoBase, uByteIdx);
MACvWriteMultiAddr(dwIoBase, uByteIdx, (unsigned char)(byOrgValue | byBitMask));
}
/*
* Description:
* Reset this hash index into multicast address register bit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byHashIdx - Hash index to clear
* Out:
* none
*
* Return Value: none
*
*/
void MACvResetMultiAddrByHash (unsigned long dwIoBase, unsigned char byHashIdx)
{
unsigned int uByteIdx;
unsigned char byBitMask;
unsigned char byOrgValue;
// calculate byte position
uByteIdx = byHashIdx / 8;
ASSERT(uByteIdx < 8);
// calculate bit position
byBitMask = 1;
byBitMask <<= (byHashIdx % 8);
// turn off the bit
byOrgValue = MACbyReadMultiAddr(dwIoBase, uByteIdx);
MACvWriteMultiAddr(dwIoBase, uByteIdx, (unsigned char)(byOrgValue & (~byBitMask)));
}
/*
* Description:
* Set Rx Threshold
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byThreshold - Threshold Value
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetRxThreshold (unsigned long dwIoBase, unsigned char byThreshold)
{
unsigned char byOrgValue;
ASSERT(byThreshold < 4);
// set FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, &byOrgValue);
byOrgValue = (byOrgValue & 0xCF) | (byThreshold << 4);
VNSvOutPortB(dwIoBase + MAC_REG_FCR0, byOrgValue);
}
/*
* Description:
* Get Rx Threshold
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyThreshold- Threshold Value Get
*
* Return Value: none
*
*/
void MACvGetRxThreshold (unsigned long dwIoBase, unsigned char *pbyThreshold)
{
// get FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, pbyThreshold);
*pbyThreshold = (*pbyThreshold >> 4) & 0x03;
}
/*
* Description:
* Set Tx Threshold
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byThreshold - Threshold Value
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetTxThreshold (unsigned long dwIoBase, unsigned char byThreshold)
{
unsigned char byOrgValue;
ASSERT(byThreshold < 4);
// set FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, &byOrgValue);
byOrgValue = (byOrgValue & 0xF3) | (byThreshold << 2);
VNSvOutPortB(dwIoBase + MAC_REG_FCR0, byOrgValue);
}
/*
* Description:
* Get Tx Threshold
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyThreshold- Threshold Value Get
*
* Return Value: none
*
*/
void MACvGetTxThreshold (unsigned long dwIoBase, unsigned char *pbyThreshold)
{
// get FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, pbyThreshold);
*pbyThreshold = (*pbyThreshold >> 2) & 0x03;
}
/*
* Description:
* Set Dma Length
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byDmaLength - Dma Length Value
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetDmaLength (unsigned long dwIoBase, unsigned char byDmaLength)
{
unsigned char byOrgValue;
ASSERT(byDmaLength < 4);
// set FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, &byOrgValue);
byOrgValue = (byOrgValue & 0xFC) | byDmaLength;
VNSvOutPortB(dwIoBase + MAC_REG_FCR0, byOrgValue);
}
/*
* Description:
* Get Dma Length
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyDmaLength- Dma Length Value Get
*
* Return Value: none
*
*/
void MACvGetDmaLength (unsigned long dwIoBase, unsigned char *pbyDmaLength)
{
// get FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, pbyDmaLength);
*pbyDmaLength &= 0x03;
}
/*
* Description:
* Set 802.11 Short Retry Limit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byRetryLimit- Retry Limit
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetShortRetryLimit (unsigned long dwIoBase, unsigned char byRetryLimit)
{
// set SRT
VNSvOutPortB(dwIoBase + MAC_REG_SRT, byRetryLimit);
}
/*
* Description:
* Get 802.11 Short Retry Limit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyRetryLimit - Retry Limit Get
*
* Return Value: none
*
*/
void MACvGetShortRetryLimit (unsigned long dwIoBase, unsigned char *pbyRetryLimit)
{
// get SRT
VNSvInPortB(dwIoBase + MAC_REG_SRT, pbyRetryLimit);
}
/*
* Description:
* Set 802.11 Long Retry Limit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byRetryLimit- Retry Limit
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetLongRetryLimit (unsigned long dwIoBase, unsigned char byRetryLimit)
{
// set LRT
VNSvOutPortB(dwIoBase + MAC_REG_LRT, byRetryLimit);
}
/*
* Description:
* Get 802.11 Long Retry Limit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyRetryLimit - Retry Limit Get
*
* Return Value: none
*
*/
void MACvGetLongRetryLimit (unsigned long dwIoBase, unsigned char *pbyRetryLimit)
{
// get LRT
VNSvInPortB(dwIoBase + MAC_REG_LRT, pbyRetryLimit);
}
/*
* Description:
* Set MAC Loopback mode
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byLoopbackMode - Loopback Mode
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetLoopbackMode (unsigned long dwIoBase, unsigned char byLoopbackMode)
{
unsigned char byOrgValue;
ASSERT(byLoopbackMode < 3);
byLoopbackMode <<= 6;
// set TCR
VNSvInPortB(dwIoBase + MAC_REG_TEST, &byOrgValue);
byOrgValue = byOrgValue & 0x3F;
byOrgValue = byOrgValue | byLoopbackMode;
VNSvOutPortB(dwIoBase + MAC_REG_TEST, byOrgValue);
}
/*
* Description:
* Test if MAC in Loopback mode
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if in Loopback mode; otherwise false
*
*/
bool MACbIsInLoopbackMode (unsigned long dwIoBase)
{
unsigned char byOrgValue;
VNSvInPortB(dwIoBase + MAC_REG_TEST, &byOrgValue);
if (byOrgValue & (TEST_LBINT | TEST_LBEXT))
return true;
return false;
}
/*
* Description:
* Set MAC Address filter
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* wFilterType - Filter Type
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetPacketFilter (unsigned long dwIoBase, unsigned short wFilterType)
{
unsigned char byOldRCR;
unsigned char byNewRCR = 0;
// if only in DIRECTED mode, multicast-address will set to zero,
// but if other mode exist (e.g. PROMISCUOUS), multicast-address
// will be open
if (wFilterType & PKT_TYPE_DIRECTED) {
// set multicast address to accept none
MACvSelectPage1(dwIoBase);
VNSvOutPortD(dwIoBase + MAC_REG_MAR0, 0L);
VNSvOutPortD(dwIoBase + MAC_REG_MAR0 + sizeof(unsigned long), 0L);
MACvSelectPage0(dwIoBase);
}
if (wFilterType & (PKT_TYPE_PROMISCUOUS | PKT_TYPE_ALL_MULTICAST)) {
// set multicast address to accept all
MACvSelectPage1(dwIoBase);
VNSvOutPortD(dwIoBase + MAC_REG_MAR0, 0xFFFFFFFFL);
VNSvOutPortD(dwIoBase + MAC_REG_MAR0 + sizeof(unsigned long), 0xFFFFFFFFL);
MACvSelectPage0(dwIoBase);
}
if (wFilterType & PKT_TYPE_PROMISCUOUS) {
byNewRCR |= (RCR_RXALLTYPE | RCR_UNICAST | RCR_MULTICAST | RCR_BROADCAST);
byNewRCR &= ~RCR_BSSID;
}
if (wFilterType & (PKT_TYPE_ALL_MULTICAST | PKT_TYPE_MULTICAST))
byNewRCR |= RCR_MULTICAST;
if (wFilterType & PKT_TYPE_BROADCAST)
byNewRCR |= RCR_BROADCAST;
if (wFilterType & PKT_TYPE_ERROR_CRC)
byNewRCR |= RCR_ERRCRC;
VNSvInPortB(dwIoBase + MAC_REG_RCR, &byOldRCR);
if (byNewRCR != byOldRCR) {
// Modify the Receive Command Register
VNSvOutPortB(dwIoBase + MAC_REG_RCR, byNewRCR);
}
}
/*
* Description:
* Save MAC registers to context buffer
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyCxtBuf - Context buffer
*
* Return Value: none
*
*/
void MACvSaveContext (unsigned long dwIoBase, unsigned char *pbyCxtBuf)
{
int ii;
// read page0 register
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE0; ii++) {
VNSvInPortB((dwIoBase + ii), (pbyCxtBuf + ii));
}
MACvSelectPage1(dwIoBase);
// read page1 register
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE1; ii++) {
VNSvInPortB((dwIoBase + ii), (pbyCxtBuf + MAC_MAX_CONTEXT_SIZE_PAGE0 + ii));
}
MACvSelectPage0(dwIoBase);
}
/*
* Description:
* Restore MAC registers from context buffer
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* pbyCxtBuf - Context buffer
* Out:
* none
*
* Return Value: none
*
*/
void MACvRestoreContext (unsigned long dwIoBase, unsigned char *pbyCxtBuf)
{
int ii;
MACvSelectPage1(dwIoBase);
// restore page1
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE1; ii++) {
VNSvOutPortB((dwIoBase + ii), *(pbyCxtBuf + MAC_MAX_CONTEXT_SIZE_PAGE0 + ii));
}
MACvSelectPage0(dwIoBase);
// restore RCR,TCR,IMR...
for (ii = MAC_REG_RCR; ii < MAC_REG_ISR; ii++) {
VNSvOutPortB(dwIoBase + ii, *(pbyCxtBuf + ii));
}
// restore MAC Config.
for (ii = MAC_REG_LRT; ii < MAC_REG_PAGE1SEL; ii++) {
VNSvOutPortB(dwIoBase + ii, *(pbyCxtBuf + ii));
}
VNSvOutPortB(dwIoBase + MAC_REG_CFG, *(pbyCxtBuf + MAC_REG_CFG));
// restore PS Config.
for (ii = MAC_REG_PSCFG; ii < MAC_REG_BBREGCTL; ii++) {
VNSvOutPortB(dwIoBase + ii, *(pbyCxtBuf + ii));
}
// restore CURR_RX_DESC_ADDR, CURR_TX_DESC_ADDR
VNSvOutPortD(dwIoBase + MAC_REG_TXDMAPTR0, *(unsigned long *)(pbyCxtBuf + MAC_REG_TXDMAPTR0));
VNSvOutPortD(dwIoBase + MAC_REG_AC0DMAPTR, *(unsigned long *)(pbyCxtBuf + MAC_REG_AC0DMAPTR));
VNSvOutPortD(dwIoBase + MAC_REG_BCNDMAPTR, *(unsigned long *)(pbyCxtBuf + MAC_REG_BCNDMAPTR));
VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR0, *(unsigned long *)(pbyCxtBuf + MAC_REG_RXDMAPTR0));
VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR1, *(unsigned long *)(pbyCxtBuf + MAC_REG_RXDMAPTR1));
}
/*
* Description:
* Compare if MAC registers same as context buffer
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* pbyCxtBuf - Context buffer
* Out:
* none
*
* Return Value: true if all values are the same; otherwise false
*
*/
bool MACbCompareContext (unsigned long dwIoBase, unsigned char *pbyCxtBuf)
{
unsigned long dwData;
// compare MAC context to determine if this is a power lost init,
// return true for power remaining init, return false for power lost init
// compare CURR_RX_DESC_ADDR, CURR_TX_DESC_ADDR
VNSvInPortD(dwIoBase + MAC_REG_TXDMAPTR0, &dwData);
if (dwData != *(unsigned long *)(pbyCxtBuf + MAC_REG_TXDMAPTR0)) {
return false;
}
VNSvInPortD(dwIoBase + MAC_REG_AC0DMAPTR, &dwData);
if (dwData != *(unsigned long *)(pbyCxtBuf + MAC_REG_AC0DMAPTR)) {
return false;
}
VNSvInPortD(dwIoBase + MAC_REG_RXDMAPTR0, &dwData);
if (dwData != *(unsigned long *)(pbyCxtBuf + MAC_REG_RXDMAPTR0)) {
return false;
}
VNSvInPortD(dwIoBase + MAC_REG_RXDMAPTR1, &dwData);
if (dwData != *(unsigned long *)(pbyCxtBuf + MAC_REG_RXDMAPTR1)) {
return false;
}
return true;
}
/*
* Description:
* Software Reset MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if Reset Success; otherwise false
*
*/
bool MACbSoftwareReset (unsigned long dwIoBase)
{
unsigned char byData;
unsigned short ww;
// turn on HOSTCR_SOFTRST, just write 0x01 to reset
//MACvRegBitsOn(dwIoBase, MAC_REG_HOSTCR, HOSTCR_SOFTRST);
VNSvOutPortB(dwIoBase+ MAC_REG_HOSTCR, 0x01);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_HOSTCR, &byData);
if ( !(byData & HOSTCR_SOFTRST))
break;
}
if (ww == W_MAX_TIMEOUT)
return false;
return true;
}
/*
* Description:
* save some important register's value, then do reset, then restore register's value
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbSafeSoftwareReset (unsigned long dwIoBase)
{
unsigned char abyTmpRegData[MAC_MAX_CONTEXT_SIZE_PAGE0+MAC_MAX_CONTEXT_SIZE_PAGE1];
bool bRetVal;
// PATCH....
// save some important register's value, then do
// reset, then restore register's value
// save MAC context
MACvSaveContext(dwIoBase, abyTmpRegData);
// do reset
bRetVal = MACbSoftwareReset(dwIoBase);
//BBvSoftwareReset(pDevice->PortOffset);
// restore MAC context, except CR0
MACvRestoreContext(dwIoBase, abyTmpRegData);
return bRetVal;
}
/*
* Description:
* Trun Off MAC Rx
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbSafeRxOff (unsigned long dwIoBase)
{
unsigned short ww;
unsigned long dwData;
unsigned char byData;
// turn off wow temp for turn off Rx safely
// Clear RX DMA0,1
VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL0, DMACTL_CLRRUN);
VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL1, DMACTL_CLRRUN);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_RXDMACTL0, &dwData);
if (!(dwData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x10);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x10)\n");
return(false);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_RXDMACTL1, &dwData);
if ( !(dwData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x11);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x11)\n");
return(false);
}
// try to safe shutdown RX
MACvRegBitsOff(dwIoBase, MAC_REG_HOSTCR, HOSTCR_RXON);
// W_MAX_TIMEOUT is the timeout period
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_HOSTCR, &byData);
if ( !(byData & HOSTCR_RXONST))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x12);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x12)\n");
return(false);
}
return true;
}
/*
* Description:
* Trun Off MAC Tx
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbSafeTxOff (unsigned long dwIoBase)
{
unsigned short ww;
unsigned long dwData;
unsigned char byData;
// Clear TX DMA
//Tx0
VNSvOutPortD(dwIoBase + MAC_REG_TXDMACTL0, DMACTL_CLRRUN);
//AC0
VNSvOutPortD(dwIoBase + MAC_REG_AC0DMACTL, DMACTL_CLRRUN);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_TXDMACTL0, &dwData);
if ( !(dwData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x20);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x20)\n");
return(false);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_AC0DMACTL, &dwData);
if ( !(dwData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x21);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x21)\n");
return(false);
}
// try to safe shutdown TX
MACvRegBitsOff(dwIoBase, MAC_REG_HOSTCR, HOSTCR_TXON);
// W_MAX_TIMEOUT is the timeout period
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_HOSTCR, &byData);
if ( !(byData & HOSTCR_TXONST))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x24);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x24)\n");
return(false);
}
return true;
}
/*
* Description:
* Stop MAC function
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbSafeStop (unsigned long dwIoBase)
{
MACvRegBitsOff(dwIoBase, MAC_REG_TCR, TCR_AUTOBCNTX);
if (MACbSafeRxOff(dwIoBase) == false) {
DBG_PORT80(0xA1);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" MACbSafeRxOff == false)\n");
MACbSafeSoftwareReset(dwIoBase);
return false;
}
if (MACbSafeTxOff(dwIoBase) == false) {
DBG_PORT80(0xA2);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" MACbSafeTxOff == false)\n");
MACbSafeSoftwareReset(dwIoBase);
return false;
}
MACvRegBitsOff(dwIoBase, MAC_REG_HOSTCR, HOSTCR_MACEN);
return true;
}
/*
* Description:
* Shut Down MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbShutdown (unsigned long dwIoBase)
{
// disable MAC IMR
MACvIntDisable(dwIoBase);
MACvSetLoopbackMode(dwIoBase, MAC_LB_INTERNAL);
// stop the adapter
if (!MACbSafeStop(dwIoBase)) {
MACvSetLoopbackMode(dwIoBase, MAC_LB_NONE);
return false;
}
MACvSetLoopbackMode(dwIoBase, MAC_LB_NONE);
return true;
}
/*
* Description:
* Initialize MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: none
*
*/
void MACvInitialize (unsigned long dwIoBase)
{
// clear sticky bits
MACvClearStckDS(dwIoBase);
// disable force PME-enable
VNSvOutPortB(dwIoBase + MAC_REG_PMC1, PME_OVR);
// only 3253 A
/*
MACvPwrEvntDisable(dwIoBase);
// clear power status
VNSvOutPortW(dwIoBase + MAC_REG_WAKEUPSR0, 0x0F0F);
*/
// do reset
MACbSoftwareReset(dwIoBase);
// issue AUTOLD in EECSR to reload eeprom
//MACvRegBitsOn(dwIoBase, MAC_REG_I2MCSR, I2MCSR_AUTOLD);
// wait until EEPROM loading complete
//while (true) {
// u8 u8Data;
// VNSvInPortB(dwIoBase + MAC_REG_I2MCSR, &u8Data);
// if ( !(u8Data & I2MCSR_AUTOLD))
// break;
//}
// reset TSF counter
VNSvOutPortB(dwIoBase + MAC_REG_TFTCTL, TFTCTL_TSFCNTRST);
// enable TSF counter
VNSvOutPortB(dwIoBase + MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
// set packet filter
// receive directed and broadcast address
MACvSetPacketFilter(dwIoBase, PKT_TYPE_DIRECTED | PKT_TYPE_BROADCAST);
}
/*
* Description:
* Set the chip with current rx descriptor address
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* dwCurrDescAddr - Descriptor Address
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetCurrRx0DescAddr (unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
unsigned short ww;
unsigned char byData;
unsigned char byOrgDMACtl;
VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL0, &byOrgDMACtl);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL0+2, DMACTL_RUN);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL0, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x13);
}
VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR0, dwCurrDescAddr);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL0, DMACTL_RUN);
}
}
/*
* Description:
* Set the chip with current rx descriptor address
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* dwCurrDescAddr - Descriptor Address
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetCurrRx1DescAddr (unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
unsigned short ww;
unsigned char byData;
unsigned char byOrgDMACtl;
VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL1, &byOrgDMACtl);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL1+2, DMACTL_RUN);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL1, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x14);
}
VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR1, dwCurrDescAddr);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL1, DMACTL_RUN);
}
}
/*
* Description:
* Set the chip with current tx0 descriptor address
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* dwCurrDescAddr - Descriptor Address
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetCurrTx0DescAddrEx (unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
unsigned short ww;
unsigned char byData;
unsigned char byOrgDMACtl;
VNSvInPortB(dwIoBase + MAC_REG_TXDMACTL0, &byOrgDMACtl);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_TXDMACTL0+2, DMACTL_RUN);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_TXDMACTL0, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x25);
}
VNSvOutPortD(dwIoBase + MAC_REG_TXDMAPTR0, dwCurrDescAddr);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_TXDMACTL0, DMACTL_RUN);
}
}
/*
* Description:
* Set the chip with current AC0 descriptor address
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* dwCurrDescAddr - Descriptor Address
* Out:
* none
*
* Return Value: none
*
*/
//TxDMA1 = AC0DMA
void MACvSetCurrAC0DescAddrEx (unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
unsigned short ww;
unsigned char byData;
unsigned char byOrgDMACtl;
VNSvInPortB(dwIoBase + MAC_REG_AC0DMACTL, &byOrgDMACtl);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_AC0DMACTL+2, DMACTL_RUN);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_AC0DMACTL, &byData);
if (!(byData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x26);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x26)\n");
}
VNSvOutPortD(dwIoBase + MAC_REG_AC0DMAPTR, dwCurrDescAddr);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_AC0DMACTL, DMACTL_RUN);
}
}
void MACvSetCurrTXDescAddr (int iTxType, unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
if(iTxType == TYPE_AC0DMA){
MACvSetCurrAC0DescAddrEx(dwIoBase, dwCurrDescAddr);
}else if(iTxType == TYPE_TXDMA0){
MACvSetCurrTx0DescAddrEx(dwIoBase, dwCurrDescAddr);
}
}
/*
* Description:
* Micro Second Delay via MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uDelay - Delay time (timer resolution is 4 us)
* Out:
* none
*
* Return Value: none
*
*/
void MACvTimer0MicroSDelay (unsigned long dwIoBase, unsigned int uDelay)
{
unsigned char byValue;
unsigned int uu,ii;
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
VNSvOutPortD(dwIoBase + MAC_REG_TMDATA0, uDelay);
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, (TMCTL_TMD | TMCTL_TE));
for(ii=0;ii<66;ii++) { // assume max PCI clock is 66Mhz
for (uu = 0; uu < uDelay; uu++) {
VNSvInPortB(dwIoBase + MAC_REG_TMCTL0, &byValue);
if ((byValue == 0) ||
(byValue & TMCTL_TSUSP)) {
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
return;
}
}
}
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
}
/*
* Description:
* Micro Second One shot timer via MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uDelay - Delay time
* Out:
* none
*
* Return Value: none
*
*/
void MACvOneShotTimer0MicroSec (unsigned long dwIoBase, unsigned int uDelayTime)
{
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
VNSvOutPortD(dwIoBase + MAC_REG_TMDATA0, uDelayTime);
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, (TMCTL_TMD | TMCTL_TE));
}
/*
* Description:
* Micro Second One shot timer via MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uDelay - Delay time
* Out:
* none
*
* Return Value: none
*
*/
void MACvOneShotTimer1MicroSec (unsigned long dwIoBase, unsigned int uDelayTime)
{
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL1, 0);
VNSvOutPortD(dwIoBase + MAC_REG_TMDATA1, uDelayTime);
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL1, (TMCTL_TMD | TMCTL_TE));
}
void MACvSetMISCFifo (unsigned long dwIoBase, unsigned short wOffset, unsigned long dwData)
{
if (wOffset > 273)
return;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
bool MACbTxDMAOff (unsigned long dwIoBase, unsigned int idx)
{
unsigned char byData;
unsigned int ww = 0;
if (idx == TYPE_TXDMA0) {
VNSvOutPortB(dwIoBase + MAC_REG_TXDMACTL0+2, DMACTL_RUN);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_TXDMACTL0, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
} else if (idx == TYPE_AC0DMA) {
VNSvOutPortB(dwIoBase + MAC_REG_AC0DMACTL+2, DMACTL_RUN);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_AC0DMACTL, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x29);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x29)\n");
return false;
}
return true;
}
void MACvClearBusSusInd (unsigned long dwIoBase)
{
unsigned long dwOrgValue;
unsigned int ww;
// check if BcnSusInd enabled
VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue);
if( !(dwOrgValue & EnCFG_BcnSusInd))
return;
//Set BcnSusClr
dwOrgValue = dwOrgValue | EnCFG_BcnSusClr;
VNSvOutPortD(dwIoBase + MAC_REG_ENCFG, dwOrgValue);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue);
if( !(dwOrgValue & EnCFG_BcnSusInd))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x33);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x33)\n");
}
}
void MACvEnableBusSusEn (unsigned long dwIoBase)
{
unsigned char byOrgValue;
unsigned long dwOrgValue;
unsigned int ww;
// check if BcnSusInd enabled
VNSvInPortB(dwIoBase + MAC_REG_CFG , &byOrgValue);
//Set BcnSusEn
byOrgValue = byOrgValue | CFG_BCNSUSEN;
VNSvOutPortB(dwIoBase + MAC_REG_ENCFG, byOrgValue);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue);
if(dwOrgValue & EnCFG_BcnSusInd)
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x34);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x34)\n");
}
}
bool MACbFlushSYNCFifo (unsigned long dwIoBase)
{
unsigned char byOrgValue;
unsigned int ww;
// Read MACCR
VNSvInPortB(dwIoBase + MAC_REG_MACCR , &byOrgValue);
// Set SYNCFLUSH
byOrgValue = byOrgValue | MACCR_SYNCFLUSH;
VNSvOutPortB(dwIoBase + MAC_REG_MACCR, byOrgValue);
// Check if SyncFlushOK
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_MACCR , &byOrgValue);
if(byOrgValue & MACCR_SYNCFLUSHOK)
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x35);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x33)\n");
}
return true;
}
bool MACbPSWakeup (unsigned long dwIoBase)
{
unsigned char byOrgValue;
unsigned int ww;
// Read PSCTL
if (MACbIsRegBitsOff(dwIoBase, MAC_REG_PSCTL, PSCTL_PS)) {
return true;
}
// Disable PS
MACvRegBitsOff(dwIoBase, MAC_REG_PSCTL, PSCTL_PSEN);
// Check if SyncFlushOK
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_PSCTL , &byOrgValue);
if(byOrgValue & PSCTL_WAKEDONE)
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x36);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x33)\n");
return false;
}
return true;
}
/*
* Description:
* Set the Key by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetKeyEntry (unsigned long dwIoBase, unsigned short wKeyCtl, unsigned int uEntryIdx,
unsigned int uKeyIdx, unsigned char *pbyAddr, unsigned long *pdwKey, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
int ii;
if (byLocalID <= 1)
return;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetKeyEntry\n");
wOffset = MISCFIFO_KEYETRY0;
wOffset += (uEntryIdx * MISCFIFO_KEYENTRYSIZE);
dwData = 0;
dwData |= wKeyCtl;
dwData <<= 16;
dwData |= MAKEWORD(*(pbyAddr+4), *(pbyAddr+5));
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1. wOffset: %d, Data: %lX, KeyCtl:%X\n", wOffset, dwData, wKeyCtl);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
wOffset++;
dwData = 0;
dwData |= *(pbyAddr+3);
dwData <<= 8;
dwData |= *(pbyAddr+2);
dwData <<= 8;
dwData |= *(pbyAddr+1);
dwData <<= 8;
dwData |= *(pbyAddr+0);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"2. wOffset: %d, Data: %lX\n", wOffset, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
wOffset++;
wOffset += (uKeyIdx * 4);
for (ii=0;ii<4;ii++) {
// alway push 128 bits
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"3.(%d) wOffset: %d, Data: %lX\n", ii, wOffset+ii, *pdwKey);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+ii);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, *pdwKey++);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
}
/*
* Description:
* Disable the Key Entry by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvDisableKeyEntry (unsigned long dwIoBase, unsigned int uEntryIdx)
{
unsigned short wOffset;
wOffset = MISCFIFO_KEYETRY0;
wOffset += (uEntryIdx * MISCFIFO_KEYENTRYSIZE);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, 0);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
/*
* Description:
* Set the default Key (KeyEntry[10]) by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetDefaultKeyEntry (unsigned long dwIoBase, unsigned int uKeyLen,
unsigned int uKeyIdx, unsigned long *pdwKey, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
int ii;
if (byLocalID <= 1)
return;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetDefaultKeyEntry\n");
wOffset = MISCFIFO_KEYETRY0;
wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
wOffset++;
wOffset++;
wOffset += (uKeyIdx * 4);
// alway push 128 bits
for (ii=0; ii<3; ii++) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"(%d) wOffset: %d, Data: %lX\n", ii, wOffset+ii, *pdwKey);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+ii);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, *pdwKey++);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
dwData = *pdwKey;
if (uKeyLen == WLAN_WEP104_KEYLEN) {
dwData |= 0x80000000;
}
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+3);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"End. wOffset: %d, Data: %lX\n", wOffset+3, dwData);
}
/*
* Description:
* Enable default Key (KeyEntry[10]) by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
/*
void MACvEnableDefaultKey (unsigned long dwIoBase, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
if (byLocalID <= 1)
return;
wOffset = MISCFIFO_KEYETRY0;
wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
dwData = 0xC0440000;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvEnableDefaultKey: wOffset: %d, Data: %lX\n", wOffset, dwData);
}
*/
/*
* Description:
* Disable default Key (KeyEntry[10]) by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvDisableDefaultKey (unsigned long dwIoBase)
{
unsigned short wOffset;
unsigned long dwData;
wOffset = MISCFIFO_KEYETRY0;
wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
dwData = 0x0;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvDisableDefaultKey: wOffset: %d, Data: %lX\n", wOffset, dwData);
}
/*
* Description:
* Set the default TKIP Group Key (KeyEntry[10]) by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetDefaultTKIPKeyEntry (unsigned long dwIoBase, unsigned int uKeyLen,
unsigned int uKeyIdx, unsigned long *pdwKey, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
int ii;
if (byLocalID <= 1)
return;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetDefaultTKIPKeyEntry\n");
wOffset = MISCFIFO_KEYETRY0;
// Kyle test : change offset from 10 -> 0
wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
dwData = 0xC0660000;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
wOffset++;
dwData = 0;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
wOffset++;
wOffset += (uKeyIdx * 4);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1. wOffset: %d, Data: %lX, idx:%d\n", wOffset, *pdwKey, uKeyIdx);
// alway push 128 bits
for (ii=0; ii<4; ii++) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"2.(%d) wOffset: %d, Data: %lX\n", ii, wOffset+ii, *pdwKey);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+ii);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, *pdwKey++);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
}
/*
* Description:
* Set the Key Control by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetDefaultKeyCtl (unsigned long dwIoBase, unsigned short wKeyCtl, unsigned int uEntryIdx, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
if (byLocalID <= 1)
return;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetKeyEntry\n");
wOffset = MISCFIFO_KEYETRY0;
wOffset += (uEntryIdx * MISCFIFO_KEYENTRYSIZE);
dwData = 0;
dwData |= wKeyCtl;
dwData <<= 16;
dwData |= 0xffff;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1. wOffset: %d, Data: %lX, KeyCtl:%X\n", wOffset, dwData, wKeyCtl);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
| gpl-2.0 |
Fusion-Devices/android_kernel_lge_mako | drivers/staging/usbip/userspace/src/usbip_bind.c | 8369 | 6837 | /*
* Copyright (C) 2011 matt mooney <mfm@muteddisk.com>
* 2005-2007 Takahiro Hirofuchi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sysfs/libsysfs.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "usbip_common.h"
#include "utils.h"
#include "usbip.h"
enum unbind_status {
UNBIND_ST_OK,
UNBIND_ST_USBIP_HOST,
UNBIND_ST_FAILED
};
static const char usbip_bind_usage_string[] =
"usbip bind <args>\n"
" -b, --busid=<busid> Bind " USBIP_HOST_DRV_NAME ".ko to device "
"on <busid>\n";
void usbip_bind_usage(void)
{
printf("usage: %s", usbip_bind_usage_string);
}
/* call at unbound state */
static int bind_usbip(char *busid)
{
char bus_type[] = "usb";
char attr_name[] = "bind";
char sysfs_mntpath[SYSFS_PATH_MAX];
char bind_attr_path[SYSFS_PATH_MAX];
char intf_busid[SYSFS_BUS_ID_SIZE];
struct sysfs_device *busid_dev;
struct sysfs_attribute *bind_attr;
struct sysfs_attribute *bConfValue;
struct sysfs_attribute *bNumIntfs;
int i, failed = 0;
int rc, ret = -1;
rc = sysfs_get_mnt_path(sysfs_mntpath, SYSFS_PATH_MAX);
if (rc < 0) {
err("sysfs must be mounted: %s", strerror(errno));
return -1;
}
snprintf(bind_attr_path, sizeof(bind_attr_path), "%s/%s/%s/%s/%s/%s",
sysfs_mntpath, SYSFS_BUS_NAME, bus_type, SYSFS_DRIVERS_NAME,
USBIP_HOST_DRV_NAME, attr_name);
bind_attr = sysfs_open_attribute(bind_attr_path);
if (!bind_attr) {
dbg("problem getting bind attribute: %s", strerror(errno));
return -1;
}
busid_dev = sysfs_open_device(bus_type, busid);
if (!busid_dev) {
dbg("sysfs_open_device %s failed: %s", busid, strerror(errno));
goto err_close_bind_attr;
}
bConfValue = sysfs_get_device_attr(busid_dev, "bConfigurationValue");
bNumIntfs = sysfs_get_device_attr(busid_dev, "bNumInterfaces");
if (!bConfValue || !bNumIntfs) {
dbg("problem getting device attributes: %s",
strerror(errno));
goto err_close_busid_dev;
}
for (i = 0; i < atoi(bNumIntfs->value); i++) {
snprintf(intf_busid, SYSFS_BUS_ID_SIZE, "%s:%.1s.%d", busid,
bConfValue->value, i);
rc = sysfs_write_attribute(bind_attr, intf_busid,
SYSFS_BUS_ID_SIZE);
if (rc < 0) {
dbg("bind driver at %s failed", intf_busid);
failed = 1;
}
}
if (!failed)
ret = 0;
err_close_busid_dev:
sysfs_close_device(busid_dev);
err_close_bind_attr:
sysfs_close_attribute(bind_attr);
return ret;
}
/* buggy driver may cause dead lock */
static int unbind_other(char *busid)
{
char bus_type[] = "usb";
char intf_busid[SYSFS_BUS_ID_SIZE];
struct sysfs_device *busid_dev;
struct sysfs_device *intf_dev;
struct sysfs_driver *intf_drv;
struct sysfs_attribute *unbind_attr;
struct sysfs_attribute *bConfValue;
struct sysfs_attribute *bDevClass;
struct sysfs_attribute *bNumIntfs;
int i, rc;
enum unbind_status status = UNBIND_ST_OK;
busid_dev = sysfs_open_device(bus_type, busid);
if (!busid_dev) {
dbg("sysfs_open_device %s failed: %s", busid, strerror(errno));
return -1;
}
bConfValue = sysfs_get_device_attr(busid_dev, "bConfigurationValue");
bDevClass = sysfs_get_device_attr(busid_dev, "bDeviceClass");
bNumIntfs = sysfs_get_device_attr(busid_dev, "bNumInterfaces");
if (!bConfValue || !bDevClass || !bNumIntfs) {
dbg("problem getting device attributes: %s",
strerror(errno));
goto err_close_busid_dev;
}
if (!strncmp(bDevClass->value, "09", bDevClass->len)) {
dbg("skip unbinding of hub");
goto err_close_busid_dev;
}
for (i = 0; i < atoi(bNumIntfs->value); i++) {
snprintf(intf_busid, SYSFS_BUS_ID_SIZE, "%s:%.1s.%d", busid,
bConfValue->value, i);
intf_dev = sysfs_open_device(bus_type, intf_busid);
if (!intf_dev) {
dbg("could not open interface device: %s",
strerror(errno));
goto err_close_busid_dev;
}
dbg("%s -> %s", intf_dev->name, intf_dev->driver_name);
if (!strncmp("unknown", intf_dev->driver_name, SYSFS_NAME_LEN))
/* unbound interface */
continue;
if (!strncmp(USBIP_HOST_DRV_NAME, intf_dev->driver_name,
SYSFS_NAME_LEN)) {
/* already bound to usbip-host */
status = UNBIND_ST_USBIP_HOST;
continue;
}
/* unbinding */
intf_drv = sysfs_open_driver(bus_type, intf_dev->driver_name);
if (!intf_drv) {
dbg("could not open interface driver on %s: %s",
intf_dev->name, strerror(errno));
goto err_close_intf_dev;
}
unbind_attr = sysfs_get_driver_attr(intf_drv, "unbind");
if (!unbind_attr) {
dbg("problem getting interface driver attribute: %s",
strerror(errno));
goto err_close_intf_drv;
}
rc = sysfs_write_attribute(unbind_attr, intf_dev->bus_id,
SYSFS_BUS_ID_SIZE);
if (rc < 0) {
/* NOTE: why keep unbinding other interfaces? */
dbg("unbind driver at %s failed", intf_dev->bus_id);
status = UNBIND_ST_FAILED;
}
sysfs_close_driver(intf_drv);
sysfs_close_device(intf_dev);
}
goto out;
err_close_intf_drv:
sysfs_close_driver(intf_drv);
err_close_intf_dev:
sysfs_close_device(intf_dev);
err_close_busid_dev:
status = UNBIND_ST_FAILED;
out:
sysfs_close_device(busid_dev);
return status;
}
static int bind_device(char *busid)
{
int rc;
rc = unbind_other(busid);
if (rc == UNBIND_ST_FAILED) {
err("could not unbind driver from device on busid %s", busid);
return -1;
} else if (rc == UNBIND_ST_USBIP_HOST) {
err("device on busid %s is already bound to %s", busid,
USBIP_HOST_DRV_NAME);
return -1;
}
rc = modify_match_busid(busid, 1);
if (rc < 0) {
err("unable to bind device on %s", busid);
return -1;
}
rc = bind_usbip(busid);
if (rc < 0) {
err("could not bind device to %s", USBIP_HOST_DRV_NAME);
modify_match_busid(busid, 0);
return -1;
}
printf("bind device on busid %s: complete\n", busid);
return 0;
}
int usbip_bind(int argc, char *argv[])
{
static const struct option opts[] = {
{ "busid", required_argument, NULL, 'b' },
{ NULL, 0, NULL, 0 }
};
int opt;
int ret = -1;
for (;;) {
opt = getopt_long(argc, argv, "b:", opts, NULL);
if (opt == -1)
break;
switch (opt) {
case 'b':
ret = bind_device(optarg);
goto out;
default:
goto err_out;
}
}
err_out:
usbip_bind_usage();
out:
return ret;
}
| gpl-2.0 |
smallsilver/linux | drivers/staging/vt6655/mac.c | 8369 | 44114 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*
* File: mac.c
*
* Purpose: MAC routines
*
* Author: Tevin Chen
*
* Date: May 21, 1996
*
* Functions:
* MACvReadAllRegs - Read All MAC Registers to buffer
* MACbIsRegBitsOn - Test if All test Bits On
* MACbIsRegBitsOff - Test if All test Bits Off
* MACbIsIntDisable - Test if MAC interrupt disable
* MACbyReadMultiAddr - Read Multicast Address Mask Pattern
* MACvWriteMultiAddr - Write Multicast Address Mask Pattern
* MACvSetMultiAddrByHash - Set Multicast Address Mask by Hash value
* MACvResetMultiAddrByHash - Clear Multicast Address Mask by Hash value
* MACvSetRxThreshold - Set Rx Threshold value
* MACvGetRxThreshold - Get Rx Threshold value
* MACvSetTxThreshold - Set Tx Threshold value
* MACvGetTxThreshold - Get Tx Threshold value
* MACvSetDmaLength - Set Dma Length value
* MACvGetDmaLength - Get Dma Length value
* MACvSetShortRetryLimit - Set 802.11 Short Retry limit
* MACvGetShortRetryLimit - Get 802.11 Short Retry limit
* MACvSetLongRetryLimit - Set 802.11 Long Retry limit
* MACvGetLongRetryLimit - Get 802.11 Long Retry limit
* MACvSetLoopbackMode - Set MAC Loopback Mode
* MACbIsInLoopbackMode - Test if MAC in Loopback mode
* MACvSetPacketFilter - Set MAC Address Filter
* MACvSaveContext - Save Context of MAC Registers
* MACvRestoreContext - Restore Context of MAC Registers
* MACbCompareContext - Compare if values of MAC Registers same as Context
* MACbSoftwareReset - Software Reset MAC
* MACbSafeRxOff - Turn Off MAC Rx
* MACbSafeTxOff - Turn Off MAC Tx
* MACbSafeStop - Stop MAC function
* MACbShutdown - Shut down MAC
* MACvInitialize - Initialize MAC
* MACvSetCurrRxDescAddr - Set Rx Descriptos Address
* MACvSetCurrTx0DescAddr - Set Tx0 Descriptos Address
* MACvSetCurrTx1DescAddr - Set Tx1 Descriptos Address
* MACvTimer0MicroSDelay - Micro Second Delay Loop by MAC
*
* Revision History:
* 08-22-2003 Kyle Hsu : Porting MAC functions from sim53
* 09-03-2003 Bryan YC Fan : Add MACvClearBusSusInd()& MACvEnableBusSusEn()
* 09-18-2003 Jerry Chen : Add MACvSetKeyEntry & MACvDisableKeyEntry
*
*/
#include "tmacro.h"
#include "tether.h"
#include "mac.h"
unsigned short TxRate_iwconfig;//2008-5-8 <add> by chester
/*--------------------- Static Definitions -------------------------*/
//static int msglevel =MSG_LEVEL_DEBUG;
static int msglevel =MSG_LEVEL_INFO;
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
/*--------------------- Static Functions --------------------------*/
/*--------------------- Export Variables --------------------------*/
/*--------------------- Export Functions --------------------------*/
/*
* Description:
* Read All MAC Registers to buffer
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyMacRegs - buffer to read
*
* Return Value: none
*
*/
void MACvReadAllRegs (unsigned long dwIoBase, unsigned char *pbyMacRegs)
{
int ii;
// read page0 register
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE0; ii++) {
VNSvInPortB(dwIoBase + ii, pbyMacRegs);
pbyMacRegs++;
}
MACvSelectPage1(dwIoBase);
// read page1 register
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE1; ii++) {
VNSvInPortB(dwIoBase + ii, pbyMacRegs);
pbyMacRegs++;
}
MACvSelectPage0(dwIoBase);
}
/*
* Description:
* Test if all test bits on
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byRegOfs - Offset of MAC Register
* byTestBits - Test bits
* Out:
* none
*
* Return Value: true if all test bits On; otherwise false
*
*/
bool MACbIsRegBitsOn (unsigned long dwIoBase, unsigned char byRegOfs, unsigned char byTestBits)
{
unsigned char byData;
VNSvInPortB(dwIoBase + byRegOfs, &byData);
return (byData & byTestBits) == byTestBits;
}
/*
* Description:
* Test if all test bits off
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byRegOfs - Offset of MAC Register
* byTestBits - Test bits
* Out:
* none
*
* Return Value: true if all test bits Off; otherwise false
*
*/
bool MACbIsRegBitsOff (unsigned long dwIoBase, unsigned char byRegOfs, unsigned char byTestBits)
{
unsigned char byData;
VNSvInPortB(dwIoBase + byRegOfs, &byData);
return !(byData & byTestBits);
}
/*
* Description:
* Test if MAC interrupt disable
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if interrupt is disable; otherwise false
*
*/
bool MACbIsIntDisable (unsigned long dwIoBase)
{
unsigned long dwData;
VNSvInPortD(dwIoBase + MAC_REG_IMR, &dwData);
if (dwData != 0)
return false;
return true;
}
/*
* Description:
* Read MAC Multicast Address Mask
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uByteidx - Index of Mask
* Out:
* none
*
* Return Value: Mask Value read
*
*/
unsigned char MACbyReadMultiAddr (unsigned long dwIoBase, unsigned int uByteIdx)
{
unsigned char byData;
MACvSelectPage1(dwIoBase);
VNSvInPortB(dwIoBase + MAC_REG_MAR0 + uByteIdx, &byData);
MACvSelectPage0(dwIoBase);
return byData;
}
/*
* Description:
* Write MAC Multicast Address Mask
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uByteidx - Index of Mask
* byData - Mask Value to write
* Out:
* none
*
* Return Value: none
*
*/
void MACvWriteMultiAddr (unsigned long dwIoBase, unsigned int uByteIdx, unsigned char byData)
{
MACvSelectPage1(dwIoBase);
VNSvOutPortB(dwIoBase + MAC_REG_MAR0 + uByteIdx, byData);
MACvSelectPage0(dwIoBase);
}
/*
* Description:
* Set this hash index into multicast address register bit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byHashIdx - Hash index to set
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetMultiAddrByHash (unsigned long dwIoBase, unsigned char byHashIdx)
{
unsigned int uByteIdx;
unsigned char byBitMask;
unsigned char byOrgValue;
// calculate byte position
uByteIdx = byHashIdx / 8;
ASSERT(uByteIdx < 8);
// calculate bit position
byBitMask = 1;
byBitMask <<= (byHashIdx % 8);
// turn on the bit
byOrgValue = MACbyReadMultiAddr(dwIoBase, uByteIdx);
MACvWriteMultiAddr(dwIoBase, uByteIdx, (unsigned char)(byOrgValue | byBitMask));
}
/*
* Description:
* Reset this hash index into multicast address register bit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byHashIdx - Hash index to clear
* Out:
* none
*
* Return Value: none
*
*/
void MACvResetMultiAddrByHash (unsigned long dwIoBase, unsigned char byHashIdx)
{
unsigned int uByteIdx;
unsigned char byBitMask;
unsigned char byOrgValue;
// calculate byte position
uByteIdx = byHashIdx / 8;
ASSERT(uByteIdx < 8);
// calculate bit position
byBitMask = 1;
byBitMask <<= (byHashIdx % 8);
// turn off the bit
byOrgValue = MACbyReadMultiAddr(dwIoBase, uByteIdx);
MACvWriteMultiAddr(dwIoBase, uByteIdx, (unsigned char)(byOrgValue & (~byBitMask)));
}
/*
* Description:
* Set Rx Threshold
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byThreshold - Threshold Value
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetRxThreshold (unsigned long dwIoBase, unsigned char byThreshold)
{
unsigned char byOrgValue;
ASSERT(byThreshold < 4);
// set FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, &byOrgValue);
byOrgValue = (byOrgValue & 0xCF) | (byThreshold << 4);
VNSvOutPortB(dwIoBase + MAC_REG_FCR0, byOrgValue);
}
/*
* Description:
* Get Rx Threshold
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyThreshold- Threshold Value Get
*
* Return Value: none
*
*/
void MACvGetRxThreshold (unsigned long dwIoBase, unsigned char *pbyThreshold)
{
// get FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, pbyThreshold);
*pbyThreshold = (*pbyThreshold >> 4) & 0x03;
}
/*
* Description:
* Set Tx Threshold
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byThreshold - Threshold Value
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetTxThreshold (unsigned long dwIoBase, unsigned char byThreshold)
{
unsigned char byOrgValue;
ASSERT(byThreshold < 4);
// set FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, &byOrgValue);
byOrgValue = (byOrgValue & 0xF3) | (byThreshold << 2);
VNSvOutPortB(dwIoBase + MAC_REG_FCR0, byOrgValue);
}
/*
* Description:
* Get Tx Threshold
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyThreshold- Threshold Value Get
*
* Return Value: none
*
*/
void MACvGetTxThreshold (unsigned long dwIoBase, unsigned char *pbyThreshold)
{
// get FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, pbyThreshold);
*pbyThreshold = (*pbyThreshold >> 2) & 0x03;
}
/*
* Description:
* Set Dma Length
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byDmaLength - Dma Length Value
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetDmaLength (unsigned long dwIoBase, unsigned char byDmaLength)
{
unsigned char byOrgValue;
ASSERT(byDmaLength < 4);
// set FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, &byOrgValue);
byOrgValue = (byOrgValue & 0xFC) | byDmaLength;
VNSvOutPortB(dwIoBase + MAC_REG_FCR0, byOrgValue);
}
/*
* Description:
* Get Dma Length
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyDmaLength- Dma Length Value Get
*
* Return Value: none
*
*/
void MACvGetDmaLength (unsigned long dwIoBase, unsigned char *pbyDmaLength)
{
// get FCR0
VNSvInPortB(dwIoBase + MAC_REG_FCR0, pbyDmaLength);
*pbyDmaLength &= 0x03;
}
/*
* Description:
* Set 802.11 Short Retry Limit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byRetryLimit- Retry Limit
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetShortRetryLimit (unsigned long dwIoBase, unsigned char byRetryLimit)
{
// set SRT
VNSvOutPortB(dwIoBase + MAC_REG_SRT, byRetryLimit);
}
/*
* Description:
* Get 802.11 Short Retry Limit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyRetryLimit - Retry Limit Get
*
* Return Value: none
*
*/
void MACvGetShortRetryLimit (unsigned long dwIoBase, unsigned char *pbyRetryLimit)
{
// get SRT
VNSvInPortB(dwIoBase + MAC_REG_SRT, pbyRetryLimit);
}
/*
* Description:
* Set 802.11 Long Retry Limit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byRetryLimit- Retry Limit
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetLongRetryLimit (unsigned long dwIoBase, unsigned char byRetryLimit)
{
// set LRT
VNSvOutPortB(dwIoBase + MAC_REG_LRT, byRetryLimit);
}
/*
* Description:
* Get 802.11 Long Retry Limit
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyRetryLimit - Retry Limit Get
*
* Return Value: none
*
*/
void MACvGetLongRetryLimit (unsigned long dwIoBase, unsigned char *pbyRetryLimit)
{
// get LRT
VNSvInPortB(dwIoBase + MAC_REG_LRT, pbyRetryLimit);
}
/*
* Description:
* Set MAC Loopback mode
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* byLoopbackMode - Loopback Mode
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetLoopbackMode (unsigned long dwIoBase, unsigned char byLoopbackMode)
{
unsigned char byOrgValue;
ASSERT(byLoopbackMode < 3);
byLoopbackMode <<= 6;
// set TCR
VNSvInPortB(dwIoBase + MAC_REG_TEST, &byOrgValue);
byOrgValue = byOrgValue & 0x3F;
byOrgValue = byOrgValue | byLoopbackMode;
VNSvOutPortB(dwIoBase + MAC_REG_TEST, byOrgValue);
}
/*
* Description:
* Test if MAC in Loopback mode
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if in Loopback mode; otherwise false
*
*/
bool MACbIsInLoopbackMode (unsigned long dwIoBase)
{
unsigned char byOrgValue;
VNSvInPortB(dwIoBase + MAC_REG_TEST, &byOrgValue);
if (byOrgValue & (TEST_LBINT | TEST_LBEXT))
return true;
return false;
}
/*
* Description:
* Set MAC Address filter
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* wFilterType - Filter Type
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetPacketFilter (unsigned long dwIoBase, unsigned short wFilterType)
{
unsigned char byOldRCR;
unsigned char byNewRCR = 0;
// if only in DIRECTED mode, multicast-address will set to zero,
// but if other mode exist (e.g. PROMISCUOUS), multicast-address
// will be open
if (wFilterType & PKT_TYPE_DIRECTED) {
// set multicast address to accept none
MACvSelectPage1(dwIoBase);
VNSvOutPortD(dwIoBase + MAC_REG_MAR0, 0L);
VNSvOutPortD(dwIoBase + MAC_REG_MAR0 + sizeof(unsigned long), 0L);
MACvSelectPage0(dwIoBase);
}
if (wFilterType & (PKT_TYPE_PROMISCUOUS | PKT_TYPE_ALL_MULTICAST)) {
// set multicast address to accept all
MACvSelectPage1(dwIoBase);
VNSvOutPortD(dwIoBase + MAC_REG_MAR0, 0xFFFFFFFFL);
VNSvOutPortD(dwIoBase + MAC_REG_MAR0 + sizeof(unsigned long), 0xFFFFFFFFL);
MACvSelectPage0(dwIoBase);
}
if (wFilterType & PKT_TYPE_PROMISCUOUS) {
byNewRCR |= (RCR_RXALLTYPE | RCR_UNICAST | RCR_MULTICAST | RCR_BROADCAST);
byNewRCR &= ~RCR_BSSID;
}
if (wFilterType & (PKT_TYPE_ALL_MULTICAST | PKT_TYPE_MULTICAST))
byNewRCR |= RCR_MULTICAST;
if (wFilterType & PKT_TYPE_BROADCAST)
byNewRCR |= RCR_BROADCAST;
if (wFilterType & PKT_TYPE_ERROR_CRC)
byNewRCR |= RCR_ERRCRC;
VNSvInPortB(dwIoBase + MAC_REG_RCR, &byOldRCR);
if (byNewRCR != byOldRCR) {
// Modify the Receive Command Register
VNSvOutPortB(dwIoBase + MAC_REG_RCR, byNewRCR);
}
}
/*
* Description:
* Save MAC registers to context buffer
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* pbyCxtBuf - Context buffer
*
* Return Value: none
*
*/
void MACvSaveContext (unsigned long dwIoBase, unsigned char *pbyCxtBuf)
{
int ii;
// read page0 register
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE0; ii++) {
VNSvInPortB((dwIoBase + ii), (pbyCxtBuf + ii));
}
MACvSelectPage1(dwIoBase);
// read page1 register
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE1; ii++) {
VNSvInPortB((dwIoBase + ii), (pbyCxtBuf + MAC_MAX_CONTEXT_SIZE_PAGE0 + ii));
}
MACvSelectPage0(dwIoBase);
}
/*
* Description:
* Restore MAC registers from context buffer
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* pbyCxtBuf - Context buffer
* Out:
* none
*
* Return Value: none
*
*/
void MACvRestoreContext (unsigned long dwIoBase, unsigned char *pbyCxtBuf)
{
int ii;
MACvSelectPage1(dwIoBase);
// restore page1
for (ii = 0; ii < MAC_MAX_CONTEXT_SIZE_PAGE1; ii++) {
VNSvOutPortB((dwIoBase + ii), *(pbyCxtBuf + MAC_MAX_CONTEXT_SIZE_PAGE0 + ii));
}
MACvSelectPage0(dwIoBase);
// restore RCR,TCR,IMR...
for (ii = MAC_REG_RCR; ii < MAC_REG_ISR; ii++) {
VNSvOutPortB(dwIoBase + ii, *(pbyCxtBuf + ii));
}
// restore MAC Config.
for (ii = MAC_REG_LRT; ii < MAC_REG_PAGE1SEL; ii++) {
VNSvOutPortB(dwIoBase + ii, *(pbyCxtBuf + ii));
}
VNSvOutPortB(dwIoBase + MAC_REG_CFG, *(pbyCxtBuf + MAC_REG_CFG));
// restore PS Config.
for (ii = MAC_REG_PSCFG; ii < MAC_REG_BBREGCTL; ii++) {
VNSvOutPortB(dwIoBase + ii, *(pbyCxtBuf + ii));
}
// restore CURR_RX_DESC_ADDR, CURR_TX_DESC_ADDR
VNSvOutPortD(dwIoBase + MAC_REG_TXDMAPTR0, *(unsigned long *)(pbyCxtBuf + MAC_REG_TXDMAPTR0));
VNSvOutPortD(dwIoBase + MAC_REG_AC0DMAPTR, *(unsigned long *)(pbyCxtBuf + MAC_REG_AC0DMAPTR));
VNSvOutPortD(dwIoBase + MAC_REG_BCNDMAPTR, *(unsigned long *)(pbyCxtBuf + MAC_REG_BCNDMAPTR));
VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR0, *(unsigned long *)(pbyCxtBuf + MAC_REG_RXDMAPTR0));
VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR1, *(unsigned long *)(pbyCxtBuf + MAC_REG_RXDMAPTR1));
}
/*
* Description:
* Compare if MAC registers same as context buffer
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* pbyCxtBuf - Context buffer
* Out:
* none
*
* Return Value: true if all values are the same; otherwise false
*
*/
bool MACbCompareContext (unsigned long dwIoBase, unsigned char *pbyCxtBuf)
{
unsigned long dwData;
// compare MAC context to determine if this is a power lost init,
// return true for power remaining init, return false for power lost init
// compare CURR_RX_DESC_ADDR, CURR_TX_DESC_ADDR
VNSvInPortD(dwIoBase + MAC_REG_TXDMAPTR0, &dwData);
if (dwData != *(unsigned long *)(pbyCxtBuf + MAC_REG_TXDMAPTR0)) {
return false;
}
VNSvInPortD(dwIoBase + MAC_REG_AC0DMAPTR, &dwData);
if (dwData != *(unsigned long *)(pbyCxtBuf + MAC_REG_AC0DMAPTR)) {
return false;
}
VNSvInPortD(dwIoBase + MAC_REG_RXDMAPTR0, &dwData);
if (dwData != *(unsigned long *)(pbyCxtBuf + MAC_REG_RXDMAPTR0)) {
return false;
}
VNSvInPortD(dwIoBase + MAC_REG_RXDMAPTR1, &dwData);
if (dwData != *(unsigned long *)(pbyCxtBuf + MAC_REG_RXDMAPTR1)) {
return false;
}
return true;
}
/*
* Description:
* Software Reset MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if Reset Success; otherwise false
*
*/
bool MACbSoftwareReset (unsigned long dwIoBase)
{
unsigned char byData;
unsigned short ww;
// turn on HOSTCR_SOFTRST, just write 0x01 to reset
//MACvRegBitsOn(dwIoBase, MAC_REG_HOSTCR, HOSTCR_SOFTRST);
VNSvOutPortB(dwIoBase+ MAC_REG_HOSTCR, 0x01);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_HOSTCR, &byData);
if ( !(byData & HOSTCR_SOFTRST))
break;
}
if (ww == W_MAX_TIMEOUT)
return false;
return true;
}
/*
* Description:
* save some important register's value, then do reset, then restore register's value
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbSafeSoftwareReset (unsigned long dwIoBase)
{
unsigned char abyTmpRegData[MAC_MAX_CONTEXT_SIZE_PAGE0+MAC_MAX_CONTEXT_SIZE_PAGE1];
bool bRetVal;
// PATCH....
// save some important register's value, then do
// reset, then restore register's value
// save MAC context
MACvSaveContext(dwIoBase, abyTmpRegData);
// do reset
bRetVal = MACbSoftwareReset(dwIoBase);
//BBvSoftwareReset(pDevice->PortOffset);
// restore MAC context, except CR0
MACvRestoreContext(dwIoBase, abyTmpRegData);
return bRetVal;
}
/*
* Description:
* Trun Off MAC Rx
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbSafeRxOff (unsigned long dwIoBase)
{
unsigned short ww;
unsigned long dwData;
unsigned char byData;
// turn off wow temp for turn off Rx safely
// Clear RX DMA0,1
VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL0, DMACTL_CLRRUN);
VNSvOutPortD(dwIoBase + MAC_REG_RXDMACTL1, DMACTL_CLRRUN);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_RXDMACTL0, &dwData);
if (!(dwData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x10);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x10)\n");
return(false);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_RXDMACTL1, &dwData);
if ( !(dwData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x11);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x11)\n");
return(false);
}
// try to safe shutdown RX
MACvRegBitsOff(dwIoBase, MAC_REG_HOSTCR, HOSTCR_RXON);
// W_MAX_TIMEOUT is the timeout period
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_HOSTCR, &byData);
if ( !(byData & HOSTCR_RXONST))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x12);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x12)\n");
return(false);
}
return true;
}
/*
* Description:
* Trun Off MAC Tx
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbSafeTxOff (unsigned long dwIoBase)
{
unsigned short ww;
unsigned long dwData;
unsigned char byData;
// Clear TX DMA
//Tx0
VNSvOutPortD(dwIoBase + MAC_REG_TXDMACTL0, DMACTL_CLRRUN);
//AC0
VNSvOutPortD(dwIoBase + MAC_REG_AC0DMACTL, DMACTL_CLRRUN);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_TXDMACTL0, &dwData);
if ( !(dwData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x20);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x20)\n");
return(false);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_AC0DMACTL, &dwData);
if ( !(dwData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x21);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x21)\n");
return(false);
}
// try to safe shutdown TX
MACvRegBitsOff(dwIoBase, MAC_REG_HOSTCR, HOSTCR_TXON);
// W_MAX_TIMEOUT is the timeout period
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_HOSTCR, &byData);
if ( !(byData & HOSTCR_TXONST))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x24);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x24)\n");
return(false);
}
return true;
}
/*
* Description:
* Stop MAC function
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbSafeStop (unsigned long dwIoBase)
{
MACvRegBitsOff(dwIoBase, MAC_REG_TCR, TCR_AUTOBCNTX);
if (MACbSafeRxOff(dwIoBase) == false) {
DBG_PORT80(0xA1);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" MACbSafeRxOff == false)\n");
MACbSafeSoftwareReset(dwIoBase);
return false;
}
if (MACbSafeTxOff(dwIoBase) == false) {
DBG_PORT80(0xA2);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" MACbSafeTxOff == false)\n");
MACbSafeSoftwareReset(dwIoBase);
return false;
}
MACvRegBitsOff(dwIoBase, MAC_REG_HOSTCR, HOSTCR_MACEN);
return true;
}
/*
* Description:
* Shut Down MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: true if success; otherwise false
*
*/
bool MACbShutdown (unsigned long dwIoBase)
{
// disable MAC IMR
MACvIntDisable(dwIoBase);
MACvSetLoopbackMode(dwIoBase, MAC_LB_INTERNAL);
// stop the adapter
if (!MACbSafeStop(dwIoBase)) {
MACvSetLoopbackMode(dwIoBase, MAC_LB_NONE);
return false;
}
MACvSetLoopbackMode(dwIoBase, MAC_LB_NONE);
return true;
}
/*
* Description:
* Initialize MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* Out:
* none
*
* Return Value: none
*
*/
void MACvInitialize (unsigned long dwIoBase)
{
// clear sticky bits
MACvClearStckDS(dwIoBase);
// disable force PME-enable
VNSvOutPortB(dwIoBase + MAC_REG_PMC1, PME_OVR);
// only 3253 A
/*
MACvPwrEvntDisable(dwIoBase);
// clear power status
VNSvOutPortW(dwIoBase + MAC_REG_WAKEUPSR0, 0x0F0F);
*/
// do reset
MACbSoftwareReset(dwIoBase);
// issue AUTOLD in EECSR to reload eeprom
//MACvRegBitsOn(dwIoBase, MAC_REG_I2MCSR, I2MCSR_AUTOLD);
// wait until EEPROM loading complete
//while (true) {
// u8 u8Data;
// VNSvInPortB(dwIoBase + MAC_REG_I2MCSR, &u8Data);
// if ( !(u8Data & I2MCSR_AUTOLD))
// break;
//}
// reset TSF counter
VNSvOutPortB(dwIoBase + MAC_REG_TFTCTL, TFTCTL_TSFCNTRST);
// enable TSF counter
VNSvOutPortB(dwIoBase + MAC_REG_TFTCTL, TFTCTL_TSFCNTREN);
// set packet filter
// receive directed and broadcast address
MACvSetPacketFilter(dwIoBase, PKT_TYPE_DIRECTED | PKT_TYPE_BROADCAST);
}
/*
* Description:
* Set the chip with current rx descriptor address
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* dwCurrDescAddr - Descriptor Address
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetCurrRx0DescAddr (unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
unsigned short ww;
unsigned char byData;
unsigned char byOrgDMACtl;
VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL0, &byOrgDMACtl);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL0+2, DMACTL_RUN);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL0, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x13);
}
VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR0, dwCurrDescAddr);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL0, DMACTL_RUN);
}
}
/*
* Description:
* Set the chip with current rx descriptor address
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* dwCurrDescAddr - Descriptor Address
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetCurrRx1DescAddr (unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
unsigned short ww;
unsigned char byData;
unsigned char byOrgDMACtl;
VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL1, &byOrgDMACtl);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL1+2, DMACTL_RUN);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_RXDMACTL1, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x14);
}
VNSvOutPortD(dwIoBase + MAC_REG_RXDMAPTR1, dwCurrDescAddr);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_RXDMACTL1, DMACTL_RUN);
}
}
/*
* Description:
* Set the chip with current tx0 descriptor address
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* dwCurrDescAddr - Descriptor Address
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetCurrTx0DescAddrEx (unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
unsigned short ww;
unsigned char byData;
unsigned char byOrgDMACtl;
VNSvInPortB(dwIoBase + MAC_REG_TXDMACTL0, &byOrgDMACtl);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_TXDMACTL0+2, DMACTL_RUN);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_TXDMACTL0, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x25);
}
VNSvOutPortD(dwIoBase + MAC_REG_TXDMAPTR0, dwCurrDescAddr);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_TXDMACTL0, DMACTL_RUN);
}
}
/*
* Description:
* Set the chip with current AC0 descriptor address
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* dwCurrDescAddr - Descriptor Address
* Out:
* none
*
* Return Value: none
*
*/
//TxDMA1 = AC0DMA
void MACvSetCurrAC0DescAddrEx (unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
unsigned short ww;
unsigned char byData;
unsigned char byOrgDMACtl;
VNSvInPortB(dwIoBase + MAC_REG_AC0DMACTL, &byOrgDMACtl);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_AC0DMACTL+2, DMACTL_RUN);
}
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_AC0DMACTL, &byData);
if (!(byData & DMACTL_RUN))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x26);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x26)\n");
}
VNSvOutPortD(dwIoBase + MAC_REG_AC0DMAPTR, dwCurrDescAddr);
if (byOrgDMACtl & DMACTL_RUN) {
VNSvOutPortB(dwIoBase + MAC_REG_AC0DMACTL, DMACTL_RUN);
}
}
void MACvSetCurrTXDescAddr (int iTxType, unsigned long dwIoBase, unsigned long dwCurrDescAddr)
{
if(iTxType == TYPE_AC0DMA){
MACvSetCurrAC0DescAddrEx(dwIoBase, dwCurrDescAddr);
}else if(iTxType == TYPE_TXDMA0){
MACvSetCurrTx0DescAddrEx(dwIoBase, dwCurrDescAddr);
}
}
/*
* Description:
* Micro Second Delay via MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uDelay - Delay time (timer resolution is 4 us)
* Out:
* none
*
* Return Value: none
*
*/
void MACvTimer0MicroSDelay (unsigned long dwIoBase, unsigned int uDelay)
{
unsigned char byValue;
unsigned int uu,ii;
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
VNSvOutPortD(dwIoBase + MAC_REG_TMDATA0, uDelay);
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, (TMCTL_TMD | TMCTL_TE));
for(ii=0;ii<66;ii++) { // assume max PCI clock is 66Mhz
for (uu = 0; uu < uDelay; uu++) {
VNSvInPortB(dwIoBase + MAC_REG_TMCTL0, &byValue);
if ((byValue == 0) ||
(byValue & TMCTL_TSUSP)) {
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
return;
}
}
}
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
}
/*
* Description:
* Micro Second One shot timer via MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uDelay - Delay time
* Out:
* none
*
* Return Value: none
*
*/
void MACvOneShotTimer0MicroSec (unsigned long dwIoBase, unsigned int uDelayTime)
{
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, 0);
VNSvOutPortD(dwIoBase + MAC_REG_TMDATA0, uDelayTime);
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL0, (TMCTL_TMD | TMCTL_TE));
}
/*
* Description:
* Micro Second One shot timer via MAC
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
* uDelay - Delay time
* Out:
* none
*
* Return Value: none
*
*/
void MACvOneShotTimer1MicroSec (unsigned long dwIoBase, unsigned int uDelayTime)
{
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL1, 0);
VNSvOutPortD(dwIoBase + MAC_REG_TMDATA1, uDelayTime);
VNSvOutPortB(dwIoBase + MAC_REG_TMCTL1, (TMCTL_TMD | TMCTL_TE));
}
void MACvSetMISCFifo (unsigned long dwIoBase, unsigned short wOffset, unsigned long dwData)
{
if (wOffset > 273)
return;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
bool MACbTxDMAOff (unsigned long dwIoBase, unsigned int idx)
{
unsigned char byData;
unsigned int ww = 0;
if (idx == TYPE_TXDMA0) {
VNSvOutPortB(dwIoBase + MAC_REG_TXDMACTL0+2, DMACTL_RUN);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_TXDMACTL0, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
} else if (idx == TYPE_AC0DMA) {
VNSvOutPortB(dwIoBase + MAC_REG_AC0DMACTL+2, DMACTL_RUN);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_AC0DMACTL, &byData);
if ( !(byData & DMACTL_RUN))
break;
}
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x29);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x29)\n");
return false;
}
return true;
}
void MACvClearBusSusInd (unsigned long dwIoBase)
{
unsigned long dwOrgValue;
unsigned int ww;
// check if BcnSusInd enabled
VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue);
if( !(dwOrgValue & EnCFG_BcnSusInd))
return;
//Set BcnSusClr
dwOrgValue = dwOrgValue | EnCFG_BcnSusClr;
VNSvOutPortD(dwIoBase + MAC_REG_ENCFG, dwOrgValue);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue);
if( !(dwOrgValue & EnCFG_BcnSusInd))
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x33);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x33)\n");
}
}
void MACvEnableBusSusEn (unsigned long dwIoBase)
{
unsigned char byOrgValue;
unsigned long dwOrgValue;
unsigned int ww;
// check if BcnSusInd enabled
VNSvInPortB(dwIoBase + MAC_REG_CFG , &byOrgValue);
//Set BcnSusEn
byOrgValue = byOrgValue | CFG_BCNSUSEN;
VNSvOutPortB(dwIoBase + MAC_REG_ENCFG, byOrgValue);
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortD(dwIoBase + MAC_REG_ENCFG , &dwOrgValue);
if(dwOrgValue & EnCFG_BcnSusInd)
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x34);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x34)\n");
}
}
bool MACbFlushSYNCFifo (unsigned long dwIoBase)
{
unsigned char byOrgValue;
unsigned int ww;
// Read MACCR
VNSvInPortB(dwIoBase + MAC_REG_MACCR , &byOrgValue);
// Set SYNCFLUSH
byOrgValue = byOrgValue | MACCR_SYNCFLUSH;
VNSvOutPortB(dwIoBase + MAC_REG_MACCR, byOrgValue);
// Check if SyncFlushOK
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_MACCR , &byOrgValue);
if(byOrgValue & MACCR_SYNCFLUSHOK)
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x35);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x33)\n");
}
return true;
}
bool MACbPSWakeup (unsigned long dwIoBase)
{
unsigned char byOrgValue;
unsigned int ww;
// Read PSCTL
if (MACbIsRegBitsOff(dwIoBase, MAC_REG_PSCTL, PSCTL_PS)) {
return true;
}
// Disable PS
MACvRegBitsOff(dwIoBase, MAC_REG_PSCTL, PSCTL_PSEN);
// Check if SyncFlushOK
for (ww = 0; ww < W_MAX_TIMEOUT; ww++) {
VNSvInPortB(dwIoBase + MAC_REG_PSCTL , &byOrgValue);
if(byOrgValue & PSCTL_WAKEDONE)
break;
}
if (ww == W_MAX_TIMEOUT) {
DBG_PORT80(0x36);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO" DBG_PORT80(0x33)\n");
return false;
}
return true;
}
/*
* Description:
* Set the Key by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetKeyEntry (unsigned long dwIoBase, unsigned short wKeyCtl, unsigned int uEntryIdx,
unsigned int uKeyIdx, unsigned char *pbyAddr, unsigned long *pdwKey, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
int ii;
if (byLocalID <= 1)
return;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetKeyEntry\n");
wOffset = MISCFIFO_KEYETRY0;
wOffset += (uEntryIdx * MISCFIFO_KEYENTRYSIZE);
dwData = 0;
dwData |= wKeyCtl;
dwData <<= 16;
dwData |= MAKEWORD(*(pbyAddr+4), *(pbyAddr+5));
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1. wOffset: %d, Data: %lX, KeyCtl:%X\n", wOffset, dwData, wKeyCtl);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
wOffset++;
dwData = 0;
dwData |= *(pbyAddr+3);
dwData <<= 8;
dwData |= *(pbyAddr+2);
dwData <<= 8;
dwData |= *(pbyAddr+1);
dwData <<= 8;
dwData |= *(pbyAddr+0);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"2. wOffset: %d, Data: %lX\n", wOffset, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
wOffset++;
wOffset += (uKeyIdx * 4);
for (ii=0;ii<4;ii++) {
// alway push 128 bits
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"3.(%d) wOffset: %d, Data: %lX\n", ii, wOffset+ii, *pdwKey);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+ii);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, *pdwKey++);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
}
/*
* Description:
* Disable the Key Entry by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvDisableKeyEntry (unsigned long dwIoBase, unsigned int uEntryIdx)
{
unsigned short wOffset;
wOffset = MISCFIFO_KEYETRY0;
wOffset += (uEntryIdx * MISCFIFO_KEYENTRYSIZE);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, 0);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
/*
* Description:
* Set the default Key (KeyEntry[10]) by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetDefaultKeyEntry (unsigned long dwIoBase, unsigned int uKeyLen,
unsigned int uKeyIdx, unsigned long *pdwKey, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
int ii;
if (byLocalID <= 1)
return;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetDefaultKeyEntry\n");
wOffset = MISCFIFO_KEYETRY0;
wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
wOffset++;
wOffset++;
wOffset += (uKeyIdx * 4);
// alway push 128 bits
for (ii=0; ii<3; ii++) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"(%d) wOffset: %d, Data: %lX\n", ii, wOffset+ii, *pdwKey);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+ii);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, *pdwKey++);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
dwData = *pdwKey;
if (uKeyLen == WLAN_WEP104_KEYLEN) {
dwData |= 0x80000000;
}
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+3);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"End. wOffset: %d, Data: %lX\n", wOffset+3, dwData);
}
/*
* Description:
* Enable default Key (KeyEntry[10]) by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
/*
void MACvEnableDefaultKey (unsigned long dwIoBase, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
if (byLocalID <= 1)
return;
wOffset = MISCFIFO_KEYETRY0;
wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
dwData = 0xC0440000;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvEnableDefaultKey: wOffset: %d, Data: %lX\n", wOffset, dwData);
}
*/
/*
* Description:
* Disable default Key (KeyEntry[10]) by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvDisableDefaultKey (unsigned long dwIoBase)
{
unsigned short wOffset;
unsigned long dwData;
wOffset = MISCFIFO_KEYETRY0;
wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
dwData = 0x0;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvDisableDefaultKey: wOffset: %d, Data: %lX\n", wOffset, dwData);
}
/*
* Description:
* Set the default TKIP Group Key (KeyEntry[10]) by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetDefaultTKIPKeyEntry (unsigned long dwIoBase, unsigned int uKeyLen,
unsigned int uKeyIdx, unsigned long *pdwKey, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
int ii;
if (byLocalID <= 1)
return;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetDefaultTKIPKeyEntry\n");
wOffset = MISCFIFO_KEYETRY0;
// Kyle test : change offset from 10 -> 0
wOffset += (10 * MISCFIFO_KEYENTRYSIZE);
dwData = 0xC0660000;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
wOffset++;
dwData = 0;
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
wOffset++;
wOffset += (uKeyIdx * 4);
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1. wOffset: %d, Data: %lX, idx:%d\n", wOffset, *pdwKey, uKeyIdx);
// alway push 128 bits
for (ii=0; ii<4; ii++) {
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"2.(%d) wOffset: %d, Data: %lX\n", ii, wOffset+ii, *pdwKey);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset+ii);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, *pdwKey++);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
}
/*
* Description:
* Set the Key Control by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void MACvSetDefaultKeyCtl (unsigned long dwIoBase, unsigned short wKeyCtl, unsigned int uEntryIdx, unsigned char byLocalID)
{
unsigned short wOffset;
unsigned long dwData;
if (byLocalID <= 1)
return;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"MACvSetKeyEntry\n");
wOffset = MISCFIFO_KEYETRY0;
wOffset += (uEntryIdx * MISCFIFO_KEYENTRYSIZE);
dwData = 0;
dwData |= wKeyCtl;
dwData <<= 16;
dwData |= 0xffff;
DBG_PRT(MSG_LEVEL_DEBUG, KERN_INFO"1. wOffset: %d, Data: %lX, KeyCtl:%X\n", wOffset, dwData, wKeyCtl);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFNDEX, wOffset);
VNSvOutPortD(dwIoBase + MAC_REG_MISCFFDATA, dwData);
VNSvOutPortW(dwIoBase + MAC_REG_MISCFFCTL, MISCFFCTL_WRITE);
}
| gpl-2.0 |
davidmueller13/lt03lte_tw_kernel_5.1.1 | drivers/staging/usbip/userspace/src/usbip_bind.c | 8369 | 6837 | /*
* Copyright (C) 2011 matt mooney <mfm@muteddisk.com>
* 2005-2007 Takahiro Hirofuchi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sysfs/libsysfs.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "usbip_common.h"
#include "utils.h"
#include "usbip.h"
enum unbind_status {
UNBIND_ST_OK,
UNBIND_ST_USBIP_HOST,
UNBIND_ST_FAILED
};
static const char usbip_bind_usage_string[] =
"usbip bind <args>\n"
" -b, --busid=<busid> Bind " USBIP_HOST_DRV_NAME ".ko to device "
"on <busid>\n";
void usbip_bind_usage(void)
{
printf("usage: %s", usbip_bind_usage_string);
}
/* call at unbound state */
static int bind_usbip(char *busid)
{
char bus_type[] = "usb";
char attr_name[] = "bind";
char sysfs_mntpath[SYSFS_PATH_MAX];
char bind_attr_path[SYSFS_PATH_MAX];
char intf_busid[SYSFS_BUS_ID_SIZE];
struct sysfs_device *busid_dev;
struct sysfs_attribute *bind_attr;
struct sysfs_attribute *bConfValue;
struct sysfs_attribute *bNumIntfs;
int i, failed = 0;
int rc, ret = -1;
rc = sysfs_get_mnt_path(sysfs_mntpath, SYSFS_PATH_MAX);
if (rc < 0) {
err("sysfs must be mounted: %s", strerror(errno));
return -1;
}
snprintf(bind_attr_path, sizeof(bind_attr_path), "%s/%s/%s/%s/%s/%s",
sysfs_mntpath, SYSFS_BUS_NAME, bus_type, SYSFS_DRIVERS_NAME,
USBIP_HOST_DRV_NAME, attr_name);
bind_attr = sysfs_open_attribute(bind_attr_path);
if (!bind_attr) {
dbg("problem getting bind attribute: %s", strerror(errno));
return -1;
}
busid_dev = sysfs_open_device(bus_type, busid);
if (!busid_dev) {
dbg("sysfs_open_device %s failed: %s", busid, strerror(errno));
goto err_close_bind_attr;
}
bConfValue = sysfs_get_device_attr(busid_dev, "bConfigurationValue");
bNumIntfs = sysfs_get_device_attr(busid_dev, "bNumInterfaces");
if (!bConfValue || !bNumIntfs) {
dbg("problem getting device attributes: %s",
strerror(errno));
goto err_close_busid_dev;
}
for (i = 0; i < atoi(bNumIntfs->value); i++) {
snprintf(intf_busid, SYSFS_BUS_ID_SIZE, "%s:%.1s.%d", busid,
bConfValue->value, i);
rc = sysfs_write_attribute(bind_attr, intf_busid,
SYSFS_BUS_ID_SIZE);
if (rc < 0) {
dbg("bind driver at %s failed", intf_busid);
failed = 1;
}
}
if (!failed)
ret = 0;
err_close_busid_dev:
sysfs_close_device(busid_dev);
err_close_bind_attr:
sysfs_close_attribute(bind_attr);
return ret;
}
/* buggy driver may cause dead lock */
static int unbind_other(char *busid)
{
char bus_type[] = "usb";
char intf_busid[SYSFS_BUS_ID_SIZE];
struct sysfs_device *busid_dev;
struct sysfs_device *intf_dev;
struct sysfs_driver *intf_drv;
struct sysfs_attribute *unbind_attr;
struct sysfs_attribute *bConfValue;
struct sysfs_attribute *bDevClass;
struct sysfs_attribute *bNumIntfs;
int i, rc;
enum unbind_status status = UNBIND_ST_OK;
busid_dev = sysfs_open_device(bus_type, busid);
if (!busid_dev) {
dbg("sysfs_open_device %s failed: %s", busid, strerror(errno));
return -1;
}
bConfValue = sysfs_get_device_attr(busid_dev, "bConfigurationValue");
bDevClass = sysfs_get_device_attr(busid_dev, "bDeviceClass");
bNumIntfs = sysfs_get_device_attr(busid_dev, "bNumInterfaces");
if (!bConfValue || !bDevClass || !bNumIntfs) {
dbg("problem getting device attributes: %s",
strerror(errno));
goto err_close_busid_dev;
}
if (!strncmp(bDevClass->value, "09", bDevClass->len)) {
dbg("skip unbinding of hub");
goto err_close_busid_dev;
}
for (i = 0; i < atoi(bNumIntfs->value); i++) {
snprintf(intf_busid, SYSFS_BUS_ID_SIZE, "%s:%.1s.%d", busid,
bConfValue->value, i);
intf_dev = sysfs_open_device(bus_type, intf_busid);
if (!intf_dev) {
dbg("could not open interface device: %s",
strerror(errno));
goto err_close_busid_dev;
}
dbg("%s -> %s", intf_dev->name, intf_dev->driver_name);
if (!strncmp("unknown", intf_dev->driver_name, SYSFS_NAME_LEN))
/* unbound interface */
continue;
if (!strncmp(USBIP_HOST_DRV_NAME, intf_dev->driver_name,
SYSFS_NAME_LEN)) {
/* already bound to usbip-host */
status = UNBIND_ST_USBIP_HOST;
continue;
}
/* unbinding */
intf_drv = sysfs_open_driver(bus_type, intf_dev->driver_name);
if (!intf_drv) {
dbg("could not open interface driver on %s: %s",
intf_dev->name, strerror(errno));
goto err_close_intf_dev;
}
unbind_attr = sysfs_get_driver_attr(intf_drv, "unbind");
if (!unbind_attr) {
dbg("problem getting interface driver attribute: %s",
strerror(errno));
goto err_close_intf_drv;
}
rc = sysfs_write_attribute(unbind_attr, intf_dev->bus_id,
SYSFS_BUS_ID_SIZE);
if (rc < 0) {
/* NOTE: why keep unbinding other interfaces? */
dbg("unbind driver at %s failed", intf_dev->bus_id);
status = UNBIND_ST_FAILED;
}
sysfs_close_driver(intf_drv);
sysfs_close_device(intf_dev);
}
goto out;
err_close_intf_drv:
sysfs_close_driver(intf_drv);
err_close_intf_dev:
sysfs_close_device(intf_dev);
err_close_busid_dev:
status = UNBIND_ST_FAILED;
out:
sysfs_close_device(busid_dev);
return status;
}
static int bind_device(char *busid)
{
int rc;
rc = unbind_other(busid);
if (rc == UNBIND_ST_FAILED) {
err("could not unbind driver from device on busid %s", busid);
return -1;
} else if (rc == UNBIND_ST_USBIP_HOST) {
err("device on busid %s is already bound to %s", busid,
USBIP_HOST_DRV_NAME);
return -1;
}
rc = modify_match_busid(busid, 1);
if (rc < 0) {
err("unable to bind device on %s", busid);
return -1;
}
rc = bind_usbip(busid);
if (rc < 0) {
err("could not bind device to %s", USBIP_HOST_DRV_NAME);
modify_match_busid(busid, 0);
return -1;
}
printf("bind device on busid %s: complete\n", busid);
return 0;
}
int usbip_bind(int argc, char *argv[])
{
static const struct option opts[] = {
{ "busid", required_argument, NULL, 'b' },
{ NULL, 0, NULL, 0 }
};
int opt;
int ret = -1;
for (;;) {
opt = getopt_long(argc, argv, "b:", opts, NULL);
if (opt == -1)
break;
switch (opt) {
case 'b':
ret = bind_device(optarg);
goto out;
default:
goto err_out;
}
}
err_out:
usbip_bind_usage();
out:
return ret;
}
| gpl-2.0 |
GlitchKernel/Glitch | sound/oss/v_midi.c | 12721 | 6457 | /*
* sound/oss/v_midi.c
*
* The low level driver for the Sound Blaster DS chips.
*
*
* Copyright (C) by Hannu Savolainen 1993-1996
*
* USS/Lite for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
* ??
*
* Changes
* Alan Cox Modularisation, changed memory allocations
* Christoph Hellwig Adapted to module_init/module_exit
*
* Status
* Untested
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include "sound_config.h"
#include "v_midi.h"
static vmidi_devc *v_devc[2] = { NULL, NULL};
static int midi1,midi2;
static void *midi_mem = NULL;
/*
* The DSP channel can be used either for input or output. Variable
* 'sb_irq_mode' will be set when the program calls read or write first time
* after open. Current version doesn't support mode changes without closing
* and reopening the device. Support for this feature may be implemented in a
* future version of this driver.
*/
static int v_midi_open (int dev, int mode,
void (*input) (int dev, unsigned char data),
void (*output) (int dev)
)
{
vmidi_devc *devc = midi_devs[dev]->devc;
unsigned long flags;
if (devc == NULL)
return -(ENXIO);
spin_lock_irqsave(&devc->lock,flags);
if (devc->opened)
{
spin_unlock_irqrestore(&devc->lock,flags);
return -(EBUSY);
}
devc->opened = 1;
spin_unlock_irqrestore(&devc->lock,flags);
devc->intr_active = 1;
if (mode & OPEN_READ)
{
devc->input_opened = 1;
devc->midi_input_intr = input;
}
return 0;
}
static void v_midi_close (int dev)
{
vmidi_devc *devc = midi_devs[dev]->devc;
unsigned long flags;
if (devc == NULL)
return;
spin_lock_irqsave(&devc->lock,flags);
devc->intr_active = 0;
devc->input_opened = 0;
devc->opened = 0;
spin_unlock_irqrestore(&devc->lock,flags);
}
static int v_midi_out (int dev, unsigned char midi_byte)
{
vmidi_devc *devc = midi_devs[dev]->devc;
vmidi_devc *pdevc;
if (devc == NULL)
return -ENXIO;
pdevc = midi_devs[devc->pair_mididev]->devc;
if (pdevc->input_opened > 0){
if (MIDIbuf_avail(pdevc->my_mididev) > 500)
return 0;
pdevc->midi_input_intr (pdevc->my_mididev, midi_byte);
}
return 1;
}
static inline int v_midi_start_read (int dev)
{
return 0;
}
static int v_midi_end_read (int dev)
{
vmidi_devc *devc = midi_devs[dev]->devc;
if (devc == NULL)
return -ENXIO;
devc->intr_active = 0;
return 0;
}
/* why -EPERM and not -EINVAL?? */
static inline int v_midi_ioctl (int dev, unsigned cmd, void __user *arg)
{
return -EPERM;
}
#define MIDI_SYNTH_NAME "Loopback MIDI"
#define MIDI_SYNTH_CAPS SYNTH_CAP_INPUT
#include "midi_synth.h"
static struct midi_operations v_midi_operations =
{
.owner = THIS_MODULE,
.info = {"Loopback MIDI Port 1", 0, 0, SNDCARD_VMIDI},
.converter = &std_midi_synth,
.in_info = {0},
.open = v_midi_open,
.close = v_midi_close,
.ioctl = v_midi_ioctl,
.outputc = v_midi_out,
.start_read = v_midi_start_read,
.end_read = v_midi_end_read,
};
static struct midi_operations v_midi_operations2 =
{
.owner = THIS_MODULE,
.info = {"Loopback MIDI Port 2", 0, 0, SNDCARD_VMIDI},
.converter = &std_midi_synth,
.in_info = {0},
.open = v_midi_open,
.close = v_midi_close,
.ioctl = v_midi_ioctl,
.outputc = v_midi_out,
.start_read = v_midi_start_read,
.end_read = v_midi_end_read,
};
/*
* We kmalloc just one of these - it makes life simpler and the code
* cleaner and the memory handling far more efficient
*/
struct vmidi_memory
{
/* Must be first */
struct midi_operations m_ops[2];
struct synth_operations s_ops[2];
struct vmidi_devc v_ops[2];
};
static void __init attach_v_midi (struct address_info *hw_config)
{
struct vmidi_memory *m;
/* printk("Attaching v_midi device.....\n"); */
midi1 = sound_alloc_mididev();
if (midi1 == -1)
{
printk(KERN_ERR "v_midi: Too many midi devices detected\n");
return;
}
m = kmalloc(sizeof(struct vmidi_memory), GFP_KERNEL);
if (m == NULL)
{
printk(KERN_WARNING "Loopback MIDI: Failed to allocate memory\n");
sound_unload_mididev(midi1);
return;
}
midi_mem = m;
midi_devs[midi1] = &m->m_ops[0];
midi2 = sound_alloc_mididev();
if (midi2 == -1)
{
printk (KERN_ERR "v_midi: Too many midi devices detected\n");
kfree(m);
sound_unload_mididev(midi1);
return;
}
midi_devs[midi2] = &m->m_ops[1];
/* printk("VMIDI1: %d VMIDI2: %d\n",midi1,midi2); */
/* for MIDI-1 */
v_devc[0] = &m->v_ops[0];
memcpy ((char *) midi_devs[midi1], (char *) &v_midi_operations,
sizeof (struct midi_operations));
v_devc[0]->my_mididev = midi1;
v_devc[0]->pair_mididev = midi2;
v_devc[0]->opened = v_devc[0]->input_opened = 0;
v_devc[0]->intr_active = 0;
v_devc[0]->midi_input_intr = NULL;
spin_lock_init(&v_devc[0]->lock);
midi_devs[midi1]->devc = v_devc[0];
midi_devs[midi1]->converter = &m->s_ops[0];
std_midi_synth.midi_dev = midi1;
memcpy ((char *) midi_devs[midi1]->converter, (char *) &std_midi_synth,
sizeof (struct synth_operations));
midi_devs[midi1]->converter->id = "V_MIDI 1";
/* for MIDI-2 */
v_devc[1] = &m->v_ops[1];
memcpy ((char *) midi_devs[midi2], (char *) &v_midi_operations2,
sizeof (struct midi_operations));
v_devc[1]->my_mididev = midi2;
v_devc[1]->pair_mididev = midi1;
v_devc[1]->opened = v_devc[1]->input_opened = 0;
v_devc[1]->intr_active = 0;
v_devc[1]->midi_input_intr = NULL;
spin_lock_init(&v_devc[1]->lock);
midi_devs[midi2]->devc = v_devc[1];
midi_devs[midi2]->converter = &m->s_ops[1];
std_midi_synth.midi_dev = midi2;
memcpy ((char *) midi_devs[midi2]->converter, (char *) &std_midi_synth,
sizeof (struct synth_operations));
midi_devs[midi2]->converter->id = "V_MIDI 2";
sequencer_init();
/* printk("Attached v_midi device\n"); */
}
static inline int __init probe_v_midi(struct address_info *hw_config)
{
return(1); /* always OK */
}
static void __exit unload_v_midi(struct address_info *hw_config)
{
sound_unload_mididev(midi1);
sound_unload_mididev(midi2);
kfree(midi_mem);
}
static struct address_info cfg; /* dummy */
static int __init init_vmidi(void)
{
printk("MIDI Loopback device driver\n");
if (!probe_v_midi(&cfg))
return -ENODEV;
attach_v_midi(&cfg);
return 0;
}
static void __exit cleanup_vmidi(void)
{
unload_v_midi(&cfg);
}
module_init(init_vmidi);
module_exit(cleanup_vmidi);
MODULE_LICENSE("GPL");
| gpl-2.0 |
anshulsahni/linux | sound/oss/v_midi.c | 12721 | 6457 | /*
* sound/oss/v_midi.c
*
* The low level driver for the Sound Blaster DS chips.
*
*
* Copyright (C) by Hannu Savolainen 1993-1996
*
* USS/Lite for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
* ??
*
* Changes
* Alan Cox Modularisation, changed memory allocations
* Christoph Hellwig Adapted to module_init/module_exit
*
* Status
* Untested
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include "sound_config.h"
#include "v_midi.h"
static vmidi_devc *v_devc[2] = { NULL, NULL};
static int midi1,midi2;
static void *midi_mem = NULL;
/*
* The DSP channel can be used either for input or output. Variable
* 'sb_irq_mode' will be set when the program calls read or write first time
* after open. Current version doesn't support mode changes without closing
* and reopening the device. Support for this feature may be implemented in a
* future version of this driver.
*/
static int v_midi_open (int dev, int mode,
void (*input) (int dev, unsigned char data),
void (*output) (int dev)
)
{
vmidi_devc *devc = midi_devs[dev]->devc;
unsigned long flags;
if (devc == NULL)
return -(ENXIO);
spin_lock_irqsave(&devc->lock,flags);
if (devc->opened)
{
spin_unlock_irqrestore(&devc->lock,flags);
return -(EBUSY);
}
devc->opened = 1;
spin_unlock_irqrestore(&devc->lock,flags);
devc->intr_active = 1;
if (mode & OPEN_READ)
{
devc->input_opened = 1;
devc->midi_input_intr = input;
}
return 0;
}
static void v_midi_close (int dev)
{
vmidi_devc *devc = midi_devs[dev]->devc;
unsigned long flags;
if (devc == NULL)
return;
spin_lock_irqsave(&devc->lock,flags);
devc->intr_active = 0;
devc->input_opened = 0;
devc->opened = 0;
spin_unlock_irqrestore(&devc->lock,flags);
}
static int v_midi_out (int dev, unsigned char midi_byte)
{
vmidi_devc *devc = midi_devs[dev]->devc;
vmidi_devc *pdevc;
if (devc == NULL)
return -ENXIO;
pdevc = midi_devs[devc->pair_mididev]->devc;
if (pdevc->input_opened > 0){
if (MIDIbuf_avail(pdevc->my_mididev) > 500)
return 0;
pdevc->midi_input_intr (pdevc->my_mididev, midi_byte);
}
return 1;
}
static inline int v_midi_start_read (int dev)
{
return 0;
}
static int v_midi_end_read (int dev)
{
vmidi_devc *devc = midi_devs[dev]->devc;
if (devc == NULL)
return -ENXIO;
devc->intr_active = 0;
return 0;
}
/* why -EPERM and not -EINVAL?? */
static inline int v_midi_ioctl (int dev, unsigned cmd, void __user *arg)
{
return -EPERM;
}
#define MIDI_SYNTH_NAME "Loopback MIDI"
#define MIDI_SYNTH_CAPS SYNTH_CAP_INPUT
#include "midi_synth.h"
static struct midi_operations v_midi_operations =
{
.owner = THIS_MODULE,
.info = {"Loopback MIDI Port 1", 0, 0, SNDCARD_VMIDI},
.converter = &std_midi_synth,
.in_info = {0},
.open = v_midi_open,
.close = v_midi_close,
.ioctl = v_midi_ioctl,
.outputc = v_midi_out,
.start_read = v_midi_start_read,
.end_read = v_midi_end_read,
};
static struct midi_operations v_midi_operations2 =
{
.owner = THIS_MODULE,
.info = {"Loopback MIDI Port 2", 0, 0, SNDCARD_VMIDI},
.converter = &std_midi_synth,
.in_info = {0},
.open = v_midi_open,
.close = v_midi_close,
.ioctl = v_midi_ioctl,
.outputc = v_midi_out,
.start_read = v_midi_start_read,
.end_read = v_midi_end_read,
};
/*
* We kmalloc just one of these - it makes life simpler and the code
* cleaner and the memory handling far more efficient
*/
struct vmidi_memory
{
/* Must be first */
struct midi_operations m_ops[2];
struct synth_operations s_ops[2];
struct vmidi_devc v_ops[2];
};
static void __init attach_v_midi (struct address_info *hw_config)
{
struct vmidi_memory *m;
/* printk("Attaching v_midi device.....\n"); */
midi1 = sound_alloc_mididev();
if (midi1 == -1)
{
printk(KERN_ERR "v_midi: Too many midi devices detected\n");
return;
}
m = kmalloc(sizeof(struct vmidi_memory), GFP_KERNEL);
if (m == NULL)
{
printk(KERN_WARNING "Loopback MIDI: Failed to allocate memory\n");
sound_unload_mididev(midi1);
return;
}
midi_mem = m;
midi_devs[midi1] = &m->m_ops[0];
midi2 = sound_alloc_mididev();
if (midi2 == -1)
{
printk (KERN_ERR "v_midi: Too many midi devices detected\n");
kfree(m);
sound_unload_mididev(midi1);
return;
}
midi_devs[midi2] = &m->m_ops[1];
/* printk("VMIDI1: %d VMIDI2: %d\n",midi1,midi2); */
/* for MIDI-1 */
v_devc[0] = &m->v_ops[0];
memcpy ((char *) midi_devs[midi1], (char *) &v_midi_operations,
sizeof (struct midi_operations));
v_devc[0]->my_mididev = midi1;
v_devc[0]->pair_mididev = midi2;
v_devc[0]->opened = v_devc[0]->input_opened = 0;
v_devc[0]->intr_active = 0;
v_devc[0]->midi_input_intr = NULL;
spin_lock_init(&v_devc[0]->lock);
midi_devs[midi1]->devc = v_devc[0];
midi_devs[midi1]->converter = &m->s_ops[0];
std_midi_synth.midi_dev = midi1;
memcpy ((char *) midi_devs[midi1]->converter, (char *) &std_midi_synth,
sizeof (struct synth_operations));
midi_devs[midi1]->converter->id = "V_MIDI 1";
/* for MIDI-2 */
v_devc[1] = &m->v_ops[1];
memcpy ((char *) midi_devs[midi2], (char *) &v_midi_operations2,
sizeof (struct midi_operations));
v_devc[1]->my_mididev = midi2;
v_devc[1]->pair_mididev = midi1;
v_devc[1]->opened = v_devc[1]->input_opened = 0;
v_devc[1]->intr_active = 0;
v_devc[1]->midi_input_intr = NULL;
spin_lock_init(&v_devc[1]->lock);
midi_devs[midi2]->devc = v_devc[1];
midi_devs[midi2]->converter = &m->s_ops[1];
std_midi_synth.midi_dev = midi2;
memcpy ((char *) midi_devs[midi2]->converter, (char *) &std_midi_synth,
sizeof (struct synth_operations));
midi_devs[midi2]->converter->id = "V_MIDI 2";
sequencer_init();
/* printk("Attached v_midi device\n"); */
}
static inline int __init probe_v_midi(struct address_info *hw_config)
{
return(1); /* always OK */
}
static void __exit unload_v_midi(struct address_info *hw_config)
{
sound_unload_mididev(midi1);
sound_unload_mididev(midi2);
kfree(midi_mem);
}
static struct address_info cfg; /* dummy */
static int __init init_vmidi(void)
{
printk("MIDI Loopback device driver\n");
if (!probe_v_midi(&cfg))
return -ENODEV;
attach_v_midi(&cfg);
return 0;
}
static void __exit cleanup_vmidi(void)
{
unload_v_midi(&cfg);
}
module_init(init_vmidi);
module_exit(cleanup_vmidi);
MODULE_LICENSE("GPL");
| gpl-2.0 |
boa19861105/android_LP5.0.2_kernel_htc_dlxpul | drivers/net/bonding/bond_main.c | 434 | 133021 | /*
* originally based on the dummy device.
*
* Copyright 1999, Thomas Davis, tadavis@lbl.gov.
* Licensed under the GPL. Based on dummy.c, and eql.c devices.
*
* bonding.c: an Ethernet Bonding driver
*
* This is useful to talk to a Cisco EtherChannel compatible equipment:
* Cisco 5500
* Sun Trunking (Solaris)
* Alteon AceDirector Trunks
* Linux Bonding
* and probably many L2 switches ...
*
* How it works:
* ifconfig bond0 ipaddress netmask up
* will setup a network device, with an ip address. No mac address
* will be assigned at this time. The hw mac address will come from
* the first slave bonded to the channel. All slaves will then use
* this hw mac address.
*
* ifconfig bond0 down
* will release all slaves, marking them as down.
*
* ifenslave bond0 eth0
* will attach eth0 to bond0 as a slave. eth0 hw mac address will either
* a: be used as initial mac address
* b: if a hw mac address already is there, eth0's hw mac address
* will then be set from bond0.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/interrupt.h>
#include <linux/ptrace.h>
#include <linux/ioport.h>
#include <linux/in.h>
#include <net/ip.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/socket.h>
#include <linux/ctype.h>
#include <linux/inet.h>
#include <linux/bitops.h>
#include <linux/io.h>
#include <asm/dma.h>
#include <linux/uaccess.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/inetdevice.h>
#include <linux/igmp.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/rtnetlink.h>
#include <linux/smp.h>
#include <linux/if_ether.h>
#include <net/arp.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/if_vlan.h>
#include <linux/if_bonding.h>
#include <linux/jiffies.h>
#include <linux/preempt.h>
#include <net/route.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/pkt_sched.h>
#include "bonding.h"
#include "bond_3ad.h"
#include "bond_alb.h"
/*---------------------------- Module parameters ----------------------------*/
/* monitor all links that often (in milliseconds). <=0 disables monitoring */
#define BOND_LINK_MON_INTERV 0
#define BOND_LINK_ARP_INTERV 0
static int max_bonds = BOND_DEFAULT_MAX_BONDS;
static int tx_queues = BOND_DEFAULT_TX_QUEUES;
static int num_peer_notif = 1;
static int miimon = BOND_LINK_MON_INTERV;
static int updelay;
static int downdelay;
static int use_carrier = 1;
static char *mode;
static char *primary;
static char *primary_reselect;
static char *lacp_rate;
static int min_links;
static char *ad_select;
static char *xmit_hash_policy;
static int arp_interval = BOND_LINK_ARP_INTERV;
static char *arp_ip_target[BOND_MAX_ARP_TARGETS];
static char *arp_validate;
static char *fail_over_mac;
static int all_slaves_active = 0;
static struct bond_params bonding_defaults;
static int resend_igmp = BOND_DEFAULT_RESEND_IGMP;
module_param(max_bonds, int, 0);
MODULE_PARM_DESC(max_bonds, "Max number of bonded devices");
module_param(tx_queues, int, 0);
MODULE_PARM_DESC(tx_queues, "Max number of transmit queues (default = 16)");
module_param_named(num_grat_arp, num_peer_notif, int, 0644);
MODULE_PARM_DESC(num_grat_arp, "Number of peer notifications to send on "
"failover event (alias of num_unsol_na)");
module_param_named(num_unsol_na, num_peer_notif, int, 0644);
MODULE_PARM_DESC(num_unsol_na, "Number of peer notifications to send on "
"failover event (alias of num_grat_arp)");
module_param(miimon, int, 0);
MODULE_PARM_DESC(miimon, "Link check interval in milliseconds");
module_param(updelay, int, 0);
MODULE_PARM_DESC(updelay, "Delay before considering link up, in milliseconds");
module_param(downdelay, int, 0);
MODULE_PARM_DESC(downdelay, "Delay before considering link down, "
"in milliseconds");
module_param(use_carrier, int, 0);
MODULE_PARM_DESC(use_carrier, "Use netif_carrier_ok (vs MII ioctls) in miimon; "
"0 for off, 1 for on (default)");
module_param(mode, charp, 0);
MODULE_PARM_DESC(mode, "Mode of operation; 0 for balance-rr, "
"1 for active-backup, 2 for balance-xor, "
"3 for broadcast, 4 for 802.3ad, 5 for balance-tlb, "
"6 for balance-alb");
module_param(primary, charp, 0);
MODULE_PARM_DESC(primary, "Primary network device to use");
module_param(primary_reselect, charp, 0);
MODULE_PARM_DESC(primary_reselect, "Reselect primary slave "
"once it comes up; "
"0 for always (default), "
"1 for only if speed of primary is "
"better, "
"2 for only on active slave "
"failure");
module_param(lacp_rate, charp, 0);
MODULE_PARM_DESC(lacp_rate, "LACPDU tx rate to request from 802.3ad partner; "
"0 for slow, 1 for fast");
module_param(ad_select, charp, 0);
MODULE_PARM_DESC(ad_select, "803.ad aggregation selection logic; "
"0 for stable (default), 1 for bandwidth, "
"2 for count");
module_param(min_links, int, 0);
MODULE_PARM_DESC(min_links, "Minimum number of available links before turning on carrier");
module_param(xmit_hash_policy, charp, 0);
MODULE_PARM_DESC(xmit_hash_policy, "balance-xor and 802.3ad hashing method; "
"0 for layer 2 (default), 1 for layer 3+4, "
"2 for layer 2+3");
module_param(arp_interval, int, 0);
MODULE_PARM_DESC(arp_interval, "arp interval in milliseconds");
module_param_array(arp_ip_target, charp, NULL, 0);
MODULE_PARM_DESC(arp_ip_target, "arp targets in n.n.n.n form");
module_param(arp_validate, charp, 0);
MODULE_PARM_DESC(arp_validate, "validate src/dst of ARP probes; "
"0 for none (default), 1 for active, "
"2 for backup, 3 for all");
module_param(fail_over_mac, charp, 0);
MODULE_PARM_DESC(fail_over_mac, "For active-backup, do not set all slaves to "
"the same MAC; 0 for none (default), "
"1 for active, 2 for follow");
module_param(all_slaves_active, int, 0);
MODULE_PARM_DESC(all_slaves_active, "Keep all frames received on an interface"
"by setting active flag for all slaves; "
"0 for never (default), 1 for always.");
module_param(resend_igmp, int, 0);
MODULE_PARM_DESC(resend_igmp, "Number of IGMP membership reports to send on "
"link failure");
/*----------------------------- Global variables ----------------------------*/
#ifdef CONFIG_NET_POLL_CONTROLLER
atomic_t netpoll_block_tx = ATOMIC_INIT(0);
#endif
int bond_net_id __read_mostly;
static __be32 arp_target[BOND_MAX_ARP_TARGETS];
static int arp_ip_count;
static int bond_mode = BOND_MODE_ROUNDROBIN;
static int xmit_hashtype = BOND_XMIT_POLICY_LAYER2;
static int lacp_fast;
const struct bond_parm_tbl bond_lacp_tbl[] = {
{ "slow", AD_LACP_SLOW},
{ "fast", AD_LACP_FAST},
{ NULL, -1},
};
const struct bond_parm_tbl bond_mode_tbl[] = {
{ "balance-rr", BOND_MODE_ROUNDROBIN},
{ "active-backup", BOND_MODE_ACTIVEBACKUP},
{ "balance-xor", BOND_MODE_XOR},
{ "broadcast", BOND_MODE_BROADCAST},
{ "802.3ad", BOND_MODE_8023AD},
{ "balance-tlb", BOND_MODE_TLB},
{ "balance-alb", BOND_MODE_ALB},
{ NULL, -1},
};
const struct bond_parm_tbl xmit_hashtype_tbl[] = {
{ "layer2", BOND_XMIT_POLICY_LAYER2},
{ "layer3+4", BOND_XMIT_POLICY_LAYER34},
{ "layer2+3", BOND_XMIT_POLICY_LAYER23},
{ NULL, -1},
};
const struct bond_parm_tbl arp_validate_tbl[] = {
{ "none", BOND_ARP_VALIDATE_NONE},
{ "active", BOND_ARP_VALIDATE_ACTIVE},
{ "backup", BOND_ARP_VALIDATE_BACKUP},
{ "all", BOND_ARP_VALIDATE_ALL},
{ NULL, -1},
};
const struct bond_parm_tbl fail_over_mac_tbl[] = {
{ "none", BOND_FOM_NONE},
{ "active", BOND_FOM_ACTIVE},
{ "follow", BOND_FOM_FOLLOW},
{ NULL, -1},
};
const struct bond_parm_tbl pri_reselect_tbl[] = {
{ "always", BOND_PRI_RESELECT_ALWAYS},
{ "better", BOND_PRI_RESELECT_BETTER},
{ "failure", BOND_PRI_RESELECT_FAILURE},
{ NULL, -1},
};
struct bond_parm_tbl ad_select_tbl[] = {
{ "stable", BOND_AD_STABLE},
{ "bandwidth", BOND_AD_BANDWIDTH},
{ "count", BOND_AD_COUNT},
{ NULL, -1},
};
/*-------------------------- Forward declarations ---------------------------*/
static int bond_init(struct net_device *bond_dev);
static void bond_uninit(struct net_device *bond_dev);
/*---------------------------- General routines -----------------------------*/
const char *bond_mode_name(int mode)
{
static const char *names[] = {
[BOND_MODE_ROUNDROBIN] = "load balancing (round-robin)",
[BOND_MODE_ACTIVEBACKUP] = "fault-tolerance (active-backup)",
[BOND_MODE_XOR] = "load balancing (xor)",
[BOND_MODE_BROADCAST] = "fault-tolerance (broadcast)",
[BOND_MODE_8023AD] = "IEEE 802.3ad Dynamic link aggregation",
[BOND_MODE_TLB] = "transmit load balancing",
[BOND_MODE_ALB] = "adaptive load balancing",
};
if (mode < 0 || mode > BOND_MODE_ALB)
return "unknown";
return names[mode];
}
/*---------------------------------- VLAN -----------------------------------*/
/**
* bond_add_vlan - add a new vlan id on bond
* @bond: bond that got the notification
* @vlan_id: the vlan id to add
*
* Returns -ENOMEM if allocation failed.
*/
static int bond_add_vlan(struct bonding *bond, unsigned short vlan_id)
{
struct vlan_entry *vlan;
pr_debug("bond: %s, vlan id %d\n",
(bond ? bond->dev->name : "None"), vlan_id);
vlan = kzalloc(sizeof(struct vlan_entry), GFP_KERNEL);
if (!vlan)
return -ENOMEM;
INIT_LIST_HEAD(&vlan->vlan_list);
vlan->vlan_id = vlan_id;
write_lock_bh(&bond->lock);
list_add_tail(&vlan->vlan_list, &bond->vlan_list);
write_unlock_bh(&bond->lock);
pr_debug("added VLAN ID %d on bond %s\n", vlan_id, bond->dev->name);
return 0;
}
/**
* bond_del_vlan - delete a vlan id from bond
* @bond: bond that got the notification
* @vlan_id: the vlan id to delete
*
* returns -ENODEV if @vlan_id was not found in @bond.
*/
static int bond_del_vlan(struct bonding *bond, unsigned short vlan_id)
{
struct vlan_entry *vlan;
int res = -ENODEV;
pr_debug("bond: %s, vlan id %d\n", bond->dev->name, vlan_id);
block_netpoll_tx();
write_lock_bh(&bond->lock);
list_for_each_entry(vlan, &bond->vlan_list, vlan_list) {
if (vlan->vlan_id == vlan_id) {
list_del(&vlan->vlan_list);
if (bond_is_lb(bond))
bond_alb_clear_vlan(bond, vlan_id);
pr_debug("removed VLAN ID %d from bond %s\n",
vlan_id, bond->dev->name);
kfree(vlan);
res = 0;
goto out;
}
}
pr_debug("couldn't find VLAN ID %d in bond %s\n",
vlan_id, bond->dev->name);
out:
write_unlock_bh(&bond->lock);
unblock_netpoll_tx();
return res;
}
/**
* bond_next_vlan - safely skip to the next item in the vlans list.
* @bond: the bond we're working on
* @curr: item we're advancing from
*
* Returns %NULL if list is empty, bond->next_vlan if @curr is %NULL,
* or @curr->next otherwise (even if it is @curr itself again).
*
* Caller must hold bond->lock
*/
struct vlan_entry *bond_next_vlan(struct bonding *bond, struct vlan_entry *curr)
{
struct vlan_entry *next, *last;
if (list_empty(&bond->vlan_list))
return NULL;
if (!curr) {
next = list_entry(bond->vlan_list.next,
struct vlan_entry, vlan_list);
} else {
last = list_entry(bond->vlan_list.prev,
struct vlan_entry, vlan_list);
if (last == curr) {
next = list_entry(bond->vlan_list.next,
struct vlan_entry, vlan_list);
} else {
next = list_entry(curr->vlan_list.next,
struct vlan_entry, vlan_list);
}
}
return next;
}
/**
* bond_dev_queue_xmit - Prepare skb for xmit.
*
* @bond: bond device that got this skb for tx.
* @skb: hw accel VLAN tagged skb to transmit
* @slave_dev: slave that is supposed to xmit this skbuff
*/
int bond_dev_queue_xmit(struct bonding *bond, struct sk_buff *skb,
struct net_device *slave_dev)
{
skb->dev = slave_dev;
BUILD_BUG_ON(sizeof(skb->queue_mapping) !=
sizeof(qdisc_skb_cb(skb)->bond_queue_mapping));
skb->queue_mapping = qdisc_skb_cb(skb)->bond_queue_mapping;
if (unlikely(netpoll_tx_running(slave_dev)))
bond_netpoll_send_skb(bond_get_slave_by_dev(bond, slave_dev), skb);
else
dev_queue_xmit(skb);
return 0;
}
/*
* In the following 2 functions, bond_vlan_rx_add_vid and bond_vlan_rx_kill_vid,
* We don't protect the slave list iteration with a lock because:
* a. This operation is performed in IOCTL context,
* b. The operation is protected by the RTNL semaphore in the 8021q code,
* c. Holding a lock with BH disabled while directly calling a base driver
* entry point is generally a BAD idea.
*
* The design of synchronization/protection for this operation in the 8021q
* module is good for one or more VLAN devices over a single physical device
* and cannot be extended for a teaming solution like bonding, so there is a
* potential race condition here where a net device from the vlan group might
* be referenced (either by a base driver or the 8021q code) while it is being
* removed from the system. However, it turns out we're not making matters
* worse, and if it works for regular VLAN usage it will work here too.
*/
/**
* bond_vlan_rx_add_vid - Propagates adding an id to slaves
* @bond_dev: bonding net device that got called
* @vid: vlan id being added
*/
static int bond_vlan_rx_add_vid(struct net_device *bond_dev, uint16_t vid)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave, *stop_at;
int i, res;
bond_for_each_slave(bond, slave, i) {
res = vlan_vid_add(slave->dev, vid);
if (res)
goto unwind;
}
res = bond_add_vlan(bond, vid);
if (res) {
pr_err("%s: Error: Failed to add vlan id %d\n",
bond_dev->name, vid);
return res;
}
return 0;
unwind:
/* unwind from head to the slave that failed */
stop_at = slave;
bond_for_each_slave_from_to(bond, slave, i, bond->first_slave, stop_at)
vlan_vid_del(slave->dev, vid);
return res;
}
/**
* bond_vlan_rx_kill_vid - Propagates deleting an id to slaves
* @bond_dev: bonding net device that got called
* @vid: vlan id being removed
*/
static int bond_vlan_rx_kill_vid(struct net_device *bond_dev, uint16_t vid)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave;
int i, res;
bond_for_each_slave(bond, slave, i)
vlan_vid_del(slave->dev, vid);
res = bond_del_vlan(bond, vid);
if (res) {
pr_err("%s: Error: Failed to remove vlan id %d\n",
bond_dev->name, vid);
return res;
}
return 0;
}
static void bond_add_vlans_on_slave(struct bonding *bond, struct net_device *slave_dev)
{
struct vlan_entry *vlan;
int res;
list_for_each_entry(vlan, &bond->vlan_list, vlan_list) {
res = vlan_vid_add(slave_dev, vlan->vlan_id);
if (res)
pr_warning("%s: Failed to add vlan id %d to device %s\n",
bond->dev->name, vlan->vlan_id,
slave_dev->name);
}
}
static void bond_del_vlans_from_slave(struct bonding *bond,
struct net_device *slave_dev)
{
struct vlan_entry *vlan;
list_for_each_entry(vlan, &bond->vlan_list, vlan_list) {
if (!vlan->vlan_id)
continue;
vlan_vid_del(slave_dev, vlan->vlan_id);
}
}
/*------------------------------- Link status -------------------------------*/
/*
* Set the carrier state for the master according to the state of its
* slaves. If any slaves are up, the master is up. In 802.3ad mode,
* do special 802.3ad magic.
*
* Returns zero if carrier state does not change, nonzero if it does.
*/
static int bond_set_carrier(struct bonding *bond)
{
struct slave *slave;
int i;
if (bond->slave_cnt == 0)
goto down;
if (bond->params.mode == BOND_MODE_8023AD)
return bond_3ad_set_carrier(bond);
bond_for_each_slave(bond, slave, i) {
if (slave->link == BOND_LINK_UP) {
if (!netif_carrier_ok(bond->dev)) {
netif_carrier_on(bond->dev);
return 1;
}
return 0;
}
}
down:
if (netif_carrier_ok(bond->dev)) {
netif_carrier_off(bond->dev);
return 1;
}
return 0;
}
/*
* Get link speed and duplex from the slave's base driver
* using ethtool. If for some reason the call fails or the
* values are invalid, set speed and duplex to -1,
* and return error.
*/
static int bond_update_speed_duplex(struct slave *slave)
{
struct net_device *slave_dev = slave->dev;
struct ethtool_cmd ecmd;
u32 slave_speed;
int res;
slave->speed = SPEED_UNKNOWN;
slave->duplex = DUPLEX_UNKNOWN;
res = __ethtool_get_settings(slave_dev, &ecmd);
if (res < 0)
return -1;
slave_speed = ethtool_cmd_speed(&ecmd);
if (slave_speed == 0 || slave_speed == ((__u32) -1))
return -1;
switch (ecmd.duplex) {
case DUPLEX_FULL:
case DUPLEX_HALF:
break;
default:
return -1;
}
slave->speed = slave_speed;
slave->duplex = ecmd.duplex;
return 0;
}
/*
* if <dev> supports MII link status reporting, check its link status.
*
* We either do MII/ETHTOOL ioctls, or check netif_carrier_ok(),
* depending upon the setting of the use_carrier parameter.
*
* Return either BMSR_LSTATUS, meaning that the link is up (or we
* can't tell and just pretend it is), or 0, meaning that the link is
* down.
*
* If reporting is non-zero, instead of faking link up, return -1 if
* both ETHTOOL and MII ioctls fail (meaning the device does not
* support them). If use_carrier is set, return whatever it says.
* It'd be nice if there was a good way to tell if a driver supports
* netif_carrier, but there really isn't.
*/
static int bond_check_dev_link(struct bonding *bond,
struct net_device *slave_dev, int reporting)
{
const struct net_device_ops *slave_ops = slave_dev->netdev_ops;
int (*ioctl)(struct net_device *, struct ifreq *, int);
struct ifreq ifr;
struct mii_ioctl_data *mii;
if (!reporting && !netif_running(slave_dev))
return 0;
if (bond->params.use_carrier)
return netif_carrier_ok(slave_dev) ? BMSR_LSTATUS : 0;
/* Try to get link status using Ethtool first. */
if (slave_dev->ethtool_ops) {
if (slave_dev->ethtool_ops->get_link) {
u32 link;
link = slave_dev->ethtool_ops->get_link(slave_dev);
return link ? BMSR_LSTATUS : 0;
}
}
/* Ethtool can't be used, fallback to MII ioctls. */
ioctl = slave_ops->ndo_do_ioctl;
if (ioctl) {
/* TODO: set pointer to correct ioctl on a per team member */
/* bases to make this more efficient. that is, once */
/* we determine the correct ioctl, we will always */
/* call it and not the others for that team */
/* member. */
/*
* We cannot assume that SIOCGMIIPHY will also read a
* register; not all network drivers (e.g., e100)
* support that.
*/
/* Yes, the mii is overlaid on the ifreq.ifr_ifru */
strncpy(ifr.ifr_name, slave_dev->name, IFNAMSIZ);
mii = if_mii(&ifr);
if (IOCTL(slave_dev, &ifr, SIOCGMIIPHY) == 0) {
mii->reg_num = MII_BMSR;
if (IOCTL(slave_dev, &ifr, SIOCGMIIREG) == 0)
return mii->val_out & BMSR_LSTATUS;
}
}
/*
* If reporting, report that either there's no dev->do_ioctl,
* or both SIOCGMIIREG and get_link failed (meaning that we
* cannot report link status). If not reporting, pretend
* we're ok.
*/
return reporting ? -1 : BMSR_LSTATUS;
}
/*----------------------------- Multicast list ------------------------------*/
/*
* Push the promiscuity flag down to appropriate slaves
*/
static int bond_set_promiscuity(struct bonding *bond, int inc)
{
int err = 0;
if (USES_PRIMARY(bond->params.mode)) {
/* write lock already acquired */
if (bond->curr_active_slave) {
err = dev_set_promiscuity(bond->curr_active_slave->dev,
inc);
}
} else {
struct slave *slave;
int i;
bond_for_each_slave(bond, slave, i) {
err = dev_set_promiscuity(slave->dev, inc);
if (err)
return err;
}
}
return err;
}
/*
* Push the allmulti flag down to all slaves
*/
static int bond_set_allmulti(struct bonding *bond, int inc)
{
int err = 0;
if (USES_PRIMARY(bond->params.mode)) {
/* write lock already acquired */
if (bond->curr_active_slave) {
err = dev_set_allmulti(bond->curr_active_slave->dev,
inc);
}
} else {
struct slave *slave;
int i;
bond_for_each_slave(bond, slave, i) {
err = dev_set_allmulti(slave->dev, inc);
if (err)
return err;
}
}
return err;
}
/*
* Add a Multicast address to slaves
* according to mode
*/
static void bond_mc_add(struct bonding *bond, void *addr)
{
if (USES_PRIMARY(bond->params.mode)) {
/* write lock already acquired */
if (bond->curr_active_slave)
dev_mc_add(bond->curr_active_slave->dev, addr);
} else {
struct slave *slave;
int i;
bond_for_each_slave(bond, slave, i)
dev_mc_add(slave->dev, addr);
}
}
/*
* Remove a multicast address from slave
* according to mode
*/
static void bond_mc_del(struct bonding *bond, void *addr)
{
if (USES_PRIMARY(bond->params.mode)) {
/* write lock already acquired */
if (bond->curr_active_slave)
dev_mc_del(bond->curr_active_slave->dev, addr);
} else {
struct slave *slave;
int i;
bond_for_each_slave(bond, slave, i) {
dev_mc_del(slave->dev, addr);
}
}
}
static void __bond_resend_igmp_join_requests(struct net_device *dev)
{
struct in_device *in_dev;
rcu_read_lock();
in_dev = __in_dev_get_rcu(dev);
if (in_dev)
ip_mc_rejoin_groups(in_dev);
rcu_read_unlock();
}
/*
* Retrieve the list of registered multicast addresses for the bonding
* device and retransmit an IGMP JOIN request to the current active
* slave.
*/
static void bond_resend_igmp_join_requests(struct bonding *bond)
{
struct net_device *bond_dev, *vlan_dev, *master_dev;
struct vlan_entry *vlan;
read_lock(&bond->lock);
bond_dev = bond->dev;
/* rejoin all groups on bond device */
__bond_resend_igmp_join_requests(bond_dev);
/*
* if bond is enslaved to a bridge,
* then rejoin all groups on its master
*/
master_dev = bond_dev->master;
if (master_dev)
if ((master_dev->priv_flags & IFF_EBRIDGE)
&& (bond_dev->priv_flags & IFF_BRIDGE_PORT))
__bond_resend_igmp_join_requests(master_dev);
/* rejoin all groups on vlan devices */
list_for_each_entry(vlan, &bond->vlan_list, vlan_list) {
rcu_read_lock();
vlan_dev = __vlan_find_dev_deep(bond_dev,
vlan->vlan_id);
rcu_read_unlock();
if (vlan_dev)
__bond_resend_igmp_join_requests(vlan_dev);
}
if (--bond->igmp_retrans > 0)
queue_delayed_work(bond->wq, &bond->mcast_work, HZ/5);
read_unlock(&bond->lock);
}
static void bond_resend_igmp_join_requests_delayed(struct work_struct *work)
{
struct bonding *bond = container_of(work, struct bonding,
mcast_work.work);
bond_resend_igmp_join_requests(bond);
}
/*
* flush all members of flush->mc_list from device dev->mc_list
*/
static void bond_mc_list_flush(struct net_device *bond_dev,
struct net_device *slave_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct netdev_hw_addr *ha;
netdev_for_each_mc_addr(ha, bond_dev)
dev_mc_del(slave_dev, ha->addr);
if (bond->params.mode == BOND_MODE_8023AD) {
/* del lacpdu mc addr from mc list */
u8 lacpdu_multicast[ETH_ALEN] = MULTICAST_LACPDU_ADDR;
dev_mc_del(slave_dev, lacpdu_multicast);
}
}
/*--------------------------- Active slave change ---------------------------*/
/*
* Update the mc list and multicast-related flags for the new and
* old active slaves (if any) according to the multicast mode, and
* promiscuous flags unconditionally.
*/
static void bond_mc_swap(struct bonding *bond, struct slave *new_active,
struct slave *old_active)
{
struct netdev_hw_addr *ha;
if (!USES_PRIMARY(bond->params.mode))
/* nothing to do - mc list is already up-to-date on
* all slaves
*/
return;
if (old_active) {
if (bond->dev->flags & IFF_PROMISC)
dev_set_promiscuity(old_active->dev, -1);
if (bond->dev->flags & IFF_ALLMULTI)
dev_set_allmulti(old_active->dev, -1);
netdev_for_each_mc_addr(ha, bond->dev)
dev_mc_del(old_active->dev, ha->addr);
}
if (new_active) {
/* FIXME: Signal errors upstream. */
if (bond->dev->flags & IFF_PROMISC)
dev_set_promiscuity(new_active->dev, 1);
if (bond->dev->flags & IFF_ALLMULTI)
dev_set_allmulti(new_active->dev, 1);
netdev_for_each_mc_addr(ha, bond->dev)
dev_mc_add(new_active->dev, ha->addr);
}
}
/*
* bond_do_fail_over_mac
*
* Perform special MAC address swapping for fail_over_mac settings
*
* Called with RTNL, bond->lock for read, curr_slave_lock for write_bh.
*/
static void bond_do_fail_over_mac(struct bonding *bond,
struct slave *new_active,
struct slave *old_active)
__releases(&bond->curr_slave_lock)
__releases(&bond->lock)
__acquires(&bond->lock)
__acquires(&bond->curr_slave_lock)
{
u8 tmp_mac[ETH_ALEN];
struct sockaddr saddr;
int rv;
switch (bond->params.fail_over_mac) {
case BOND_FOM_ACTIVE:
if (new_active) {
memcpy(bond->dev->dev_addr, new_active->dev->dev_addr,
new_active->dev->addr_len);
write_unlock_bh(&bond->curr_slave_lock);
read_unlock(&bond->lock);
call_netdevice_notifiers(NETDEV_CHANGEADDR, bond->dev);
read_lock(&bond->lock);
write_lock_bh(&bond->curr_slave_lock);
}
break;
case BOND_FOM_FOLLOW:
/*
* if new_active && old_active, swap them
* if just old_active, do nothing (going to no active slave)
* if just new_active, set new_active to bond's MAC
*/
if (!new_active)
return;
write_unlock_bh(&bond->curr_slave_lock);
read_unlock(&bond->lock);
if (old_active) {
memcpy(tmp_mac, new_active->dev->dev_addr, ETH_ALEN);
memcpy(saddr.sa_data, old_active->dev->dev_addr,
ETH_ALEN);
saddr.sa_family = new_active->dev->type;
} else {
memcpy(saddr.sa_data, bond->dev->dev_addr, ETH_ALEN);
saddr.sa_family = bond->dev->type;
}
rv = dev_set_mac_address(new_active->dev, &saddr);
if (rv) {
pr_err("%s: Error %d setting MAC of slave %s\n",
bond->dev->name, -rv, new_active->dev->name);
goto out;
}
if (!old_active)
goto out;
memcpy(saddr.sa_data, tmp_mac, ETH_ALEN);
saddr.sa_family = old_active->dev->type;
rv = dev_set_mac_address(old_active->dev, &saddr);
if (rv)
pr_err("%s: Error %d setting MAC of slave %s\n",
bond->dev->name, -rv, new_active->dev->name);
out:
read_lock(&bond->lock);
write_lock_bh(&bond->curr_slave_lock);
break;
default:
pr_err("%s: bond_do_fail_over_mac impossible: bad policy %d\n",
bond->dev->name, bond->params.fail_over_mac);
break;
}
}
static bool bond_should_change_active(struct bonding *bond)
{
struct slave *prim = bond->primary_slave;
struct slave *curr = bond->curr_active_slave;
if (!prim || !curr || curr->link != BOND_LINK_UP)
return true;
if (bond->force_primary) {
bond->force_primary = false;
return true;
}
if (bond->params.primary_reselect == BOND_PRI_RESELECT_BETTER &&
(prim->speed < curr->speed ||
(prim->speed == curr->speed && prim->duplex <= curr->duplex)))
return false;
if (bond->params.primary_reselect == BOND_PRI_RESELECT_FAILURE)
return false;
return true;
}
/**
* find_best_interface - select the best available slave to be the active one
* @bond: our bonding struct
*
* Warning: Caller must hold curr_slave_lock for writing.
*/
static struct slave *bond_find_best_slave(struct bonding *bond)
{
struct slave *new_active, *old_active;
struct slave *bestslave = NULL;
int mintime = bond->params.updelay;
int i;
new_active = bond->curr_active_slave;
if (!new_active) { /* there were no active slaves left */
if (bond->slave_cnt > 0) /* found one slave */
new_active = bond->first_slave;
else
return NULL; /* still no slave, return NULL */
}
if ((bond->primary_slave) &&
bond->primary_slave->link == BOND_LINK_UP &&
bond_should_change_active(bond)) {
new_active = bond->primary_slave;
}
/* remember where to stop iterating over the slaves */
old_active = new_active;
bond_for_each_slave_from(bond, new_active, i, old_active) {
if (new_active->link == BOND_LINK_UP) {
return new_active;
} else if (new_active->link == BOND_LINK_BACK &&
IS_UP(new_active->dev)) {
/* link up, but waiting for stabilization */
if (new_active->delay < mintime) {
mintime = new_active->delay;
bestslave = new_active;
}
}
}
return bestslave;
}
static bool bond_should_notify_peers(struct bonding *bond)
{
struct slave *slave = bond->curr_active_slave;
pr_debug("bond_should_notify_peers: bond %s slave %s\n",
bond->dev->name, slave ? slave->dev->name : "NULL");
if (!slave || !bond->send_peer_notif ||
test_bit(__LINK_STATE_LINKWATCH_PENDING, &slave->dev->state))
return false;
bond->send_peer_notif--;
return true;
}
/**
* change_active_interface - change the active slave into the specified one
* @bond: our bonding struct
* @new: the new slave to make the active one
*
* Set the new slave to the bond's settings and unset them on the old
* curr_active_slave.
* Setting include flags, mc-list, promiscuity, allmulti, etc.
*
* If @new's link state is %BOND_LINK_BACK we'll set it to %BOND_LINK_UP,
* because it is apparently the best available slave we have, even though its
* updelay hasn't timed out yet.
*
* If new_active is not NULL, caller must hold bond->lock for read and
* curr_slave_lock for write_bh.
*/
void bond_change_active_slave(struct bonding *bond, struct slave *new_active)
{
struct slave *old_active = bond->curr_active_slave;
if (old_active == new_active)
return;
if (new_active) {
new_active->jiffies = jiffies;
if (new_active->link == BOND_LINK_BACK) {
if (USES_PRIMARY(bond->params.mode)) {
pr_info("%s: making interface %s the new active one %d ms earlier.\n",
bond->dev->name, new_active->dev->name,
(bond->params.updelay - new_active->delay) * bond->params.miimon);
}
new_active->delay = 0;
new_active->link = BOND_LINK_UP;
if (bond->params.mode == BOND_MODE_8023AD)
bond_3ad_handle_link_change(new_active, BOND_LINK_UP);
if (bond_is_lb(bond))
bond_alb_handle_link_change(bond, new_active, BOND_LINK_UP);
} else {
if (USES_PRIMARY(bond->params.mode)) {
pr_info("%s: making interface %s the new active one.\n",
bond->dev->name, new_active->dev->name);
}
}
}
if (USES_PRIMARY(bond->params.mode))
bond_mc_swap(bond, new_active, old_active);
if (bond_is_lb(bond)) {
bond_alb_handle_active_change(bond, new_active);
if (old_active)
bond_set_slave_inactive_flags(old_active);
if (new_active)
bond_set_slave_active_flags(new_active);
} else {
bond->curr_active_slave = new_active;
}
if (bond->params.mode == BOND_MODE_ACTIVEBACKUP) {
if (old_active)
bond_set_slave_inactive_flags(old_active);
if (new_active) {
bool should_notify_peers = false;
bond_set_slave_active_flags(new_active);
if (bond->params.fail_over_mac)
bond_do_fail_over_mac(bond, new_active,
old_active);
if (netif_running(bond->dev)) {
bond->send_peer_notif =
bond->params.num_peer_notif;
should_notify_peers =
bond_should_notify_peers(bond);
}
write_unlock_bh(&bond->curr_slave_lock);
read_unlock(&bond->lock);
netdev_bonding_change(bond->dev, NETDEV_BONDING_FAILOVER);
if (should_notify_peers)
netdev_bonding_change(bond->dev,
NETDEV_NOTIFY_PEERS);
read_lock(&bond->lock);
write_lock_bh(&bond->curr_slave_lock);
}
}
/* resend IGMP joins since active slave has changed or
* all were sent on curr_active_slave.
* resend only if bond is brought up with the affected
* bonding modes and the retransmission is enabled */
if (netif_running(bond->dev) && (bond->params.resend_igmp > 0) &&
((USES_PRIMARY(bond->params.mode) && new_active) ||
bond->params.mode == BOND_MODE_ROUNDROBIN)) {
bond->igmp_retrans = bond->params.resend_igmp;
queue_delayed_work(bond->wq, &bond->mcast_work, 0);
}
}
/**
* bond_select_active_slave - select a new active slave, if needed
* @bond: our bonding struct
*
* This functions should be called when one of the following occurs:
* - The old curr_active_slave has been released or lost its link.
* - The primary_slave has got its link back.
* - A slave has got its link back and there's no old curr_active_slave.
*
* Caller must hold bond->lock for read and curr_slave_lock for write_bh.
*/
void bond_select_active_slave(struct bonding *bond)
{
struct slave *best_slave;
int rv;
best_slave = bond_find_best_slave(bond);
if (best_slave != bond->curr_active_slave) {
bond_change_active_slave(bond, best_slave);
rv = bond_set_carrier(bond);
if (!rv)
return;
if (netif_carrier_ok(bond->dev)) {
pr_info("%s: first active interface up!\n",
bond->dev->name);
} else {
pr_info("%s: now running without any active interface !\n",
bond->dev->name);
}
}
}
/*--------------------------- slave list handling ---------------------------*/
/*
* This function attaches the slave to the end of list.
*
* bond->lock held for writing by caller.
*/
static void bond_attach_slave(struct bonding *bond, struct slave *new_slave)
{
if (bond->first_slave == NULL) { /* attaching the first slave */
new_slave->next = new_slave;
new_slave->prev = new_slave;
bond->first_slave = new_slave;
} else {
new_slave->next = bond->first_slave;
new_slave->prev = bond->first_slave->prev;
new_slave->next->prev = new_slave;
new_slave->prev->next = new_slave;
}
bond->slave_cnt++;
}
/*
* This function detaches the slave from the list.
* WARNING: no check is made to verify if the slave effectively
* belongs to <bond>.
* Nothing is freed on return, structures are just unchained.
* If any slave pointer in bond was pointing to <slave>,
* it should be changed by the calling function.
*
* bond->lock held for writing by caller.
*/
static void bond_detach_slave(struct bonding *bond, struct slave *slave)
{
if (slave->next)
slave->next->prev = slave->prev;
if (slave->prev)
slave->prev->next = slave->next;
if (bond->first_slave == slave) { /* slave is the first slave */
if (bond->slave_cnt > 1) { /* there are more slave */
bond->first_slave = slave->next;
} else {
bond->first_slave = NULL; /* slave was the last one */
}
}
slave->next = NULL;
slave->prev = NULL;
bond->slave_cnt--;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static inline int slave_enable_netpoll(struct slave *slave)
{
struct netpoll *np;
int err = 0;
np = kzalloc(sizeof(*np), GFP_KERNEL);
err = -ENOMEM;
if (!np)
goto out;
np->dev = slave->dev;
strlcpy(np->dev_name, slave->dev->name, IFNAMSIZ);
err = __netpoll_setup(np);
if (err) {
kfree(np);
goto out;
}
slave->np = np;
out:
return err;
}
static inline void slave_disable_netpoll(struct slave *slave)
{
struct netpoll *np = slave->np;
if (!np)
return;
slave->np = NULL;
synchronize_rcu_bh();
__netpoll_cleanup(np);
kfree(np);
}
static inline bool slave_dev_support_netpoll(struct net_device *slave_dev)
{
if (slave_dev->priv_flags & IFF_DISABLE_NETPOLL)
return false;
if (!slave_dev->netdev_ops->ndo_poll_controller)
return false;
return true;
}
static void bond_poll_controller(struct net_device *bond_dev)
{
}
static void __bond_netpoll_cleanup(struct bonding *bond)
{
struct slave *slave;
int i;
bond_for_each_slave(bond, slave, i)
if (IS_UP(slave->dev))
slave_disable_netpoll(slave);
}
static void bond_netpoll_cleanup(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
read_lock(&bond->lock);
__bond_netpoll_cleanup(bond);
read_unlock(&bond->lock);
}
static int bond_netpoll_setup(struct net_device *dev, struct netpoll_info *ni)
{
struct bonding *bond = netdev_priv(dev);
struct slave *slave;
int i, err = 0;
read_lock(&bond->lock);
bond_for_each_slave(bond, slave, i) {
err = slave_enable_netpoll(slave);
if (err) {
__bond_netpoll_cleanup(bond);
break;
}
}
read_unlock(&bond->lock);
return err;
}
static struct netpoll_info *bond_netpoll_info(struct bonding *bond)
{
return bond->dev->npinfo;
}
#else
static inline int slave_enable_netpoll(struct slave *slave)
{
return 0;
}
static inline void slave_disable_netpoll(struct slave *slave)
{
}
static void bond_netpoll_cleanup(struct net_device *bond_dev)
{
}
#endif
/*---------------------------------- IOCTL ----------------------------------*/
static int bond_sethwaddr(struct net_device *bond_dev,
struct net_device *slave_dev)
{
pr_debug("bond_dev=%p\n", bond_dev);
pr_debug("slave_dev=%p\n", slave_dev);
pr_debug("slave_dev->addr_len=%d\n", slave_dev->addr_len);
memcpy(bond_dev->dev_addr, slave_dev->dev_addr, slave_dev->addr_len);
return 0;
}
static netdev_features_t bond_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct slave *slave;
struct bonding *bond = netdev_priv(dev);
netdev_features_t mask;
int i;
read_lock(&bond->lock);
if (!bond->first_slave) {
/* Disable adding VLANs to empty bond. But why? --mq */
features |= NETIF_F_VLAN_CHALLENGED;
goto out;
}
mask = features;
features &= ~NETIF_F_ONE_FOR_ALL;
features |= NETIF_F_ALL_FOR_ALL;
bond_for_each_slave(bond, slave, i) {
features = netdev_increment_features(features,
slave->dev->features,
mask);
}
out:
read_unlock(&bond->lock);
return features;
}
#define BOND_VLAN_FEATURES (NETIF_F_ALL_CSUM | NETIF_F_SG | \
NETIF_F_FRAGLIST | NETIF_F_ALL_TSO | \
NETIF_F_HIGHDMA | NETIF_F_LRO)
static void bond_compute_features(struct bonding *bond)
{
struct slave *slave;
struct net_device *bond_dev = bond->dev;
netdev_features_t vlan_features = BOND_VLAN_FEATURES;
unsigned short max_hard_header_len = ETH_HLEN;
int i;
read_lock(&bond->lock);
if (!bond->first_slave)
goto done;
bond_for_each_slave(bond, slave, i) {
vlan_features = netdev_increment_features(vlan_features,
slave->dev->vlan_features, BOND_VLAN_FEATURES);
if (slave->dev->hard_header_len > max_hard_header_len)
max_hard_header_len = slave->dev->hard_header_len;
}
done:
bond_dev->vlan_features = vlan_features;
bond_dev->hard_header_len = max_hard_header_len;
read_unlock(&bond->lock);
netdev_change_features(bond_dev);
}
static void bond_setup_by_slave(struct net_device *bond_dev,
struct net_device *slave_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
bond_dev->header_ops = slave_dev->header_ops;
bond_dev->type = slave_dev->type;
bond_dev->hard_header_len = slave_dev->hard_header_len;
bond_dev->addr_len = slave_dev->addr_len;
memcpy(bond_dev->broadcast, slave_dev->broadcast,
slave_dev->addr_len);
bond->setup_by_slave = 1;
}
/* On bonding slaves other than the currently active slave, suppress
* duplicates except for alb non-mcast/bcast.
*/
static bool bond_should_deliver_exact_match(struct sk_buff *skb,
struct slave *slave,
struct bonding *bond)
{
if (bond_is_slave_inactive(slave)) {
if (bond->params.mode == BOND_MODE_ALB &&
skb->pkt_type != PACKET_BROADCAST &&
skb->pkt_type != PACKET_MULTICAST)
return false;
return true;
}
return false;
}
static rx_handler_result_t bond_handle_frame(struct sk_buff **pskb)
{
struct sk_buff *skb = *pskb;
struct slave *slave;
struct bonding *bond;
int (*recv_probe)(struct sk_buff *, struct bonding *,
struct slave *);
int ret = RX_HANDLER_ANOTHER;
skb = skb_share_check(skb, GFP_ATOMIC);
if (unlikely(!skb))
return RX_HANDLER_CONSUMED;
*pskb = skb;
slave = bond_slave_get_rcu(skb->dev);
bond = slave->bond;
if (bond->params.arp_interval)
slave->dev->last_rx = jiffies;
recv_probe = ACCESS_ONCE(bond->recv_probe);
if (recv_probe) {
struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
if (likely(nskb)) {
ret = recv_probe(nskb, bond, slave);
dev_kfree_skb(nskb);
if (ret == RX_HANDLER_CONSUMED) {
consume_skb(skb);
return ret;
}
}
}
if (bond_should_deliver_exact_match(skb, slave, bond)) {
return RX_HANDLER_EXACT;
}
skb->dev = bond->dev;
if (bond->params.mode == BOND_MODE_ALB &&
bond->dev->priv_flags & IFF_BRIDGE_PORT &&
skb->pkt_type == PACKET_HOST) {
if (unlikely(skb_cow_head(skb,
skb->data - skb_mac_header(skb)))) {
kfree_skb(skb);
return RX_HANDLER_CONSUMED;
}
memcpy(eth_hdr(skb)->h_dest, bond->dev->dev_addr, ETH_ALEN);
}
return ret;
}
/* enslave device <slave> to bond device <master> */
int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
const struct net_device_ops *slave_ops = slave_dev->netdev_ops;
struct slave *new_slave = NULL;
struct netdev_hw_addr *ha;
struct sockaddr addr;
int link_reporting;
int res = 0;
if (!bond->params.use_carrier && slave_dev->ethtool_ops == NULL &&
slave_ops->ndo_do_ioctl == NULL) {
pr_warning("%s: Warning: no link monitoring support for %s\n",
bond_dev->name, slave_dev->name);
}
/* already enslaved */
if (slave_dev->flags & IFF_SLAVE) {
pr_debug("Error, Device was already enslaved\n");
return -EBUSY;
}
/* vlan challenged mutual exclusion */
/* no need to lock since we're protected by rtnl_lock */
if (slave_dev->features & NETIF_F_VLAN_CHALLENGED) {
pr_debug("%s: NETIF_F_VLAN_CHALLENGED\n", slave_dev->name);
if (bond_vlan_used(bond)) {
pr_err("%s: Error: cannot enslave VLAN challenged slave %s on VLAN enabled bond %s\n",
bond_dev->name, slave_dev->name, bond_dev->name);
return -EPERM;
} else {
pr_warning("%s: Warning: enslaved VLAN challenged slave %s. Adding VLANs will be blocked as long as %s is part of bond %s\n",
bond_dev->name, slave_dev->name,
slave_dev->name, bond_dev->name);
}
} else {
pr_debug("%s: ! NETIF_F_VLAN_CHALLENGED\n", slave_dev->name);
}
/*
* Old ifenslave binaries are no longer supported. These can
* be identified with moderate accuracy by the state of the slave:
* the current ifenslave will set the interface down prior to
* enslaving it; the old ifenslave will not.
*/
if ((slave_dev->flags & IFF_UP)) {
pr_err("%s is up. This may be due to an out of date ifenslave.\n",
slave_dev->name);
res = -EPERM;
goto err_undo_flags;
}
/* set bonding device ether type by slave - bonding netdevices are
* created with ether_setup, so when the slave type is not ARPHRD_ETHER
* there is a need to override some of the type dependent attribs/funcs.
*
* bond ether type mutual exclusion - don't allow slaves of dissimilar
* ether type (eg ARPHRD_ETHER and ARPHRD_INFINIBAND) share the same bond
*/
if (bond->slave_cnt == 0) {
if (bond_dev->type != slave_dev->type) {
pr_debug("%s: change device type from %d to %d\n",
bond_dev->name,
bond_dev->type, slave_dev->type);
res = netdev_bonding_change(bond_dev,
NETDEV_PRE_TYPE_CHANGE);
res = notifier_to_errno(res);
if (res) {
pr_err("%s: refused to change device type\n",
bond_dev->name);
res = -EBUSY;
goto err_undo_flags;
}
/* Flush unicast and multicast addresses */
dev_uc_flush(bond_dev);
dev_mc_flush(bond_dev);
if (slave_dev->type != ARPHRD_ETHER)
bond_setup_by_slave(bond_dev, slave_dev);
else {
ether_setup(bond_dev);
bond_dev->priv_flags &= ~IFF_TX_SKB_SHARING;
}
netdev_bonding_change(bond_dev,
NETDEV_POST_TYPE_CHANGE);
}
} else if (bond_dev->type != slave_dev->type) {
pr_err("%s ether type (%d) is different from other slaves (%d), can not enslave it.\n",
slave_dev->name,
slave_dev->type, bond_dev->type);
res = -EINVAL;
goto err_undo_flags;
}
if (slave_ops->ndo_set_mac_address == NULL) {
if (bond->slave_cnt == 0) {
pr_warning("%s: Warning: The first slave device specified does not support setting the MAC address. Setting fail_over_mac to active.",
bond_dev->name);
bond->params.fail_over_mac = BOND_FOM_ACTIVE;
} else if (bond->params.fail_over_mac != BOND_FOM_ACTIVE) {
pr_err("%s: Error: The slave device specified does not support setting the MAC address, but fail_over_mac is not set to active.\n",
bond_dev->name);
res = -EOPNOTSUPP;
goto err_undo_flags;
}
}
call_netdevice_notifiers(NETDEV_JOIN, slave_dev);
/* If this is the first slave, then we need to set the master's hardware
* address to be the same as the slave's. */
if (is_zero_ether_addr(bond->dev->dev_addr))
memcpy(bond->dev->dev_addr, slave_dev->dev_addr,
slave_dev->addr_len);
new_slave = kzalloc(sizeof(struct slave), GFP_KERNEL);
if (!new_slave) {
res = -ENOMEM;
goto err_undo_flags;
}
/*
* Set the new_slave's queue_id to be zero. Queue ID mapping
* is set via sysfs or module option if desired.
*/
new_slave->queue_id = 0;
/* Save slave's original mtu and then set it to match the bond */
new_slave->original_mtu = slave_dev->mtu;
res = dev_set_mtu(slave_dev, bond->dev->mtu);
if (res) {
pr_debug("Error %d calling dev_set_mtu\n", res);
goto err_free;
}
/*
* Save slave's original ("permanent") mac address for modes
* that need it, and for restoring it upon release, and then
* set it to the master's address
*/
memcpy(new_slave->perm_hwaddr, slave_dev->dev_addr, ETH_ALEN);
if (!bond->params.fail_over_mac) {
/*
* Set slave to master's mac address. The application already
* set the master's mac address to that of the first slave
*/
memcpy(addr.sa_data, bond_dev->dev_addr, bond_dev->addr_len);
addr.sa_family = slave_dev->type;
res = dev_set_mac_address(slave_dev, &addr);
if (res) {
pr_debug("Error %d calling set_mac_address\n", res);
goto err_restore_mtu;
}
}
res = netdev_set_bond_master(slave_dev, bond_dev);
if (res) {
pr_debug("Error %d calling netdev_set_bond_master\n", res);
goto err_restore_mac;
}
/* open the slave since the application closed it */
res = dev_open(slave_dev);
if (res) {
pr_debug("Opening slave %s failed\n", slave_dev->name);
goto err_unset_master;
}
new_slave->bond = bond;
new_slave->dev = slave_dev;
slave_dev->priv_flags |= IFF_BONDING;
if (bond_is_lb(bond)) {
/* bond_alb_init_slave() must be called before all other stages since
* it might fail and we do not want to have to undo everything
*/
res = bond_alb_init_slave(bond, new_slave);
if (res)
goto err_close;
}
/* If the mode USES_PRIMARY, then the new slave gets the
* master's promisc (and mc) settings only if it becomes the
* curr_active_slave, and that is taken care of later when calling
* bond_change_active()
*/
if (!USES_PRIMARY(bond->params.mode)) {
/* set promiscuity level to new slave */
if (bond_dev->flags & IFF_PROMISC) {
res = dev_set_promiscuity(slave_dev, 1);
if (res)
goto err_close;
}
/* set allmulti level to new slave */
if (bond_dev->flags & IFF_ALLMULTI) {
res = dev_set_allmulti(slave_dev, 1);
if (res)
goto err_close;
}
netif_addr_lock_bh(bond_dev);
/* upload master's mc_list to new slave */
netdev_for_each_mc_addr(ha, bond_dev)
dev_mc_add(slave_dev, ha->addr);
netif_addr_unlock_bh(bond_dev);
}
if (bond->params.mode == BOND_MODE_8023AD) {
/* add lacpdu mc addr to mc list */
u8 lacpdu_multicast[ETH_ALEN] = MULTICAST_LACPDU_ADDR;
dev_mc_add(slave_dev, lacpdu_multicast);
}
bond_add_vlans_on_slave(bond, slave_dev);
write_lock_bh(&bond->lock);
bond_attach_slave(bond, new_slave);
new_slave->delay = 0;
new_slave->link_failure_count = 0;
write_unlock_bh(&bond->lock);
bond_compute_features(bond);
read_lock(&bond->lock);
new_slave->last_arp_rx = jiffies;
if (bond->params.miimon && !bond->params.use_carrier) {
link_reporting = bond_check_dev_link(bond, slave_dev, 1);
if ((link_reporting == -1) && !bond->params.arp_interval) {
/*
* miimon is set but a bonded network driver
* does not support ETHTOOL/MII and
* arp_interval is not set. Note: if
* use_carrier is enabled, we will never go
* here (because netif_carrier is always
* supported); thus, we don't need to change
* the messages for netif_carrier.
*/
pr_warning("%s: Warning: MII and ETHTOOL support not available for interface %s, and arp_interval/arp_ip_target module parameters not specified, thus bonding will not detect link failures! see bonding.txt for details.\n",
bond_dev->name, slave_dev->name);
} else if (link_reporting == -1) {
/* unable get link status using mii/ethtool */
pr_warning("%s: Warning: can't get link status from interface %s; the network driver associated with this interface does not support MII or ETHTOOL link status reporting, thus miimon has no effect on this interface.\n",
bond_dev->name, slave_dev->name);
}
}
/* check for initial state */
if (!bond->params.miimon ||
(bond_check_dev_link(bond, slave_dev, 0) == BMSR_LSTATUS)) {
if (bond->params.updelay) {
pr_debug("Initial state of slave_dev is BOND_LINK_BACK\n");
new_slave->link = BOND_LINK_BACK;
new_slave->delay = bond->params.updelay;
} else {
pr_debug("Initial state of slave_dev is BOND_LINK_UP\n");
new_slave->link = BOND_LINK_UP;
}
new_slave->jiffies = jiffies;
} else {
pr_debug("Initial state of slave_dev is BOND_LINK_DOWN\n");
new_slave->link = BOND_LINK_DOWN;
}
bond_update_speed_duplex(new_slave);
if (USES_PRIMARY(bond->params.mode) && bond->params.primary[0]) {
/* if there is a primary slave, remember it */
if (strcmp(bond->params.primary, new_slave->dev->name) == 0) {
bond->primary_slave = new_slave;
bond->force_primary = true;
}
}
write_lock_bh(&bond->curr_slave_lock);
switch (bond->params.mode) {
case BOND_MODE_ACTIVEBACKUP:
bond_set_slave_inactive_flags(new_slave);
bond_select_active_slave(bond);
break;
case BOND_MODE_8023AD:
/* in 802.3ad mode, the internal mechanism
* will activate the slaves in the selected
* aggregator
*/
bond_set_slave_inactive_flags(new_slave);
/* if this is the first slave */
if (bond->slave_cnt == 1) {
SLAVE_AD_INFO(new_slave).id = 1;
/* Initialize AD with the number of times that the AD timer is called in 1 second
* can be called only after the mac address of the bond is set
*/
bond_3ad_initialize(bond, 1000/AD_TIMER_INTERVAL);
} else {
SLAVE_AD_INFO(new_slave).id =
SLAVE_AD_INFO(new_slave->prev).id + 1;
}
bond_3ad_bind_slave(new_slave);
break;
case BOND_MODE_TLB:
case BOND_MODE_ALB:
bond_set_active_slave(new_slave);
bond_set_slave_inactive_flags(new_slave);
bond_select_active_slave(bond);
break;
default:
pr_debug("This slave is always active in trunk mode\n");
/* always active in trunk mode */
bond_set_active_slave(new_slave);
/* In trunking mode there is little meaning to curr_active_slave
* anyway (it holds no special properties of the bond device),
* so we can change it without calling change_active_interface()
*/
if (!bond->curr_active_slave)
bond->curr_active_slave = new_slave;
break;
} /* switch(bond_mode) */
write_unlock_bh(&bond->curr_slave_lock);
bond_set_carrier(bond);
#ifdef CONFIG_NET_POLL_CONTROLLER
slave_dev->npinfo = bond_netpoll_info(bond);
if (slave_dev->npinfo) {
if (slave_enable_netpoll(new_slave)) {
read_unlock(&bond->lock);
pr_info("Error, %s: master_dev is using netpoll, "
"but new slave device does not support netpoll.\n",
bond_dev->name);
res = -EBUSY;
goto err_detach;
}
}
#endif
read_unlock(&bond->lock);
res = bond_create_slave_symlinks(bond_dev, slave_dev);
if (res)
goto err_detach;
res = netdev_rx_handler_register(slave_dev, bond_handle_frame,
new_slave);
if (res) {
pr_debug("Error %d calling netdev_rx_handler_register\n", res);
goto err_dest_symlinks;
}
pr_info("%s: enslaving %s as a%s interface with a%s link.\n",
bond_dev->name, slave_dev->name,
bond_is_active_slave(new_slave) ? "n active" : " backup",
new_slave->link != BOND_LINK_DOWN ? "n up" : " down");
/* enslave is successful */
return 0;
/* Undo stages on error */
err_dest_symlinks:
bond_destroy_slave_symlinks(bond_dev, slave_dev);
err_detach:
write_lock_bh(&bond->lock);
bond_detach_slave(bond, new_slave);
write_unlock_bh(&bond->lock);
err_close:
dev_close(slave_dev);
err_unset_master:
netdev_set_bond_master(slave_dev, NULL);
err_restore_mac:
if (!bond->params.fail_over_mac) {
/* XXX TODO - fom follow mode needs to change master's
* MAC if this slave's MAC is in use by the bond, or at
* least print a warning.
*/
memcpy(addr.sa_data, new_slave->perm_hwaddr, ETH_ALEN);
addr.sa_family = slave_dev->type;
dev_set_mac_address(slave_dev, &addr);
}
err_restore_mtu:
dev_set_mtu(slave_dev, new_slave->original_mtu);
err_free:
kfree(new_slave);
err_undo_flags:
bond_compute_features(bond);
return res;
}
/*
* Try to release the slave device <slave> from the bond device <master>
* It is legal to access curr_active_slave without a lock because all the function
* is write-locked.
*
* The rules for slave state should be:
* for Active/Backup:
* Active stays on all backups go down
* for Bonded connections:
* The first up interface should be left on and all others downed.
*/
int bond_release(struct net_device *bond_dev, struct net_device *slave_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave, *oldcurrent;
struct sockaddr addr;
netdev_features_t old_features = bond_dev->features;
/* slave is not a slave or master is not master of this slave */
if (!(slave_dev->flags & IFF_SLAVE) ||
(slave_dev->master != bond_dev)) {
pr_err("%s: Error: cannot release %s.\n",
bond_dev->name, slave_dev->name);
return -EINVAL;
}
block_netpoll_tx();
netdev_bonding_change(bond_dev, NETDEV_RELEASE);
write_lock_bh(&bond->lock);
slave = bond_get_slave_by_dev(bond, slave_dev);
if (!slave) {
/* not a slave of this bond */
pr_info("%s: %s not enslaved\n",
bond_dev->name, slave_dev->name);
write_unlock_bh(&bond->lock);
unblock_netpoll_tx();
return -EINVAL;
}
/* unregister rx_handler early so bond_handle_frame wouldn't be called
* for this slave anymore.
*/
netdev_rx_handler_unregister(slave_dev);
write_unlock_bh(&bond->lock);
synchronize_net();
write_lock_bh(&bond->lock);
if (!bond->params.fail_over_mac) {
if (!compare_ether_addr(bond_dev->dev_addr, slave->perm_hwaddr) &&
bond->slave_cnt > 1)
pr_warning("%s: Warning: the permanent HWaddr of %s - %pM - is still in use by %s. Set the HWaddr of %s to a different address to avoid conflicts.\n",
bond_dev->name, slave_dev->name,
slave->perm_hwaddr,
bond_dev->name, slave_dev->name);
}
/* Inform AD package of unbinding of slave. */
if (bond->params.mode == BOND_MODE_8023AD) {
/* must be called before the slave is
* detached from the list
*/
bond_3ad_unbind_slave(slave);
}
pr_info("%s: releasing %s interface %s\n",
bond_dev->name,
bond_is_active_slave(slave) ? "active" : "backup",
slave_dev->name);
oldcurrent = bond->curr_active_slave;
bond->current_arp_slave = NULL;
/* release the slave from its bond */
bond_detach_slave(bond, slave);
if (bond->primary_slave == slave)
bond->primary_slave = NULL;
if (oldcurrent == slave)
bond_change_active_slave(bond, NULL);
if (bond_is_lb(bond)) {
/* Must be called only after the slave has been
* detached from the list and the curr_active_slave
* has been cleared (if our_slave == old_current),
* but before a new active slave is selected.
*/
write_unlock_bh(&bond->lock);
bond_alb_deinit_slave(bond, slave);
write_lock_bh(&bond->lock);
}
if (oldcurrent == slave) {
/*
* Note that we hold RTNL over this sequence, so there
* is no concern that another slave add/remove event
* will interfere.
*/
write_unlock_bh(&bond->lock);
read_lock(&bond->lock);
write_lock_bh(&bond->curr_slave_lock);
bond_select_active_slave(bond);
write_unlock_bh(&bond->curr_slave_lock);
read_unlock(&bond->lock);
write_lock_bh(&bond->lock);
}
if (bond->slave_cnt == 0) {
bond_set_carrier(bond);
/* if the last slave was removed, zero the mac address
* of the master so it will be set by the application
* to the mac address of the first slave
*/
memset(bond_dev->dev_addr, 0, bond_dev->addr_len);
if (bond_vlan_used(bond)) {
pr_warning("%s: Warning: clearing HW address of %s while it still has VLANs.\n",
bond_dev->name, bond_dev->name);
pr_warning("%s: When re-adding slaves, make sure the bond's HW address matches its VLANs'.\n",
bond_dev->name);
}
}
write_unlock_bh(&bond->lock);
unblock_netpoll_tx();
if (bond->slave_cnt == 0)
call_netdevice_notifiers(NETDEV_CHANGEADDR, bond->dev);
bond_compute_features(bond);
if (!(bond_dev->features & NETIF_F_VLAN_CHALLENGED) &&
(old_features & NETIF_F_VLAN_CHALLENGED))
pr_info("%s: last VLAN challenged slave %s left bond %s. VLAN blocking is removed\n",
bond_dev->name, slave_dev->name, bond_dev->name);
/* must do this from outside any spinlocks */
bond_destroy_slave_symlinks(bond_dev, slave_dev);
bond_del_vlans_from_slave(bond, slave_dev);
/* If the mode USES_PRIMARY, then we should only remove its
* promisc and mc settings if it was the curr_active_slave, but that was
* already taken care of above when we detached the slave
*/
if (!USES_PRIMARY(bond->params.mode)) {
/* unset promiscuity level from slave */
if (bond_dev->flags & IFF_PROMISC)
dev_set_promiscuity(slave_dev, -1);
/* unset allmulti level from slave */
if (bond_dev->flags & IFF_ALLMULTI)
dev_set_allmulti(slave_dev, -1);
/* flush master's mc_list from slave */
netif_addr_lock_bh(bond_dev);
bond_mc_list_flush(bond_dev, slave_dev);
netif_addr_unlock_bh(bond_dev);
}
netdev_set_bond_master(slave_dev, NULL);
slave_disable_netpoll(slave);
/* close slave before restoring its mac address */
dev_close(slave_dev);
if (bond->params.fail_over_mac != BOND_FOM_ACTIVE) {
/* restore original ("permanent") mac address */
memcpy(addr.sa_data, slave->perm_hwaddr, ETH_ALEN);
addr.sa_family = slave_dev->type;
dev_set_mac_address(slave_dev, &addr);
}
dev_set_mtu(slave_dev, slave->original_mtu);
slave_dev->priv_flags &= ~IFF_BONDING;
kfree(slave);
return 0; /* deletion OK */
}
/*
* First release a slave and then destroy the bond if no more slaves are left.
* Must be under rtnl_lock when this function is called.
*/
static int bond_release_and_destroy(struct net_device *bond_dev,
struct net_device *slave_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
int ret;
ret = bond_release(bond_dev, slave_dev);
if ((ret == 0) && (bond->slave_cnt == 0)) {
bond_dev->priv_flags |= IFF_DISABLE_NETPOLL;
pr_info("%s: destroying bond %s.\n",
bond_dev->name, bond_dev->name);
unregister_netdevice(bond_dev);
}
return ret;
}
/*
* This function releases all slaves.
*/
static int bond_release_all(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave;
struct net_device *slave_dev;
struct sockaddr addr;
write_lock_bh(&bond->lock);
netif_carrier_off(bond_dev);
if (bond->slave_cnt == 0)
goto out;
bond->current_arp_slave = NULL;
bond->primary_slave = NULL;
bond_change_active_slave(bond, NULL);
while ((slave = bond->first_slave) != NULL) {
/* Inform AD package of unbinding of slave
* before slave is detached from the list.
*/
if (bond->params.mode == BOND_MODE_8023AD)
bond_3ad_unbind_slave(slave);
slave_dev = slave->dev;
bond_detach_slave(bond, slave);
/* now that the slave is detached, unlock and perform
* all the undo steps that should not be called from
* within a lock.
*/
write_unlock_bh(&bond->lock);
/* unregister rx_handler early so bond_handle_frame wouldn't
* be called for this slave anymore.
*/
netdev_rx_handler_unregister(slave_dev);
synchronize_net();
if (bond_is_lb(bond)) {
/* must be called only after the slave
* has been detached from the list
*/
bond_alb_deinit_slave(bond, slave);
}
bond_destroy_slave_symlinks(bond_dev, slave_dev);
bond_del_vlans_from_slave(bond, slave_dev);
/* If the mode USES_PRIMARY, then we should only remove its
* promisc and mc settings if it was the curr_active_slave, but that was
* already taken care of above when we detached the slave
*/
if (!USES_PRIMARY(bond->params.mode)) {
/* unset promiscuity level from slave */
if (bond_dev->flags & IFF_PROMISC)
dev_set_promiscuity(slave_dev, -1);
/* unset allmulti level from slave */
if (bond_dev->flags & IFF_ALLMULTI)
dev_set_allmulti(slave_dev, -1);
/* flush master's mc_list from slave */
netif_addr_lock_bh(bond_dev);
bond_mc_list_flush(bond_dev, slave_dev);
netif_addr_unlock_bh(bond_dev);
}
netdev_set_bond_master(slave_dev, NULL);
slave_disable_netpoll(slave);
/* close slave before restoring its mac address */
dev_close(slave_dev);
if (!bond->params.fail_over_mac) {
/* restore original ("permanent") mac address*/
memcpy(addr.sa_data, slave->perm_hwaddr, ETH_ALEN);
addr.sa_family = slave_dev->type;
dev_set_mac_address(slave_dev, &addr);
}
kfree(slave);
/* re-acquire the lock before getting the next slave */
write_lock_bh(&bond->lock);
}
/* zero the mac address of the master so it will be
* set by the application to the mac address of the
* first slave
*/
memset(bond_dev->dev_addr, 0, bond_dev->addr_len);
if (bond_vlan_used(bond)) {
pr_warning("%s: Warning: clearing HW address of %s while it still has VLANs.\n",
bond_dev->name, bond_dev->name);
pr_warning("%s: When re-adding slaves, make sure the bond's HW address matches its VLANs'.\n",
bond_dev->name);
}
pr_info("%s: released all slaves\n", bond_dev->name);
out:
write_unlock_bh(&bond->lock);
bond_compute_features(bond);
return 0;
}
/*
* This function changes the active slave to slave <slave_dev>.
* It returns -EINVAL in the following cases.
* - <slave_dev> is not found in the list.
* - There is not active slave now.
* - <slave_dev> is already active.
* - The link state of <slave_dev> is not BOND_LINK_UP.
* - <slave_dev> is not running.
* In these cases, this function does nothing.
* In the other cases, current_slave pointer is changed and 0 is returned.
*/
static int bond_ioctl_change_active(struct net_device *bond_dev, struct net_device *slave_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *old_active = NULL;
struct slave *new_active = NULL;
int res = 0;
if (!USES_PRIMARY(bond->params.mode))
return -EINVAL;
/* Verify that master_dev is indeed the master of slave_dev */
if (!(slave_dev->flags & IFF_SLAVE) || (slave_dev->master != bond_dev))
return -EINVAL;
read_lock(&bond->lock);
read_lock(&bond->curr_slave_lock);
old_active = bond->curr_active_slave;
read_unlock(&bond->curr_slave_lock);
new_active = bond_get_slave_by_dev(bond, slave_dev);
/*
* Changing to the current active: do nothing; return success.
*/
if (new_active && (new_active == old_active)) {
read_unlock(&bond->lock);
return 0;
}
if ((new_active) &&
(old_active) &&
(new_active->link == BOND_LINK_UP) &&
IS_UP(new_active->dev)) {
block_netpoll_tx();
write_lock_bh(&bond->curr_slave_lock);
bond_change_active_slave(bond, new_active);
write_unlock_bh(&bond->curr_slave_lock);
unblock_netpoll_tx();
} else
res = -EINVAL;
read_unlock(&bond->lock);
return res;
}
static int bond_info_query(struct net_device *bond_dev, struct ifbond *info)
{
struct bonding *bond = netdev_priv(bond_dev);
info->bond_mode = bond->params.mode;
info->miimon = bond->params.miimon;
read_lock(&bond->lock);
info->num_slaves = bond->slave_cnt;
read_unlock(&bond->lock);
return 0;
}
static int bond_slave_info_query(struct net_device *bond_dev, struct ifslave *info)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave;
int i, res = -ENODEV;
read_lock(&bond->lock);
bond_for_each_slave(bond, slave, i) {
if (i == (int)info->slave_id) {
res = 0;
strcpy(info->slave_name, slave->dev->name);
info->link = slave->link;
info->state = bond_slave_state(slave);
info->link_failure_count = slave->link_failure_count;
break;
}
}
read_unlock(&bond->lock);
return res;
}
/*-------------------------------- Monitoring -------------------------------*/
static int bond_miimon_inspect(struct bonding *bond)
{
struct slave *slave;
int i, link_state, commit = 0;
bool ignore_updelay;
ignore_updelay = !bond->curr_active_slave ? true : false;
bond_for_each_slave(bond, slave, i) {
slave->new_link = BOND_LINK_NOCHANGE;
link_state = bond_check_dev_link(bond, slave->dev, 0);
switch (slave->link) {
case BOND_LINK_UP:
if (link_state)
continue;
slave->link = BOND_LINK_FAIL;
slave->delay = bond->params.downdelay;
if (slave->delay) {
pr_info("%s: link status down for %sinterface %s, disabling it in %d ms.\n",
bond->dev->name,
(bond->params.mode ==
BOND_MODE_ACTIVEBACKUP) ?
(bond_is_active_slave(slave) ?
"active " : "backup ") : "",
slave->dev->name,
bond->params.downdelay * bond->params.miimon);
}
/*FALLTHRU*/
case BOND_LINK_FAIL:
if (link_state) {
/*
* recovered before downdelay expired
*/
slave->link = BOND_LINK_UP;
slave->jiffies = jiffies;
pr_info("%s: link status up again after %d ms for interface %s.\n",
bond->dev->name,
(bond->params.downdelay - slave->delay) *
bond->params.miimon,
slave->dev->name);
continue;
}
if (slave->delay <= 0) {
slave->new_link = BOND_LINK_DOWN;
commit++;
continue;
}
slave->delay--;
break;
case BOND_LINK_DOWN:
if (!link_state)
continue;
slave->link = BOND_LINK_BACK;
slave->delay = bond->params.updelay;
if (slave->delay) {
pr_info("%s: link status up for interface %s, enabling it in %d ms.\n",
bond->dev->name, slave->dev->name,
ignore_updelay ? 0 :
bond->params.updelay *
bond->params.miimon);
}
/*FALLTHRU*/
case BOND_LINK_BACK:
if (!link_state) {
slave->link = BOND_LINK_DOWN;
pr_info("%s: link status down again after %d ms for interface %s.\n",
bond->dev->name,
(bond->params.updelay - slave->delay) *
bond->params.miimon,
slave->dev->name);
continue;
}
if (ignore_updelay)
slave->delay = 0;
if (slave->delay <= 0) {
slave->new_link = BOND_LINK_UP;
commit++;
ignore_updelay = false;
continue;
}
slave->delay--;
break;
}
}
return commit;
}
static void bond_miimon_commit(struct bonding *bond)
{
struct slave *slave;
int i;
bond_for_each_slave(bond, slave, i) {
switch (slave->new_link) {
case BOND_LINK_NOCHANGE:
continue;
case BOND_LINK_UP:
slave->link = BOND_LINK_UP;
slave->jiffies = jiffies;
if (bond->params.mode == BOND_MODE_8023AD) {
/* prevent it from being the active one */
bond_set_backup_slave(slave);
} else if (bond->params.mode != BOND_MODE_ACTIVEBACKUP) {
/* make it immediately active */
bond_set_active_slave(slave);
} else if (slave != bond->primary_slave) {
/* prevent it from being the active one */
bond_set_backup_slave(slave);
}
bond_update_speed_duplex(slave);
pr_info("%s: link status definitely up for interface %s, %u Mbps %s duplex.\n",
bond->dev->name, slave->dev->name,
slave->speed, slave->duplex ? "full" : "half");
/* notify ad that the link status has changed */
if (bond->params.mode == BOND_MODE_8023AD)
bond_3ad_handle_link_change(slave, BOND_LINK_UP);
if (bond_is_lb(bond))
bond_alb_handle_link_change(bond, slave,
BOND_LINK_UP);
if (!bond->curr_active_slave ||
(slave == bond->primary_slave))
goto do_failover;
continue;
case BOND_LINK_DOWN:
if (slave->link_failure_count < UINT_MAX)
slave->link_failure_count++;
slave->link = BOND_LINK_DOWN;
if (bond->params.mode == BOND_MODE_ACTIVEBACKUP ||
bond->params.mode == BOND_MODE_8023AD)
bond_set_slave_inactive_flags(slave);
pr_info("%s: link status definitely down for interface %s, disabling it\n",
bond->dev->name, slave->dev->name);
if (bond->params.mode == BOND_MODE_8023AD)
bond_3ad_handle_link_change(slave,
BOND_LINK_DOWN);
if (bond_is_lb(bond))
bond_alb_handle_link_change(bond, slave,
BOND_LINK_DOWN);
if (slave == bond->curr_active_slave)
goto do_failover;
continue;
default:
pr_err("%s: invalid new link %d on slave %s\n",
bond->dev->name, slave->new_link,
slave->dev->name);
slave->new_link = BOND_LINK_NOCHANGE;
continue;
}
do_failover:
ASSERT_RTNL();
block_netpoll_tx();
write_lock_bh(&bond->curr_slave_lock);
bond_select_active_slave(bond);
write_unlock_bh(&bond->curr_slave_lock);
unblock_netpoll_tx();
}
bond_set_carrier(bond);
}
/*
* bond_mii_monitor
*
* Really a wrapper that splits the mii monitor into two phases: an
* inspection, then (if inspection indicates something needs to be done)
* an acquisition of appropriate locks followed by a commit phase to
* implement whatever link state changes are indicated.
*/
void bond_mii_monitor(struct work_struct *work)
{
struct bonding *bond = container_of(work, struct bonding,
mii_work.work);
bool should_notify_peers = false;
unsigned long delay;
read_lock(&bond->lock);
delay = msecs_to_jiffies(bond->params.miimon);
if (bond->slave_cnt == 0)
goto re_arm;
should_notify_peers = bond_should_notify_peers(bond);
if (bond_miimon_inspect(bond)) {
read_unlock(&bond->lock);
/* Race avoidance with bond_close cancel of workqueue */
if (!rtnl_trylock()) {
read_lock(&bond->lock);
delay = 1;
should_notify_peers = false;
goto re_arm;
}
read_lock(&bond->lock);
bond_miimon_commit(bond);
read_unlock(&bond->lock);
rtnl_unlock(); /* might sleep, hold no other locks */
read_lock(&bond->lock);
}
re_arm:
if (bond->params.miimon)
queue_delayed_work(bond->wq, &bond->mii_work, delay);
read_unlock(&bond->lock);
if (should_notify_peers) {
if (!rtnl_trylock()) {
read_lock(&bond->lock);
bond->send_peer_notif++;
read_unlock(&bond->lock);
return;
}
netdev_bonding_change(bond->dev, NETDEV_NOTIFY_PEERS);
rtnl_unlock();
}
}
static int bond_has_this_ip(struct bonding *bond, __be32 ip)
{
struct vlan_entry *vlan;
struct net_device *vlan_dev;
if (ip == bond_confirm_addr(bond->dev, 0, ip))
return 1;
list_for_each_entry(vlan, &bond->vlan_list, vlan_list) {
rcu_read_lock();
vlan_dev = __vlan_find_dev_deep(bond->dev, vlan->vlan_id);
rcu_read_unlock();
if (vlan_dev && ip == bond_confirm_addr(vlan_dev, 0, ip))
return 1;
}
return 0;
}
/*
* We go to the (large) trouble of VLAN tagging ARP frames because
* switches in VLAN mode (especially if ports are configured as
* "native" to a VLAN) might not pass non-tagged frames.
*/
static void bond_arp_send(struct net_device *slave_dev, int arp_op, __be32 dest_ip, __be32 src_ip, unsigned short vlan_id)
{
struct sk_buff *skb;
pr_debug("arp %d on slave %s: dst %x src %x vid %d\n", arp_op,
slave_dev->name, dest_ip, src_ip, vlan_id);
skb = arp_create(arp_op, ETH_P_ARP, dest_ip, slave_dev, src_ip,
NULL, slave_dev->dev_addr, NULL);
if (!skb) {
pr_err("ARP packet allocation failed\n");
return;
}
if (vlan_id) {
skb = vlan_put_tag(skb, vlan_id);
if (!skb) {
pr_err("failed to insert VLAN tag\n");
return;
}
}
arp_xmit(skb);
}
static void bond_arp_send_all(struct bonding *bond, struct slave *slave)
{
int i, vlan_id;
__be32 *targets = bond->params.arp_targets;
struct vlan_entry *vlan;
struct net_device *vlan_dev = NULL;
struct rtable *rt;
for (i = 0; (i < BOND_MAX_ARP_TARGETS); i++) {
__be32 addr;
if (!targets[i])
break;
pr_debug("basa: target %x\n", targets[i]);
if (!bond_vlan_used(bond)) {
pr_debug("basa: empty vlan: arp_send\n");
addr = bond_confirm_addr(bond->dev, targets[i], 0);
bond_arp_send(slave->dev, ARPOP_REQUEST, targets[i],
addr, 0);
continue;
}
/*
* If VLANs are configured, we do a route lookup to
* determine which VLAN interface would be used, so we
* can tag the ARP with the proper VLAN tag.
*/
rt = ip_route_output(dev_net(bond->dev), targets[i], 0,
RTO_ONLINK, 0);
if (IS_ERR(rt)) {
if (net_ratelimit()) {
pr_warning("%s: no route to arp_ip_target %pI4\n",
bond->dev->name, &targets[i]);
}
continue;
}
/*
* This target is not on a VLAN
*/
if (rt->dst.dev == bond->dev) {
ip_rt_put(rt);
pr_debug("basa: rtdev == bond->dev: arp_send\n");
addr = bond_confirm_addr(bond->dev, targets[i], 0);
bond_arp_send(slave->dev, ARPOP_REQUEST, targets[i],
addr, 0);
continue;
}
vlan_id = 0;
list_for_each_entry(vlan, &bond->vlan_list, vlan_list) {
rcu_read_lock();
vlan_dev = __vlan_find_dev_deep(bond->dev,
vlan->vlan_id);
rcu_read_unlock();
if (vlan_dev == rt->dst.dev) {
vlan_id = vlan->vlan_id;
pr_debug("basa: vlan match on %s %d\n",
vlan_dev->name, vlan_id);
break;
}
}
if (vlan_id && vlan_dev) {
ip_rt_put(rt);
addr = bond_confirm_addr(vlan_dev, targets[i], 0);
bond_arp_send(slave->dev, ARPOP_REQUEST, targets[i],
addr, vlan_id);
continue;
}
if (net_ratelimit()) {
pr_warning("%s: no path to arp_ip_target %pI4 via rt.dev %s\n",
bond->dev->name, &targets[i],
rt->dst.dev ? rt->dst.dev->name : "NULL");
}
ip_rt_put(rt);
}
}
static void bond_validate_arp(struct bonding *bond, struct slave *slave, __be32 sip, __be32 tip)
{
int i;
__be32 *targets = bond->params.arp_targets;
for (i = 0; (i < BOND_MAX_ARP_TARGETS) && targets[i]; i++) {
pr_debug("bva: sip %pI4 tip %pI4 t[%d] %pI4 bhti(tip) %d\n",
&sip, &tip, i, &targets[i],
bond_has_this_ip(bond, tip));
if (sip == targets[i]) {
if (bond_has_this_ip(bond, tip))
slave->last_arp_rx = jiffies;
return;
}
}
}
static int bond_arp_rcv(struct sk_buff *skb, struct bonding *bond,
struct slave *slave)
{
struct arphdr *arp;
unsigned char *arp_ptr;
__be32 sip, tip;
if (skb->protocol != __cpu_to_be16(ETH_P_ARP))
return RX_HANDLER_ANOTHER;
read_lock(&bond->lock);
pr_debug("bond_arp_rcv: bond %s skb->dev %s\n",
bond->dev->name, skb->dev->name);
if (!pskb_may_pull(skb, arp_hdr_len(bond->dev)))
goto out_unlock;
arp = arp_hdr(skb);
if (arp->ar_hln != bond->dev->addr_len ||
skb->pkt_type == PACKET_OTHERHOST ||
skb->pkt_type == PACKET_LOOPBACK ||
arp->ar_hrd != htons(ARPHRD_ETHER) ||
arp->ar_pro != htons(ETH_P_IP) ||
arp->ar_pln != 4)
goto out_unlock;
arp_ptr = (unsigned char *)(arp + 1);
arp_ptr += bond->dev->addr_len;
memcpy(&sip, arp_ptr, 4);
arp_ptr += 4 + bond->dev->addr_len;
memcpy(&tip, arp_ptr, 4);
pr_debug("bond_arp_rcv: %s %s/%d av %d sv %d sip %pI4 tip %pI4\n",
bond->dev->name, slave->dev->name, bond_slave_state(slave),
bond->params.arp_validate, slave_do_arp_validate(bond, slave),
&sip, &tip);
/*
* Backup slaves won't see the ARP reply, but do come through
* here for each ARP probe (so we swap the sip/tip to validate
* the probe). In a "redundant switch, common router" type of
* configuration, the ARP probe will (hopefully) travel from
* the active, through one switch, the router, then the other
* switch before reaching the backup.
*/
if (bond_is_active_slave(slave))
bond_validate_arp(bond, slave, sip, tip);
else
bond_validate_arp(bond, slave, tip, sip);
out_unlock:
read_unlock(&bond->lock);
return RX_HANDLER_ANOTHER;
}
/*
* this function is called regularly to monitor each slave's link
* ensuring that traffic is being sent and received when arp monitoring
* is used in load-balancing mode. if the adapter has been dormant, then an
* arp is transmitted to generate traffic. see activebackup_arp_monitor for
* arp monitoring in active backup mode.
*/
void bond_loadbalance_arp_mon(struct work_struct *work)
{
struct bonding *bond = container_of(work, struct bonding,
arp_work.work);
struct slave *slave, *oldcurrent;
int do_failover = 0;
int delta_in_ticks;
int i;
read_lock(&bond->lock);
delta_in_ticks = msecs_to_jiffies(bond->params.arp_interval);
if (bond->slave_cnt == 0)
goto re_arm;
read_lock(&bond->curr_slave_lock);
oldcurrent = bond->curr_active_slave;
read_unlock(&bond->curr_slave_lock);
/* see if any of the previous devices are up now (i.e. they have
* xmt and rcv traffic). the curr_active_slave does not come into
* the picture unless it is null. also, slave->jiffies is not needed
* here because we send an arp on each slave and give a slave as
* long as it needs to get the tx/rx within the delta.
* TODO: what about up/down delay in arp mode? it wasn't here before
* so it can wait
*/
bond_for_each_slave(bond, slave, i) {
unsigned long trans_start = dev_trans_start(slave->dev);
if (slave->link != BOND_LINK_UP) {
if (time_in_range(jiffies,
trans_start - delta_in_ticks,
trans_start + delta_in_ticks) &&
time_in_range(jiffies,
slave->dev->last_rx - delta_in_ticks,
slave->dev->last_rx + delta_in_ticks)) {
slave->link = BOND_LINK_UP;
bond_set_active_slave(slave);
/* primary_slave has no meaning in round-robin
* mode. the window of a slave being up and
* curr_active_slave being null after enslaving
* is closed.
*/
if (!oldcurrent) {
pr_info("%s: link status definitely up for interface %s, ",
bond->dev->name,
slave->dev->name);
do_failover = 1;
} else {
pr_info("%s: interface %s is now up\n",
bond->dev->name,
slave->dev->name);
}
}
} else {
/* slave->link == BOND_LINK_UP */
/* not all switches will respond to an arp request
* when the source ip is 0, so don't take the link down
* if we don't know our ip yet
*/
if (!time_in_range(jiffies,
trans_start - delta_in_ticks,
trans_start + 2 * delta_in_ticks) ||
!time_in_range(jiffies,
slave->dev->last_rx - delta_in_ticks,
slave->dev->last_rx + 2 * delta_in_ticks)) {
slave->link = BOND_LINK_DOWN;
bond_set_backup_slave(slave);
if (slave->link_failure_count < UINT_MAX)
slave->link_failure_count++;
pr_info("%s: interface %s is now down.\n",
bond->dev->name,
slave->dev->name);
if (slave == oldcurrent)
do_failover = 1;
}
}
/* note: if switch is in round-robin mode, all links
* must tx arp to ensure all links rx an arp - otherwise
* links may oscillate or not come up at all; if switch is
* in something like xor mode, there is nothing we can
* do - all replies will be rx'ed on same link causing slaves
* to be unstable during low/no traffic periods
*/
if (IS_UP(slave->dev))
bond_arp_send_all(bond, slave);
}
if (do_failover) {
block_netpoll_tx();
write_lock_bh(&bond->curr_slave_lock);
bond_select_active_slave(bond);
write_unlock_bh(&bond->curr_slave_lock);
unblock_netpoll_tx();
}
re_arm:
if (bond->params.arp_interval)
queue_delayed_work(bond->wq, &bond->arp_work, delta_in_ticks);
read_unlock(&bond->lock);
}
/*
* Called to inspect slaves for active-backup mode ARP monitor link state
* changes. Sets new_link in slaves to specify what action should take
* place for the slave. Returns 0 if no changes are found, >0 if changes
* to link states must be committed.
*
* Called with bond->lock held for read.
*/
static int bond_ab_arp_inspect(struct bonding *bond, int delta_in_ticks)
{
struct slave *slave;
int i, commit = 0;
unsigned long trans_start;
bond_for_each_slave(bond, slave, i) {
slave->new_link = BOND_LINK_NOCHANGE;
if (slave->link != BOND_LINK_UP) {
if (time_in_range(jiffies,
slave_last_rx(bond, slave) - delta_in_ticks,
slave_last_rx(bond, slave) + delta_in_ticks)) {
slave->new_link = BOND_LINK_UP;
commit++;
}
continue;
}
/*
* Give slaves 2*delta after being enslaved or made
* active. This avoids bouncing, as the last receive
* times need a full ARP monitor cycle to be updated.
*/
if (time_in_range(jiffies,
slave->jiffies - delta_in_ticks,
slave->jiffies + 2 * delta_in_ticks))
continue;
/*
* Backup slave is down if:
* - No current_arp_slave AND
* - more than 3*delta since last receive AND
* - the bond has an IP address
*
* Note: a non-null current_arp_slave indicates
* the curr_active_slave went down and we are
* searching for a new one; under this condition
* we only take the curr_active_slave down - this
* gives each slave a chance to tx/rx traffic
* before being taken out
*/
if (!bond_is_active_slave(slave) &&
!bond->current_arp_slave &&
!time_in_range(jiffies,
slave_last_rx(bond, slave) - delta_in_ticks,
slave_last_rx(bond, slave) + 3 * delta_in_ticks)) {
slave->new_link = BOND_LINK_DOWN;
commit++;
}
/*
* Active slave is down if:
* - more than 2*delta since transmitting OR
* - (more than 2*delta since receive AND
* the bond has an IP address)
*/
trans_start = dev_trans_start(slave->dev);
if (bond_is_active_slave(slave) &&
(!time_in_range(jiffies,
trans_start - delta_in_ticks,
trans_start + 2 * delta_in_ticks) ||
!time_in_range(jiffies,
slave_last_rx(bond, slave) - delta_in_ticks,
slave_last_rx(bond, slave) + 2 * delta_in_ticks))) {
slave->new_link = BOND_LINK_DOWN;
commit++;
}
}
return commit;
}
/*
* Called to commit link state changes noted by inspection step of
* active-backup mode ARP monitor.
*
* Called with RTNL and bond->lock for read.
*/
static void bond_ab_arp_commit(struct bonding *bond, int delta_in_ticks)
{
struct slave *slave;
int i;
unsigned long trans_start;
bond_for_each_slave(bond, slave, i) {
switch (slave->new_link) {
case BOND_LINK_NOCHANGE:
continue;
case BOND_LINK_UP:
trans_start = dev_trans_start(slave->dev);
if ((!bond->curr_active_slave &&
time_in_range(jiffies,
trans_start - delta_in_ticks,
trans_start + delta_in_ticks)) ||
bond->curr_active_slave != slave) {
slave->link = BOND_LINK_UP;
if (bond->current_arp_slave) {
bond_set_slave_inactive_flags(
bond->current_arp_slave);
bond->current_arp_slave = NULL;
}
pr_info("%s: link status definitely up for interface %s.\n",
bond->dev->name, slave->dev->name);
if (!bond->curr_active_slave ||
(slave == bond->primary_slave))
goto do_failover;
}
continue;
case BOND_LINK_DOWN:
if (slave->link_failure_count < UINT_MAX)
slave->link_failure_count++;
slave->link = BOND_LINK_DOWN;
bond_set_slave_inactive_flags(slave);
pr_info("%s: link status definitely down for interface %s, disabling it\n",
bond->dev->name, slave->dev->name);
if (slave == bond->curr_active_slave) {
bond->current_arp_slave = NULL;
goto do_failover;
}
continue;
default:
pr_err("%s: impossible: new_link %d on slave %s\n",
bond->dev->name, slave->new_link,
slave->dev->name);
continue;
}
do_failover:
ASSERT_RTNL();
block_netpoll_tx();
write_lock_bh(&bond->curr_slave_lock);
bond_select_active_slave(bond);
write_unlock_bh(&bond->curr_slave_lock);
unblock_netpoll_tx();
}
bond_set_carrier(bond);
}
/*
* Send ARP probes for active-backup mode ARP monitor.
*
* Called with bond->lock held for read.
*/
static void bond_ab_arp_probe(struct bonding *bond)
{
struct slave *slave;
int i;
read_lock(&bond->curr_slave_lock);
if (bond->current_arp_slave && bond->curr_active_slave)
pr_info("PROBE: c_arp %s && cas %s BAD\n",
bond->current_arp_slave->dev->name,
bond->curr_active_slave->dev->name);
if (bond->curr_active_slave) {
bond_arp_send_all(bond, bond->curr_active_slave);
read_unlock(&bond->curr_slave_lock);
return;
}
read_unlock(&bond->curr_slave_lock);
/* if we don't have a curr_active_slave, search for the next available
* backup slave from the current_arp_slave and make it the candidate
* for becoming the curr_active_slave
*/
if (!bond->current_arp_slave) {
bond->current_arp_slave = bond->first_slave;
if (!bond->current_arp_slave)
return;
}
bond_set_slave_inactive_flags(bond->current_arp_slave);
/* search for next candidate */
bond_for_each_slave_from(bond, slave, i, bond->current_arp_slave->next) {
if (IS_UP(slave->dev)) {
slave->link = BOND_LINK_BACK;
bond_set_slave_active_flags(slave);
bond_arp_send_all(bond, slave);
slave->jiffies = jiffies;
bond->current_arp_slave = slave;
break;
}
/* if the link state is up at this point, we
* mark it down - this can happen if we have
* simultaneous link failures and
* reselect_active_interface doesn't make this
* one the current slave so it is still marked
* up when it is actually down
*/
if (slave->link == BOND_LINK_UP) {
slave->link = BOND_LINK_DOWN;
if (slave->link_failure_count < UINT_MAX)
slave->link_failure_count++;
bond_set_slave_inactive_flags(slave);
pr_info("%s: backup interface %s is now down.\n",
bond->dev->name, slave->dev->name);
}
}
}
void bond_activebackup_arp_mon(struct work_struct *work)
{
struct bonding *bond = container_of(work, struct bonding,
arp_work.work);
bool should_notify_peers = false;
int delta_in_ticks;
read_lock(&bond->lock);
delta_in_ticks = msecs_to_jiffies(bond->params.arp_interval);
if (bond->slave_cnt == 0)
goto re_arm;
should_notify_peers = bond_should_notify_peers(bond);
if (bond_ab_arp_inspect(bond, delta_in_ticks)) {
read_unlock(&bond->lock);
/* Race avoidance with bond_close flush of workqueue */
if (!rtnl_trylock()) {
read_lock(&bond->lock);
delta_in_ticks = 1;
should_notify_peers = false;
goto re_arm;
}
read_lock(&bond->lock);
bond_ab_arp_commit(bond, delta_in_ticks);
read_unlock(&bond->lock);
rtnl_unlock();
read_lock(&bond->lock);
}
bond_ab_arp_probe(bond);
re_arm:
if (bond->params.arp_interval)
queue_delayed_work(bond->wq, &bond->arp_work, delta_in_ticks);
read_unlock(&bond->lock);
if (should_notify_peers) {
if (!rtnl_trylock()) {
read_lock(&bond->lock);
bond->send_peer_notif++;
read_unlock(&bond->lock);
return;
}
netdev_bonding_change(bond->dev, NETDEV_NOTIFY_PEERS);
rtnl_unlock();
}
}
/*-------------------------- netdev event handling --------------------------*/
/*
* Change device name
*/
static int bond_event_changename(struct bonding *bond)
{
bond_remove_proc_entry(bond);
bond_create_proc_entry(bond);
bond_debug_reregister(bond);
return NOTIFY_DONE;
}
static int bond_master_netdev_event(unsigned long event,
struct net_device *bond_dev)
{
struct bonding *event_bond = netdev_priv(bond_dev);
switch (event) {
case NETDEV_CHANGENAME:
return bond_event_changename(event_bond);
case NETDEV_UNREGISTER:
bond_remove_proc_entry(event_bond);
break;
case NETDEV_REGISTER:
bond_create_proc_entry(event_bond);
break;
default:
break;
}
return NOTIFY_DONE;
}
static int bond_slave_netdev_event(unsigned long event,
struct net_device *slave_dev)
{
struct net_device *bond_dev = slave_dev->master;
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave = NULL;
switch (event) {
case NETDEV_UNREGISTER:
if (bond_dev) {
if (bond->setup_by_slave)
bond_release_and_destroy(bond_dev, slave_dev);
else
bond_release(bond_dev, slave_dev);
}
break;
case NETDEV_UP:
case NETDEV_CHANGE:
slave = bond_get_slave_by_dev(bond, slave_dev);
if (slave) {
u32 old_speed = slave->speed;
u8 old_duplex = slave->duplex;
bond_update_speed_duplex(slave);
if (bond->params.mode == BOND_MODE_8023AD) {
if (old_speed != slave->speed)
bond_3ad_adapter_speed_changed(slave);
if (old_duplex != slave->duplex)
bond_3ad_adapter_duplex_changed(slave);
}
}
break;
case NETDEV_DOWN:
/*
* ... Or is it this?
*/
break;
case NETDEV_CHANGEMTU:
/*
* TODO: Should slaves be allowed to
* independently alter their MTU? For
* an active-backup bond, slaves need
* not be the same type of device, so
* MTUs may vary. For other modes,
* slaves arguably should have the
* same MTUs. To do this, we'd need to
* take over the slave's change_mtu
* function for the duration of their
* servitude.
*/
break;
case NETDEV_CHANGENAME:
/*
* TODO: handle changing the primary's name
*/
break;
case NETDEV_FEAT_CHANGE:
bond_compute_features(bond);
break;
default:
break;
}
return NOTIFY_DONE;
}
/*
* bond_netdev_event: handle netdev notifier chain events.
*
* This function receives events for the netdev chain. The caller (an
* ioctl handler calling blocking_notifier_call_chain) holds the necessary
* locks for us to safely manipulate the slave devices (RTNL lock,
* dev_probe_lock).
*/
static int bond_netdev_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *event_dev = (struct net_device *)ptr;
pr_debug("event_dev: %s, event: %lx\n",
event_dev ? event_dev->name : "None",
event);
if (!(event_dev->priv_flags & IFF_BONDING))
return NOTIFY_DONE;
if (event_dev->flags & IFF_MASTER) {
pr_debug("IFF_MASTER\n");
return bond_master_netdev_event(event, event_dev);
}
if (event_dev->flags & IFF_SLAVE) {
pr_debug("IFF_SLAVE\n");
return bond_slave_netdev_event(event, event_dev);
}
return NOTIFY_DONE;
}
static struct notifier_block bond_netdev_notifier = {
.notifier_call = bond_netdev_event,
};
/*---------------------------- Hashing Policies -----------------------------*/
/*
* Hash for the output device based upon layer 2 and layer 3 data. If
* the packet is not IP mimic bond_xmit_hash_policy_l2()
*/
static int bond_xmit_hash_policy_l23(struct sk_buff *skb, int count)
{
struct ethhdr *data = (struct ethhdr *)skb->data;
struct iphdr *iph = ip_hdr(skb);
if (skb->protocol == htons(ETH_P_IP)) {
return ((ntohl(iph->saddr ^ iph->daddr) & 0xffff) ^
(data->h_dest[5] ^ data->h_source[5])) % count;
}
return (data->h_dest[5] ^ data->h_source[5]) % count;
}
/*
* Hash for the output device based upon layer 3 and layer 4 data. If
* the packet is a frag or not TCP or UDP, just use layer 3 data. If it is
* altogether not IP, mimic bond_xmit_hash_policy_l2()
*/
static int bond_xmit_hash_policy_l34(struct sk_buff *skb, int count)
{
struct ethhdr *data = (struct ethhdr *)skb->data;
struct iphdr *iph = ip_hdr(skb);
__be16 *layer4hdr = (__be16 *)((u32 *)iph + iph->ihl);
int layer4_xor = 0;
if (skb->protocol == htons(ETH_P_IP)) {
if (!ip_is_fragment(iph) &&
(iph->protocol == IPPROTO_TCP ||
iph->protocol == IPPROTO_UDP)) {
layer4_xor = ntohs((*layer4hdr ^ *(layer4hdr + 1)));
}
return (layer4_xor ^
((ntohl(iph->saddr ^ iph->daddr)) & 0xffff)) % count;
}
return (data->h_dest[5] ^ data->h_source[5]) % count;
}
/*
* Hash for the output device based upon layer 2 data
*/
static int bond_xmit_hash_policy_l2(struct sk_buff *skb, int count)
{
struct ethhdr *data = (struct ethhdr *)skb->data;
return (data->h_dest[5] ^ data->h_source[5]) % count;
}
/*-------------------------- Device entry points ----------------------------*/
static int bond_open(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave;
int i;
/* reset slave->backup and slave->inactive */
read_lock(&bond->lock);
if (bond->slave_cnt > 0) {
read_lock(&bond->curr_slave_lock);
bond_for_each_slave(bond, slave, i) {
if ((bond->params.mode == BOND_MODE_ACTIVEBACKUP)
&& (slave != bond->curr_active_slave)) {
bond_set_slave_inactive_flags(slave);
} else {
bond_set_slave_active_flags(slave);
}
}
read_unlock(&bond->curr_slave_lock);
}
read_unlock(&bond->lock);
INIT_DELAYED_WORK(&bond->mcast_work, bond_resend_igmp_join_requests_delayed);
if (bond_is_lb(bond)) {
/* bond_alb_initialize must be called before the timer
* is started.
*/
if (bond_alb_initialize(bond, (bond->params.mode == BOND_MODE_ALB))) {
/* something went wrong - fail the open operation */
return -ENOMEM;
}
INIT_DELAYED_WORK(&bond->alb_work, bond_alb_monitor);
queue_delayed_work(bond->wq, &bond->alb_work, 0);
}
if (bond->params.miimon) { /* link check interval, in milliseconds. */
INIT_DELAYED_WORK(&bond->mii_work, bond_mii_monitor);
queue_delayed_work(bond->wq, &bond->mii_work, 0);
}
if (bond->params.arp_interval) { /* arp interval, in milliseconds. */
if (bond->params.mode == BOND_MODE_ACTIVEBACKUP)
INIT_DELAYED_WORK(&bond->arp_work,
bond_activebackup_arp_mon);
else
INIT_DELAYED_WORK(&bond->arp_work,
bond_loadbalance_arp_mon);
queue_delayed_work(bond->wq, &bond->arp_work, 0);
if (bond->params.arp_validate)
bond->recv_probe = bond_arp_rcv;
}
if (bond->params.mode == BOND_MODE_8023AD) {
INIT_DELAYED_WORK(&bond->ad_work, bond_3ad_state_machine_handler);
queue_delayed_work(bond->wq, &bond->ad_work, 0);
/* register to receive LACPDUs */
bond->recv_probe = bond_3ad_lacpdu_recv;
bond_3ad_initiate_agg_selection(bond, 1);
}
return 0;
}
static int bond_close(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
write_lock_bh(&bond->lock);
bond->send_peer_notif = 0;
write_unlock_bh(&bond->lock);
if (bond->params.miimon) { /* link check interval, in milliseconds. */
cancel_delayed_work_sync(&bond->mii_work);
}
if (bond->params.arp_interval) { /* arp interval, in milliseconds. */
cancel_delayed_work_sync(&bond->arp_work);
}
switch (bond->params.mode) {
case BOND_MODE_8023AD:
cancel_delayed_work_sync(&bond->ad_work);
break;
case BOND_MODE_TLB:
case BOND_MODE_ALB:
cancel_delayed_work_sync(&bond->alb_work);
break;
default:
break;
}
if (delayed_work_pending(&bond->mcast_work))
cancel_delayed_work_sync(&bond->mcast_work);
if (bond_is_lb(bond)) {
/* Must be called only after all
* slaves have been released
*/
bond_alb_deinitialize(bond);
}
bond->recv_probe = NULL;
return 0;
}
static struct rtnl_link_stats64 *bond_get_stats(struct net_device *bond_dev,
struct rtnl_link_stats64 *stats)
{
struct bonding *bond = netdev_priv(bond_dev);
struct rtnl_link_stats64 temp;
struct slave *slave;
int i;
memset(stats, 0, sizeof(*stats));
read_lock_bh(&bond->lock);
bond_for_each_slave(bond, slave, i) {
const struct rtnl_link_stats64 *sstats =
dev_get_stats(slave->dev, &temp);
stats->rx_packets += sstats->rx_packets;
stats->rx_bytes += sstats->rx_bytes;
stats->rx_errors += sstats->rx_errors;
stats->rx_dropped += sstats->rx_dropped;
stats->tx_packets += sstats->tx_packets;
stats->tx_bytes += sstats->tx_bytes;
stats->tx_errors += sstats->tx_errors;
stats->tx_dropped += sstats->tx_dropped;
stats->multicast += sstats->multicast;
stats->collisions += sstats->collisions;
stats->rx_length_errors += sstats->rx_length_errors;
stats->rx_over_errors += sstats->rx_over_errors;
stats->rx_crc_errors += sstats->rx_crc_errors;
stats->rx_frame_errors += sstats->rx_frame_errors;
stats->rx_fifo_errors += sstats->rx_fifo_errors;
stats->rx_missed_errors += sstats->rx_missed_errors;
stats->tx_aborted_errors += sstats->tx_aborted_errors;
stats->tx_carrier_errors += sstats->tx_carrier_errors;
stats->tx_fifo_errors += sstats->tx_fifo_errors;
stats->tx_heartbeat_errors += sstats->tx_heartbeat_errors;
stats->tx_window_errors += sstats->tx_window_errors;
}
read_unlock_bh(&bond->lock);
return stats;
}
static int bond_do_ioctl(struct net_device *bond_dev, struct ifreq *ifr, int cmd)
{
struct net_device *slave_dev = NULL;
struct ifbond k_binfo;
struct ifbond __user *u_binfo = NULL;
struct ifslave k_sinfo;
struct ifslave __user *u_sinfo = NULL;
struct mii_ioctl_data *mii = NULL;
int res = 0;
pr_debug("bond_ioctl: master=%s, cmd=%d\n", bond_dev->name, cmd);
switch (cmd) {
case SIOCGMIIPHY:
mii = if_mii(ifr);
if (!mii)
return -EINVAL;
mii->phy_id = 0;
/* Fall Through */
case SIOCGMIIREG:
/*
* We do this again just in case we were called by SIOCGMIIREG
* instead of SIOCGMIIPHY.
*/
mii = if_mii(ifr);
if (!mii)
return -EINVAL;
if (mii->reg_num == 1) {
struct bonding *bond = netdev_priv(bond_dev);
mii->val_out = 0;
read_lock(&bond->lock);
read_lock(&bond->curr_slave_lock);
if (netif_carrier_ok(bond->dev))
mii->val_out = BMSR_LSTATUS;
read_unlock(&bond->curr_slave_lock);
read_unlock(&bond->lock);
}
return 0;
case BOND_INFO_QUERY_OLD:
case SIOCBONDINFOQUERY:
u_binfo = (struct ifbond __user *)ifr->ifr_data;
if (copy_from_user(&k_binfo, u_binfo, sizeof(ifbond)))
return -EFAULT;
res = bond_info_query(bond_dev, &k_binfo);
if (res == 0 &&
copy_to_user(u_binfo, &k_binfo, sizeof(ifbond)))
return -EFAULT;
return res;
case BOND_SLAVE_INFO_QUERY_OLD:
case SIOCBONDSLAVEINFOQUERY:
u_sinfo = (struct ifslave __user *)ifr->ifr_data;
if (copy_from_user(&k_sinfo, u_sinfo, sizeof(ifslave)))
return -EFAULT;
res = bond_slave_info_query(bond_dev, &k_sinfo);
if (res == 0 &&
copy_to_user(u_sinfo, &k_sinfo, sizeof(ifslave)))
return -EFAULT;
return res;
default:
/* Go on */
break;
}
if (!capable(CAP_NET_ADMIN))
return -EPERM;
slave_dev = dev_get_by_name(dev_net(bond_dev), ifr->ifr_slave);
pr_debug("slave_dev=%p:\n", slave_dev);
if (!slave_dev)
res = -ENODEV;
else {
pr_debug("slave_dev->name=%s:\n", slave_dev->name);
switch (cmd) {
case BOND_ENSLAVE_OLD:
case SIOCBONDENSLAVE:
res = bond_enslave(bond_dev, slave_dev);
break;
case BOND_RELEASE_OLD:
case SIOCBONDRELEASE:
res = bond_release(bond_dev, slave_dev);
break;
case BOND_SETHWADDR_OLD:
case SIOCBONDSETHWADDR:
res = bond_sethwaddr(bond_dev, slave_dev);
break;
case BOND_CHANGE_ACTIVE_OLD:
case SIOCBONDCHANGEACTIVE:
res = bond_ioctl_change_active(bond_dev, slave_dev);
break;
default:
res = -EOPNOTSUPP;
}
dev_put(slave_dev);
}
return res;
}
static bool bond_addr_in_mc_list(unsigned char *addr,
struct netdev_hw_addr_list *list,
int addrlen)
{
struct netdev_hw_addr *ha;
netdev_hw_addr_list_for_each(ha, list)
if (!memcmp(ha->addr, addr, addrlen))
return true;
return false;
}
static void bond_change_rx_flags(struct net_device *bond_dev, int change)
{
struct bonding *bond = netdev_priv(bond_dev);
if (change & IFF_PROMISC)
bond_set_promiscuity(bond,
bond_dev->flags & IFF_PROMISC ? 1 : -1);
if (change & IFF_ALLMULTI)
bond_set_allmulti(bond,
bond_dev->flags & IFF_ALLMULTI ? 1 : -1);
}
static void bond_set_multicast_list(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct netdev_hw_addr *ha;
bool found;
read_lock(&bond->lock);
/* looking for addresses to add to slaves' mc list */
netdev_for_each_mc_addr(ha, bond_dev) {
found = bond_addr_in_mc_list(ha->addr, &bond->mc_list,
bond_dev->addr_len);
if (!found)
bond_mc_add(bond, ha->addr);
}
/* looking for addresses to delete from slaves' list */
netdev_hw_addr_list_for_each(ha, &bond->mc_list) {
found = bond_addr_in_mc_list(ha->addr, &bond_dev->mc,
bond_dev->addr_len);
if (!found)
bond_mc_del(bond, ha->addr);
}
/* save master's multicast list */
__hw_addr_flush(&bond->mc_list);
__hw_addr_add_multiple(&bond->mc_list, &bond_dev->mc,
bond_dev->addr_len, NETDEV_HW_ADDR_T_MULTICAST);
read_unlock(&bond->lock);
}
static int bond_neigh_init(struct neighbour *n)
{
struct bonding *bond = netdev_priv(n->dev);
struct slave *slave = bond->first_slave;
const struct net_device_ops *slave_ops;
struct neigh_parms parms;
int ret;
if (!slave)
return 0;
slave_ops = slave->dev->netdev_ops;
if (!slave_ops->ndo_neigh_setup)
return 0;
parms.neigh_setup = NULL;
parms.neigh_cleanup = NULL;
ret = slave_ops->ndo_neigh_setup(slave->dev, &parms);
if (ret)
return ret;
/*
* Assign slave's neigh_cleanup to neighbour in case cleanup is called
* after the last slave has been detached. Assumes that all slaves
* utilize the same neigh_cleanup (true at this writing as only user
* is ipoib).
*/
n->parms->neigh_cleanup = parms.neigh_cleanup;
if (!parms.neigh_setup)
return 0;
return parms.neigh_setup(n);
}
/*
* The bonding ndo_neigh_setup is called at init time beofre any
* slave exists. So we must declare proxy setup function which will
* be used at run time to resolve the actual slave neigh param setup.
*/
static int bond_neigh_setup(struct net_device *dev,
struct neigh_parms *parms)
{
parms->neigh_setup = bond_neigh_init;
return 0;
}
/*
* Change the MTU of all of a master's slaves to match the master
*/
static int bond_change_mtu(struct net_device *bond_dev, int new_mtu)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave, *stop_at;
int res = 0;
int i;
pr_debug("bond=%p, name=%s, new_mtu=%d\n", bond,
(bond_dev ? bond_dev->name : "None"), new_mtu);
/* Can't hold bond->lock with bh disabled here since
* some base drivers panic. On the other hand we can't
* hold bond->lock without bh disabled because we'll
* deadlock. The only solution is to rely on the fact
* that we're under rtnl_lock here, and the slaves
* list won't change. This doesn't solve the problem
* of setting the slave's MTU while it is
* transmitting, but the assumption is that the base
* driver can handle that.
*
* TODO: figure out a way to safely iterate the slaves
* list, but without holding a lock around the actual
* call to the base driver.
*/
bond_for_each_slave(bond, slave, i) {
pr_debug("s %p s->p %p c_m %p\n",
slave,
slave->prev,
slave->dev->netdev_ops->ndo_change_mtu);
res = dev_set_mtu(slave->dev, new_mtu);
if (res) {
/* If we failed to set the slave's mtu to the new value
* we must abort the operation even in ACTIVE_BACKUP
* mode, because if we allow the backup slaves to have
* different mtu values than the active slave we'll
* need to change their mtu when doing a failover. That
* means changing their mtu from timer context, which
* is probably not a good idea.
*/
pr_debug("err %d %s\n", res, slave->dev->name);
goto unwind;
}
}
bond_dev->mtu = new_mtu;
return 0;
unwind:
/* unwind from head to the slave that failed */
stop_at = slave;
bond_for_each_slave_from_to(bond, slave, i, bond->first_slave, stop_at) {
int tmp_res;
tmp_res = dev_set_mtu(slave->dev, bond_dev->mtu);
if (tmp_res) {
pr_debug("unwind err %d dev %s\n",
tmp_res, slave->dev->name);
}
}
return res;
}
/*
* Change HW address
*
* Note that many devices must be down to change the HW address, and
* downing the master releases all slaves. We can make bonds full of
* bonding devices to test this, however.
*/
static int bond_set_mac_address(struct net_device *bond_dev, void *addr)
{
struct bonding *bond = netdev_priv(bond_dev);
struct sockaddr *sa = addr, tmp_sa;
struct slave *slave, *stop_at;
int res = 0;
int i;
if (bond->params.mode == BOND_MODE_ALB)
return bond_alb_set_mac_address(bond_dev, addr);
pr_debug("bond=%p, name=%s\n",
bond, bond_dev ? bond_dev->name : "None");
/*
* If fail_over_mac is set to active, do nothing and return
* success. Returning an error causes ifenslave to fail.
*/
if (bond->params.fail_over_mac == BOND_FOM_ACTIVE)
return 0;
if (!is_valid_ether_addr(sa->sa_data))
return -EADDRNOTAVAIL;
/* Can't hold bond->lock with bh disabled here since
* some base drivers panic. On the other hand we can't
* hold bond->lock without bh disabled because we'll
* deadlock. The only solution is to rely on the fact
* that we're under rtnl_lock here, and the slaves
* list won't change. This doesn't solve the problem
* of setting the slave's hw address while it is
* transmitting, but the assumption is that the base
* driver can handle that.
*
* TODO: figure out a way to safely iterate the slaves
* list, but without holding a lock around the actual
* call to the base driver.
*/
bond_for_each_slave(bond, slave, i) {
const struct net_device_ops *slave_ops = slave->dev->netdev_ops;
pr_debug("slave %p %s\n", slave, slave->dev->name);
if (slave_ops->ndo_set_mac_address == NULL) {
res = -EOPNOTSUPP;
pr_debug("EOPNOTSUPP %s\n", slave->dev->name);
goto unwind;
}
res = dev_set_mac_address(slave->dev, addr);
if (res) {
/* TODO: consider downing the slave
* and retry ?
* User should expect communications
* breakage anyway until ARP finish
* updating, so...
*/
pr_debug("err %d %s\n", res, slave->dev->name);
goto unwind;
}
}
/* success */
memcpy(bond_dev->dev_addr, sa->sa_data, bond_dev->addr_len);
return 0;
unwind:
memcpy(tmp_sa.sa_data, bond_dev->dev_addr, bond_dev->addr_len);
tmp_sa.sa_family = bond_dev->type;
/* unwind from head to the slave that failed */
stop_at = slave;
bond_for_each_slave_from_to(bond, slave, i, bond->first_slave, stop_at) {
int tmp_res;
tmp_res = dev_set_mac_address(slave->dev, &tmp_sa);
if (tmp_res) {
pr_debug("unwind err %d dev %s\n",
tmp_res, slave->dev->name);
}
}
return res;
}
static int bond_xmit_roundrobin(struct sk_buff *skb, struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave, *start_at;
int i, slave_no, res = 1;
struct iphdr *iph = ip_hdr(skb);
/*
* Start with the curr_active_slave that joined the bond as the
* default for sending IGMP traffic. For failover purposes one
* needs to maintain some consistency for the interface that will
* send the join/membership reports. The curr_active_slave found
* will send all of this type of traffic.
*/
if ((iph->protocol == IPPROTO_IGMP) &&
(skb->protocol == htons(ETH_P_IP))) {
read_lock(&bond->curr_slave_lock);
slave = bond->curr_active_slave;
read_unlock(&bond->curr_slave_lock);
if (!slave)
goto out;
} else {
/*
* Concurrent TX may collide on rr_tx_counter; we accept
* that as being rare enough not to justify using an
* atomic op here.
*/
slave_no = bond->rr_tx_counter++ % bond->slave_cnt;
bond_for_each_slave(bond, slave, i) {
slave_no--;
if (slave_no < 0)
break;
}
}
start_at = slave;
bond_for_each_slave_from(bond, slave, i, start_at) {
if (IS_UP(slave->dev) &&
(slave->link == BOND_LINK_UP) &&
bond_is_active_slave(slave)) {
res = bond_dev_queue_xmit(bond, skb, slave->dev);
break;
}
}
out:
if (res) {
/* no suitable interface, frame not sent */
dev_kfree_skb(skb);
}
return NETDEV_TX_OK;
}
/*
* in active-backup mode, we know that bond->curr_active_slave is always valid if
* the bond has a usable interface.
*/
static int bond_xmit_activebackup(struct sk_buff *skb, struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
int res = 1;
read_lock(&bond->curr_slave_lock);
if (bond->curr_active_slave)
res = bond_dev_queue_xmit(bond, skb,
bond->curr_active_slave->dev);
if (res)
/* no suitable interface, frame not sent */
dev_kfree_skb(skb);
read_unlock(&bond->curr_slave_lock);
return NETDEV_TX_OK;
}
/*
* In bond_xmit_xor() , we determine the output device by using a pre-
* determined xmit_hash_policy(), If the selected device is not enabled,
* find the next active slave.
*/
static int bond_xmit_xor(struct sk_buff *skb, struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave, *start_at;
int slave_no;
int i;
int res = 1;
slave_no = bond->xmit_hash_policy(skb, bond->slave_cnt);
bond_for_each_slave(bond, slave, i) {
slave_no--;
if (slave_no < 0)
break;
}
start_at = slave;
bond_for_each_slave_from(bond, slave, i, start_at) {
if (IS_UP(slave->dev) &&
(slave->link == BOND_LINK_UP) &&
bond_is_active_slave(slave)) {
res = bond_dev_queue_xmit(bond, skb, slave->dev);
break;
}
}
if (res) {
/* no suitable interface, frame not sent */
dev_kfree_skb(skb);
}
return NETDEV_TX_OK;
}
/*
* in broadcast mode, we send everything to all usable interfaces.
*/
static int bond_xmit_broadcast(struct sk_buff *skb, struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct slave *slave, *start_at;
struct net_device *tx_dev = NULL;
int i;
int res = 1;
read_lock(&bond->curr_slave_lock);
start_at = bond->curr_active_slave;
read_unlock(&bond->curr_slave_lock);
if (!start_at)
goto out;
bond_for_each_slave_from(bond, slave, i, start_at) {
if (IS_UP(slave->dev) &&
(slave->link == BOND_LINK_UP) &&
bond_is_active_slave(slave)) {
if (tx_dev) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2) {
pr_err("%s: Error: bond_xmit_broadcast(): skb_clone() failed\n",
bond_dev->name);
continue;
}
res = bond_dev_queue_xmit(bond, skb2, tx_dev);
if (res) {
dev_kfree_skb(skb2);
continue;
}
}
tx_dev = slave->dev;
}
}
if (tx_dev)
res = bond_dev_queue_xmit(bond, skb, tx_dev);
out:
if (res)
/* no suitable interface, frame not sent */
dev_kfree_skb(skb);
/* frame sent to all suitable interfaces */
return NETDEV_TX_OK;
}
/*------------------------- Device initialization ---------------------------*/
static void bond_set_xmit_hash_policy(struct bonding *bond)
{
switch (bond->params.xmit_policy) {
case BOND_XMIT_POLICY_LAYER23:
bond->xmit_hash_policy = bond_xmit_hash_policy_l23;
break;
case BOND_XMIT_POLICY_LAYER34:
bond->xmit_hash_policy = bond_xmit_hash_policy_l34;
break;
case BOND_XMIT_POLICY_LAYER2:
default:
bond->xmit_hash_policy = bond_xmit_hash_policy_l2;
break;
}
}
/*
* Lookup the slave that corresponds to a qid
*/
static inline int bond_slave_override(struct bonding *bond,
struct sk_buff *skb)
{
int i, res = 1;
struct slave *slave = NULL;
struct slave *check_slave;
if (!skb->queue_mapping)
return 1;
/* Find out if any slaves have the same mapping as this skb. */
bond_for_each_slave(bond, check_slave, i) {
if (check_slave->queue_id == skb->queue_mapping) {
slave = check_slave;
break;
}
}
/* If the slave isn't UP, use default transmit policy. */
if (slave && slave->queue_id && IS_UP(slave->dev) &&
(slave->link == BOND_LINK_UP)) {
res = bond_dev_queue_xmit(bond, skb, slave->dev);
}
return res;
}
static u16 bond_select_queue(struct net_device *dev, struct sk_buff *skb)
{
/*
* This helper function exists to help dev_pick_tx get the correct
* destination queue. Using a helper function skips a call to
* skb_tx_hash and will put the skbs in the queue we expect on their
* way down to the bonding driver.
*/
u16 txq = skb_rx_queue_recorded(skb) ? skb_get_rx_queue(skb) : 0;
/*
* Save the original txq to restore before passing to the driver
*/
qdisc_skb_cb(skb)->bond_queue_mapping = skb->queue_mapping;
if (unlikely(txq >= dev->real_num_tx_queues)) {
do {
txq -= dev->real_num_tx_queues;
} while (txq >= dev->real_num_tx_queues);
}
return txq;
}
static netdev_tx_t __bond_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct bonding *bond = netdev_priv(dev);
if (TX_QUEUE_OVERRIDE(bond->params.mode)) {
if (!bond_slave_override(bond, skb))
return NETDEV_TX_OK;
}
switch (bond->params.mode) {
case BOND_MODE_ROUNDROBIN:
return bond_xmit_roundrobin(skb, dev);
case BOND_MODE_ACTIVEBACKUP:
return bond_xmit_activebackup(skb, dev);
case BOND_MODE_XOR:
return bond_xmit_xor(skb, dev);
case BOND_MODE_BROADCAST:
return bond_xmit_broadcast(skb, dev);
case BOND_MODE_8023AD:
return bond_3ad_xmit_xor(skb, dev);
case BOND_MODE_ALB:
case BOND_MODE_TLB:
return bond_alb_xmit(skb, dev);
default:
/* Should never happen, mode already checked */
pr_err("%s: Error: Unknown bonding mode %d\n",
dev->name, bond->params.mode);
WARN_ON_ONCE(1);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
}
static netdev_tx_t bond_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct bonding *bond = netdev_priv(dev);
netdev_tx_t ret = NETDEV_TX_OK;
/*
* If we risk deadlock from transmitting this in the
* netpoll path, tell netpoll to queue the frame for later tx
*/
if (is_netpoll_tx_blocked(dev))
return NETDEV_TX_BUSY;
read_lock(&bond->lock);
if (bond->slave_cnt)
ret = __bond_start_xmit(skb, dev);
else
dev_kfree_skb(skb);
read_unlock(&bond->lock);
return ret;
}
/*
* set bond mode specific net device operations
*/
void bond_set_mode_ops(struct bonding *bond, int mode)
{
struct net_device *bond_dev = bond->dev;
switch (mode) {
case BOND_MODE_ROUNDROBIN:
break;
case BOND_MODE_ACTIVEBACKUP:
break;
case BOND_MODE_XOR:
bond_set_xmit_hash_policy(bond);
break;
case BOND_MODE_BROADCAST:
break;
case BOND_MODE_8023AD:
bond_set_xmit_hash_policy(bond);
break;
case BOND_MODE_ALB:
/* FALLTHRU */
case BOND_MODE_TLB:
break;
default:
/* Should never happen, mode already checked */
pr_err("%s: Error: Unknown bonding mode %d\n",
bond_dev->name, mode);
break;
}
}
static void bond_ethtool_get_drvinfo(struct net_device *bond_dev,
struct ethtool_drvinfo *drvinfo)
{
strncpy(drvinfo->driver, DRV_NAME, 32);
strncpy(drvinfo->version, DRV_VERSION, 32);
snprintf(drvinfo->fw_version, 32, "%d", BOND_ABI_VERSION);
}
static const struct ethtool_ops bond_ethtool_ops = {
.get_drvinfo = bond_ethtool_get_drvinfo,
.get_link = ethtool_op_get_link,
};
static const struct net_device_ops bond_netdev_ops = {
.ndo_init = bond_init,
.ndo_uninit = bond_uninit,
.ndo_open = bond_open,
.ndo_stop = bond_close,
.ndo_start_xmit = bond_start_xmit,
.ndo_select_queue = bond_select_queue,
.ndo_get_stats64 = bond_get_stats,
.ndo_do_ioctl = bond_do_ioctl,
.ndo_change_rx_flags = bond_change_rx_flags,
.ndo_set_rx_mode = bond_set_multicast_list,
.ndo_change_mtu = bond_change_mtu,
.ndo_set_mac_address = bond_set_mac_address,
.ndo_neigh_setup = bond_neigh_setup,
.ndo_vlan_rx_add_vid = bond_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = bond_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_netpoll_setup = bond_netpoll_setup,
.ndo_netpoll_cleanup = bond_netpoll_cleanup,
.ndo_poll_controller = bond_poll_controller,
#endif
.ndo_add_slave = bond_enslave,
.ndo_del_slave = bond_release,
.ndo_fix_features = bond_fix_features,
};
static void bond_destructor(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
if (bond->wq)
destroy_workqueue(bond->wq);
free_netdev(bond_dev);
}
static void bond_setup(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
/* initialize rwlocks */
rwlock_init(&bond->lock);
rwlock_init(&bond->curr_slave_lock);
bond->params = bonding_defaults;
/* Initialize pointers */
bond->dev = bond_dev;
INIT_LIST_HEAD(&bond->vlan_list);
/* Initialize the device entry points */
ether_setup(bond_dev);
bond_dev->netdev_ops = &bond_netdev_ops;
bond_dev->ethtool_ops = &bond_ethtool_ops;
bond_set_mode_ops(bond, bond->params.mode);
bond_dev->destructor = bond_destructor;
/* Initialize the device options */
bond_dev->tx_queue_len = 0;
bond_dev->flags |= IFF_MASTER|IFF_MULTICAST;
bond_dev->priv_flags |= IFF_BONDING;
bond_dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING);
/* At first, we block adding VLANs. That's the only way to
* prevent problems that occur when adding VLANs over an
* empty bond. The block will be removed once non-challenged
* slaves are enslaved.
*/
bond_dev->features |= NETIF_F_VLAN_CHALLENGED;
/* don't acquire bond device's netif_tx_lock when
* transmitting */
bond_dev->features |= NETIF_F_LLTX;
/* By default, we declare the bond to be fully
* VLAN hardware accelerated capable. Special
* care is taken in the various xmit functions
* when there are slaves that are not hw accel
* capable
*/
bond_dev->hw_features = BOND_VLAN_FEATURES |
NETIF_F_HW_VLAN_TX |
NETIF_F_HW_VLAN_RX |
NETIF_F_HW_VLAN_FILTER;
bond_dev->hw_features &= ~(NETIF_F_ALL_CSUM & ~NETIF_F_HW_CSUM);
bond_dev->features |= bond_dev->hw_features;
}
static void bond_work_cancel_all(struct bonding *bond)
{
if (bond->params.miimon && delayed_work_pending(&bond->mii_work))
cancel_delayed_work_sync(&bond->mii_work);
if (bond->params.arp_interval && delayed_work_pending(&bond->arp_work))
cancel_delayed_work_sync(&bond->arp_work);
if (bond->params.mode == BOND_MODE_ALB &&
delayed_work_pending(&bond->alb_work))
cancel_delayed_work_sync(&bond->alb_work);
if (bond->params.mode == BOND_MODE_8023AD &&
delayed_work_pending(&bond->ad_work))
cancel_delayed_work_sync(&bond->ad_work);
if (delayed_work_pending(&bond->mcast_work))
cancel_delayed_work_sync(&bond->mcast_work);
}
/*
* Destroy a bonding device.
* Must be under rtnl_lock when this function is called.
*/
static void bond_uninit(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct vlan_entry *vlan, *tmp;
bond_netpoll_cleanup(bond_dev);
/* Release the bonded slaves */
bond_release_all(bond_dev);
list_del(&bond->bond_list);
bond_work_cancel_all(bond);
bond_debug_unregister(bond);
__hw_addr_flush(&bond->mc_list);
list_for_each_entry_safe(vlan, tmp, &bond->vlan_list, vlan_list) {
list_del(&vlan->vlan_list);
kfree(vlan);
}
}
/*------------------------- Module initialization ---------------------------*/
/*
* Convert string input module parms. Accept either the
* number of the mode or its string name. A bit complicated because
* some mode names are substrings of other names, and calls from sysfs
* may have whitespace in the name (trailing newlines, for example).
*/
int bond_parse_parm(const char *buf, const struct bond_parm_tbl *tbl)
{
int modeint = -1, i, rv;
char *p, modestr[BOND_MAX_MODENAME_LEN + 1] = { 0, };
for (p = (char *)buf; *p; p++)
if (!(isdigit(*p) || isspace(*p)))
break;
if (*p)
rv = sscanf(buf, "%20s", modestr);
else
rv = sscanf(buf, "%d", &modeint);
if (!rv)
return -1;
for (i = 0; tbl[i].modename; i++) {
if (modeint == tbl[i].mode)
return tbl[i].mode;
if (strcmp(modestr, tbl[i].modename) == 0)
return tbl[i].mode;
}
return -1;
}
static int bond_check_params(struct bond_params *params)
{
int arp_validate_value, fail_over_mac_value, primary_reselect_value;
/*
* Convert string parameters.
*/
if (mode) {
bond_mode = bond_parse_parm(mode, bond_mode_tbl);
if (bond_mode == -1) {
pr_err("Error: Invalid bonding mode \"%s\"\n",
mode == NULL ? "NULL" : mode);
return -EINVAL;
}
}
if (xmit_hash_policy) {
if ((bond_mode != BOND_MODE_XOR) &&
(bond_mode != BOND_MODE_8023AD)) {
pr_info("xmit_hash_policy param is irrelevant in mode %s\n",
bond_mode_name(bond_mode));
} else {
xmit_hashtype = bond_parse_parm(xmit_hash_policy,
xmit_hashtype_tbl);
if (xmit_hashtype == -1) {
pr_err("Error: Invalid xmit_hash_policy \"%s\"\n",
xmit_hash_policy == NULL ? "NULL" :
xmit_hash_policy);
return -EINVAL;
}
}
}
if (lacp_rate) {
if (bond_mode != BOND_MODE_8023AD) {
pr_info("lacp_rate param is irrelevant in mode %s\n",
bond_mode_name(bond_mode));
} else {
lacp_fast = bond_parse_parm(lacp_rate, bond_lacp_tbl);
if (lacp_fast == -1) {
pr_err("Error: Invalid lacp rate \"%s\"\n",
lacp_rate == NULL ? "NULL" : lacp_rate);
return -EINVAL;
}
}
}
if (ad_select) {
params->ad_select = bond_parse_parm(ad_select, ad_select_tbl);
if (params->ad_select == -1) {
pr_err("Error: Invalid ad_select \"%s\"\n",
ad_select == NULL ? "NULL" : ad_select);
return -EINVAL;
}
if (bond_mode != BOND_MODE_8023AD) {
pr_warning("ad_select param only affects 802.3ad mode\n");
}
} else {
params->ad_select = BOND_AD_STABLE;
}
if (max_bonds < 0) {
pr_warning("Warning: max_bonds (%d) not in range %d-%d, so it was reset to BOND_DEFAULT_MAX_BONDS (%d)\n",
max_bonds, 0, INT_MAX, BOND_DEFAULT_MAX_BONDS);
max_bonds = BOND_DEFAULT_MAX_BONDS;
}
if (miimon < 0) {
pr_warning("Warning: miimon module parameter (%d), not in range 0-%d, so it was reset to %d\n",
miimon, INT_MAX, BOND_LINK_MON_INTERV);
miimon = BOND_LINK_MON_INTERV;
}
if (updelay < 0) {
pr_warning("Warning: updelay module parameter (%d), not in range 0-%d, so it was reset to 0\n",
updelay, INT_MAX);
updelay = 0;
}
if (downdelay < 0) {
pr_warning("Warning: downdelay module parameter (%d), not in range 0-%d, so it was reset to 0\n",
downdelay, INT_MAX);
downdelay = 0;
}
if ((use_carrier != 0) && (use_carrier != 1)) {
pr_warning("Warning: use_carrier module parameter (%d), not of valid value (0/1), so it was set to 1\n",
use_carrier);
use_carrier = 1;
}
if (num_peer_notif < 0 || num_peer_notif > 255) {
pr_warning("Warning: num_grat_arp/num_unsol_na (%d) not in range 0-255 so it was reset to 1\n",
num_peer_notif);
num_peer_notif = 1;
}
/* reset values for 802.3ad */
if (bond_mode == BOND_MODE_8023AD) {
if (!miimon) {
pr_warning("Warning: miimon must be specified, otherwise bonding will not detect link failure, speed and duplex which are essential for 802.3ad operation\n");
pr_warning("Forcing miimon to 100msec\n");
miimon = 100;
}
}
if (tx_queues < 1 || tx_queues > 255) {
pr_warning("Warning: tx_queues (%d) should be between "
"1 and 255, resetting to %d\n",
tx_queues, BOND_DEFAULT_TX_QUEUES);
tx_queues = BOND_DEFAULT_TX_QUEUES;
}
if ((all_slaves_active != 0) && (all_slaves_active != 1)) {
pr_warning("Warning: all_slaves_active module parameter (%d), "
"not of valid value (0/1), so it was set to "
"0\n", all_slaves_active);
all_slaves_active = 0;
}
if (resend_igmp < 0 || resend_igmp > 255) {
pr_warning("Warning: resend_igmp (%d) should be between "
"0 and 255, resetting to %d\n",
resend_igmp, BOND_DEFAULT_RESEND_IGMP);
resend_igmp = BOND_DEFAULT_RESEND_IGMP;
}
/* reset values for TLB/ALB */
if ((bond_mode == BOND_MODE_TLB) ||
(bond_mode == BOND_MODE_ALB)) {
if (!miimon) {
pr_warning("Warning: miimon must be specified, otherwise bonding will not detect link failure and link speed which are essential for TLB/ALB load balancing\n");
pr_warning("Forcing miimon to 100msec\n");
miimon = 100;
}
}
if (bond_mode == BOND_MODE_ALB) {
pr_notice("In ALB mode you might experience client disconnections upon reconnection of a link if the bonding module updelay parameter (%d msec) is incompatible with the forwarding delay time of the switch\n",
updelay);
}
if (!miimon) {
if (updelay || downdelay) {
/* just warn the user the up/down delay will have
* no effect since miimon is zero...
*/
pr_warning("Warning: miimon module parameter not set and updelay (%d) or downdelay (%d) module parameter is set; updelay and downdelay have no effect unless miimon is set\n",
updelay, downdelay);
}
} else {
/* don't allow arp monitoring */
if (arp_interval) {
pr_warning("Warning: miimon (%d) and arp_interval (%d) can't be used simultaneously, disabling ARP monitoring\n",
miimon, arp_interval);
arp_interval = 0;
}
if ((updelay % miimon) != 0) {
pr_warning("Warning: updelay (%d) is not a multiple of miimon (%d), updelay rounded to %d ms\n",
updelay, miimon,
(updelay / miimon) * miimon);
}
updelay /= miimon;
if ((downdelay % miimon) != 0) {
pr_warning("Warning: downdelay (%d) is not a multiple of miimon (%d), downdelay rounded to %d ms\n",
downdelay, miimon,
(downdelay / miimon) * miimon);
}
downdelay /= miimon;
}
if (arp_interval < 0) {
pr_warning("Warning: arp_interval module parameter (%d) , not in range 0-%d, so it was reset to %d\n",
arp_interval, INT_MAX, BOND_LINK_ARP_INTERV);
arp_interval = BOND_LINK_ARP_INTERV;
}
for (arp_ip_count = 0;
(arp_ip_count < BOND_MAX_ARP_TARGETS) && arp_ip_target[arp_ip_count];
arp_ip_count++) {
/* not complete check, but should be good enough to
catch mistakes */
if (!isdigit(arp_ip_target[arp_ip_count][0])) {
pr_warning("Warning: bad arp_ip_target module parameter (%s), ARP monitoring will not be performed\n",
arp_ip_target[arp_ip_count]);
arp_interval = 0;
} else {
__be32 ip = in_aton(arp_ip_target[arp_ip_count]);
arp_target[arp_ip_count] = ip;
}
}
if (arp_interval && !arp_ip_count) {
/* don't allow arping if no arp_ip_target given... */
pr_warning("Warning: arp_interval module parameter (%d) specified without providing an arp_ip_target parameter, arp_interval was reset to 0\n",
arp_interval);
arp_interval = 0;
}
if (arp_validate) {
if (bond_mode != BOND_MODE_ACTIVEBACKUP) {
pr_err("arp_validate only supported in active-backup mode\n");
return -EINVAL;
}
if (!arp_interval) {
pr_err("arp_validate requires arp_interval\n");
return -EINVAL;
}
arp_validate_value = bond_parse_parm(arp_validate,
arp_validate_tbl);
if (arp_validate_value == -1) {
pr_err("Error: invalid arp_validate \"%s\"\n",
arp_validate == NULL ? "NULL" : arp_validate);
return -EINVAL;
}
} else
arp_validate_value = 0;
if (miimon) {
pr_info("MII link monitoring set to %d ms\n", miimon);
} else if (arp_interval) {
int i;
pr_info("ARP monitoring set to %d ms, validate %s, with %d target(s):",
arp_interval,
arp_validate_tbl[arp_validate_value].modename,
arp_ip_count);
for (i = 0; i < arp_ip_count; i++)
pr_info(" %s", arp_ip_target[i]);
pr_info("\n");
} else if (max_bonds) {
/* miimon and arp_interval not set, we need one so things
* work as expected, see bonding.txt for details
*/
pr_debug("Warning: either miimon or arp_interval and arp_ip_target module parameters must be specified, otherwise bonding will not detect link failures! see bonding.txt for details.\n");
}
if (primary && !USES_PRIMARY(bond_mode)) {
/* currently, using a primary only makes sense
* in active backup, TLB or ALB modes
*/
pr_warning("Warning: %s primary device specified but has no effect in %s mode\n",
primary, bond_mode_name(bond_mode));
primary = NULL;
}
if (primary && primary_reselect) {
primary_reselect_value = bond_parse_parm(primary_reselect,
pri_reselect_tbl);
if (primary_reselect_value == -1) {
pr_err("Error: Invalid primary_reselect \"%s\"\n",
primary_reselect ==
NULL ? "NULL" : primary_reselect);
return -EINVAL;
}
} else {
primary_reselect_value = BOND_PRI_RESELECT_ALWAYS;
}
if (fail_over_mac) {
fail_over_mac_value = bond_parse_parm(fail_over_mac,
fail_over_mac_tbl);
if (fail_over_mac_value == -1) {
pr_err("Error: invalid fail_over_mac \"%s\"\n",
arp_validate == NULL ? "NULL" : arp_validate);
return -EINVAL;
}
if (bond_mode != BOND_MODE_ACTIVEBACKUP)
pr_warning("Warning: fail_over_mac only affects active-backup mode.\n");
} else {
fail_over_mac_value = BOND_FOM_NONE;
}
/* fill params struct with the proper values */
params->mode = bond_mode;
params->xmit_policy = xmit_hashtype;
params->miimon = miimon;
params->num_peer_notif = num_peer_notif;
params->arp_interval = arp_interval;
params->arp_validate = arp_validate_value;
params->updelay = updelay;
params->downdelay = downdelay;
params->use_carrier = use_carrier;
params->lacp_fast = lacp_fast;
params->primary[0] = 0;
params->primary_reselect = primary_reselect_value;
params->fail_over_mac = fail_over_mac_value;
params->tx_queues = tx_queues;
params->all_slaves_active = all_slaves_active;
params->resend_igmp = resend_igmp;
params->min_links = min_links;
if (primary) {
strncpy(params->primary, primary, IFNAMSIZ);
params->primary[IFNAMSIZ - 1] = 0;
}
memcpy(params->arp_targets, arp_target, sizeof(arp_target));
return 0;
}
static struct lock_class_key bonding_netdev_xmit_lock_key;
static struct lock_class_key bonding_netdev_addr_lock_key;
static void bond_set_lockdep_class_one(struct net_device *dev,
struct netdev_queue *txq,
void *_unused)
{
lockdep_set_class(&txq->_xmit_lock,
&bonding_netdev_xmit_lock_key);
}
static void bond_set_lockdep_class(struct net_device *dev)
{
lockdep_set_class(&dev->addr_list_lock,
&bonding_netdev_addr_lock_key);
netdev_for_each_tx_queue(dev, bond_set_lockdep_class_one, NULL);
}
/*
* Called from registration process
*/
static int bond_init(struct net_device *bond_dev)
{
struct bonding *bond = netdev_priv(bond_dev);
struct bond_net *bn = net_generic(dev_net(bond_dev), bond_net_id);
struct alb_bond_info *bond_info = &(BOND_ALB_INFO(bond));
pr_debug("Begin bond_init for %s\n", bond_dev->name);
/*
* Initialize locks that may be required during
* en/deslave operations. All of the bond_open work
* (of which this is part) should really be moved to
* a phase prior to dev_open
*/
spin_lock_init(&(bond_info->tx_hashtbl_lock));
spin_lock_init(&(bond_info->rx_hashtbl_lock));
bond->wq = create_singlethread_workqueue(bond_dev->name);
if (!bond->wq)
return -ENOMEM;
bond_set_lockdep_class(bond_dev);
list_add_tail(&bond->bond_list, &bn->dev_list);
bond_prepare_sysfs_group(bond);
bond_debug_register(bond);
__hw_addr_init(&bond->mc_list);
return 0;
}
static int bond_validate(struct nlattr *tb[], struct nlattr *data[])
{
if (tb[IFLA_ADDRESS]) {
if (nla_len(tb[IFLA_ADDRESS]) != ETH_ALEN)
return -EINVAL;
if (!is_valid_ether_addr(nla_data(tb[IFLA_ADDRESS])))
return -EADDRNOTAVAIL;
}
return 0;
}
static int bond_get_tx_queues(struct net *net, struct nlattr *tb[],
unsigned int *num_queues,
unsigned int *real_num_queues)
{
*num_queues = tx_queues;
return 0;
}
static struct rtnl_link_ops bond_link_ops __read_mostly = {
.kind = "bond",
.priv_size = sizeof(struct bonding),
.setup = bond_setup,
.validate = bond_validate,
.get_tx_queues = bond_get_tx_queues,
};
/* Create a new bond based on the specified name and bonding parameters.
* If name is NULL, obtain a suitable "bond%d" name for us.
* Caller must NOT hold rtnl_lock; we need to release it here before we
* set up our sysfs entries.
*/
int bond_create(struct net *net, const char *name)
{
struct net_device *bond_dev;
int res;
rtnl_lock();
bond_dev = alloc_netdev_mq(sizeof(struct bonding),
name ? name : "bond%d",
bond_setup, tx_queues);
if (!bond_dev) {
pr_err("%s: eek! can't alloc netdev!\n", name);
rtnl_unlock();
return -ENOMEM;
}
dev_net_set(bond_dev, net);
bond_dev->rtnl_link_ops = &bond_link_ops;
res = register_netdevice(bond_dev);
netif_carrier_off(bond_dev);
rtnl_unlock();
if (res < 0)
bond_destructor(bond_dev);
return res;
}
static int __net_init bond_net_init(struct net *net)
{
struct bond_net *bn = net_generic(net, bond_net_id);
bn->net = net;
INIT_LIST_HEAD(&bn->dev_list);
bond_create_proc_dir(bn);
bond_create_sysfs(bn);
return 0;
}
static void __net_exit bond_net_exit(struct net *net)
{
struct bond_net *bn = net_generic(net, bond_net_id);
bond_destroy_sysfs(bn);
bond_destroy_proc_dir(bn);
}
static struct pernet_operations bond_net_ops = {
.init = bond_net_init,
.exit = bond_net_exit,
.id = &bond_net_id,
.size = sizeof(struct bond_net),
};
static int __init bonding_init(void)
{
int i;
int res;
pr_info("%s", bond_version);
res = bond_check_params(&bonding_defaults);
if (res)
goto out;
res = register_pernet_subsys(&bond_net_ops);
if (res)
goto out;
res = rtnl_link_register(&bond_link_ops);
if (res)
goto err_link;
bond_create_debugfs();
for (i = 0; i < max_bonds; i++) {
res = bond_create(&init_net, NULL);
if (res)
goto err;
}
register_netdevice_notifier(&bond_netdev_notifier);
out:
return res;
err:
rtnl_link_unregister(&bond_link_ops);
err_link:
unregister_pernet_subsys(&bond_net_ops);
goto out;
}
static void __exit bonding_exit(void)
{
unregister_netdevice_notifier(&bond_netdev_notifier);
bond_destroy_debugfs();
rtnl_link_unregister(&bond_link_ops);
unregister_pernet_subsys(&bond_net_ops);
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Make sure we don't have an imbalance on our netpoll blocking
*/
WARN_ON(atomic_read(&netpoll_block_tx));
#endif
}
module_init(bonding_init);
module_exit(bonding_exit);
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
MODULE_DESCRIPTION(DRV_DESCRIPTION ", v" DRV_VERSION);
MODULE_AUTHOR("Thomas Davis, tadavis@lbl.gov and many others");
MODULE_ALIAS_RTNL_LINK("bond");
| gpl-2.0 |
hikerockies/linux | fs/btrfs/delayed-ref.c | 690 | 26047 | /*
* Copyright (C) 2009 Oracle. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 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 021110-1307, USA.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/sort.h>
#include "ctree.h"
#include "delayed-ref.h"
#include "transaction.h"
struct kmem_cache *btrfs_delayed_ref_head_cachep;
struct kmem_cache *btrfs_delayed_tree_ref_cachep;
struct kmem_cache *btrfs_delayed_data_ref_cachep;
struct kmem_cache *btrfs_delayed_extent_op_cachep;
/*
* delayed back reference update tracking. For subvolume trees
* we queue up extent allocations and backref maintenance for
* delayed processing. This avoids deep call chains where we
* add extents in the middle of btrfs_search_slot, and it allows
* us to buffer up frequently modified backrefs in an rb tree instead
* of hammering updates on the extent allocation tree.
*/
/*
* compare two delayed tree backrefs with same bytenr and type
*/
static int comp_tree_refs(struct btrfs_delayed_tree_ref *ref2,
struct btrfs_delayed_tree_ref *ref1, int type)
{
if (type == BTRFS_TREE_BLOCK_REF_KEY) {
if (ref1->root < ref2->root)
return -1;
if (ref1->root > ref2->root)
return 1;
} else {
if (ref1->parent < ref2->parent)
return -1;
if (ref1->parent > ref2->parent)
return 1;
}
return 0;
}
/*
* compare two delayed data backrefs with same bytenr and type
*/
static int comp_data_refs(struct btrfs_delayed_data_ref *ref2,
struct btrfs_delayed_data_ref *ref1)
{
if (ref1->node.type == BTRFS_EXTENT_DATA_REF_KEY) {
if (ref1->root < ref2->root)
return -1;
if (ref1->root > ref2->root)
return 1;
if (ref1->objectid < ref2->objectid)
return -1;
if (ref1->objectid > ref2->objectid)
return 1;
if (ref1->offset < ref2->offset)
return -1;
if (ref1->offset > ref2->offset)
return 1;
} else {
if (ref1->parent < ref2->parent)
return -1;
if (ref1->parent > ref2->parent)
return 1;
}
return 0;
}
/*
* entries in the rb tree are ordered by the byte number of the extent,
* type of the delayed backrefs and content of delayed backrefs.
*/
static int comp_entry(struct btrfs_delayed_ref_node *ref2,
struct btrfs_delayed_ref_node *ref1,
bool compare_seq)
{
if (ref1->bytenr < ref2->bytenr)
return -1;
if (ref1->bytenr > ref2->bytenr)
return 1;
if (ref1->is_head && ref2->is_head)
return 0;
if (ref2->is_head)
return -1;
if (ref1->is_head)
return 1;
if (ref1->type < ref2->type)
return -1;
if (ref1->type > ref2->type)
return 1;
if (ref1->no_quota > ref2->no_quota)
return 1;
if (ref1->no_quota < ref2->no_quota)
return -1;
/* merging of sequenced refs is not allowed */
if (compare_seq) {
if (ref1->seq < ref2->seq)
return -1;
if (ref1->seq > ref2->seq)
return 1;
}
if (ref1->type == BTRFS_TREE_BLOCK_REF_KEY ||
ref1->type == BTRFS_SHARED_BLOCK_REF_KEY) {
return comp_tree_refs(btrfs_delayed_node_to_tree_ref(ref2),
btrfs_delayed_node_to_tree_ref(ref1),
ref1->type);
} else if (ref1->type == BTRFS_EXTENT_DATA_REF_KEY ||
ref1->type == BTRFS_SHARED_DATA_REF_KEY) {
return comp_data_refs(btrfs_delayed_node_to_data_ref(ref2),
btrfs_delayed_node_to_data_ref(ref1));
}
BUG();
return 0;
}
/*
* insert a new ref into the rbtree. This returns any existing refs
* for the same (bytenr,parent) tuple, or NULL if the new node was properly
* inserted.
*/
static struct btrfs_delayed_ref_node *tree_insert(struct rb_root *root,
struct rb_node *node)
{
struct rb_node **p = &root->rb_node;
struct rb_node *parent_node = NULL;
struct btrfs_delayed_ref_node *entry;
struct btrfs_delayed_ref_node *ins;
int cmp;
ins = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
while (*p) {
parent_node = *p;
entry = rb_entry(parent_node, struct btrfs_delayed_ref_node,
rb_node);
cmp = comp_entry(entry, ins, 1);
if (cmp < 0)
p = &(*p)->rb_left;
else if (cmp > 0)
p = &(*p)->rb_right;
else
return entry;
}
rb_link_node(node, parent_node, p);
rb_insert_color(node, root);
return NULL;
}
/* insert a new ref to head ref rbtree */
static struct btrfs_delayed_ref_head *htree_insert(struct rb_root *root,
struct rb_node *node)
{
struct rb_node **p = &root->rb_node;
struct rb_node *parent_node = NULL;
struct btrfs_delayed_ref_head *entry;
struct btrfs_delayed_ref_head *ins;
u64 bytenr;
ins = rb_entry(node, struct btrfs_delayed_ref_head, href_node);
bytenr = ins->node.bytenr;
while (*p) {
parent_node = *p;
entry = rb_entry(parent_node, struct btrfs_delayed_ref_head,
href_node);
if (bytenr < entry->node.bytenr)
p = &(*p)->rb_left;
else if (bytenr > entry->node.bytenr)
p = &(*p)->rb_right;
else
return entry;
}
rb_link_node(node, parent_node, p);
rb_insert_color(node, root);
return NULL;
}
/*
* find an head entry based on bytenr. This returns the delayed ref
* head if it was able to find one, or NULL if nothing was in that spot.
* If return_bigger is given, the next bigger entry is returned if no exact
* match is found.
*/
static struct btrfs_delayed_ref_head *
find_ref_head(struct rb_root *root, u64 bytenr,
int return_bigger)
{
struct rb_node *n;
struct btrfs_delayed_ref_head *entry;
n = root->rb_node;
entry = NULL;
while (n) {
entry = rb_entry(n, struct btrfs_delayed_ref_head, href_node);
if (bytenr < entry->node.bytenr)
n = n->rb_left;
else if (bytenr > entry->node.bytenr)
n = n->rb_right;
else
return entry;
}
if (entry && return_bigger) {
if (bytenr > entry->node.bytenr) {
n = rb_next(&entry->href_node);
if (!n)
n = rb_first(root);
entry = rb_entry(n, struct btrfs_delayed_ref_head,
href_node);
return entry;
}
return entry;
}
return NULL;
}
int btrfs_delayed_ref_lock(struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_head *head)
{
struct btrfs_delayed_ref_root *delayed_refs;
delayed_refs = &trans->transaction->delayed_refs;
assert_spin_locked(&delayed_refs->lock);
if (mutex_trylock(&head->mutex))
return 0;
atomic_inc(&head->node.refs);
spin_unlock(&delayed_refs->lock);
mutex_lock(&head->mutex);
spin_lock(&delayed_refs->lock);
if (!head->node.in_tree) {
mutex_unlock(&head->mutex);
btrfs_put_delayed_ref(&head->node);
return -EAGAIN;
}
btrfs_put_delayed_ref(&head->node);
return 0;
}
static inline void drop_delayed_ref(struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_root *delayed_refs,
struct btrfs_delayed_ref_head *head,
struct btrfs_delayed_ref_node *ref)
{
if (btrfs_delayed_ref_is_head(ref)) {
head = btrfs_delayed_node_to_head(ref);
rb_erase(&head->href_node, &delayed_refs->href_root);
} else {
assert_spin_locked(&head->lock);
rb_erase(&ref->rb_node, &head->ref_root);
}
ref->in_tree = 0;
btrfs_put_delayed_ref(ref);
atomic_dec(&delayed_refs->num_entries);
if (trans->delayed_ref_updates)
trans->delayed_ref_updates--;
}
static int merge_ref(struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_root *delayed_refs,
struct btrfs_delayed_ref_head *head,
struct btrfs_delayed_ref_node *ref, u64 seq)
{
struct rb_node *node;
int mod = 0;
int done = 0;
node = rb_next(&ref->rb_node);
while (!done && node) {
struct btrfs_delayed_ref_node *next;
next = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
node = rb_next(node);
if (seq && next->seq >= seq)
break;
if (comp_entry(ref, next, 0))
continue;
if (ref->action == next->action) {
mod = next->ref_mod;
} else {
if (ref->ref_mod < next->ref_mod) {
struct btrfs_delayed_ref_node *tmp;
tmp = ref;
ref = next;
next = tmp;
done = 1;
}
mod = -next->ref_mod;
}
drop_delayed_ref(trans, delayed_refs, head, next);
ref->ref_mod += mod;
if (ref->ref_mod == 0) {
drop_delayed_ref(trans, delayed_refs, head, ref);
done = 1;
} else {
/*
* You can't have multiples of the same ref on a tree
* block.
*/
WARN_ON(ref->type == BTRFS_TREE_BLOCK_REF_KEY ||
ref->type == BTRFS_SHARED_BLOCK_REF_KEY);
}
}
return done;
}
void btrfs_merge_delayed_refs(struct btrfs_trans_handle *trans,
struct btrfs_fs_info *fs_info,
struct btrfs_delayed_ref_root *delayed_refs,
struct btrfs_delayed_ref_head *head)
{
struct rb_node *node;
u64 seq = 0;
assert_spin_locked(&head->lock);
/*
* We don't have too much refs to merge in the case of delayed data
* refs.
*/
if (head->is_data)
return;
spin_lock(&fs_info->tree_mod_seq_lock);
if (!list_empty(&fs_info->tree_mod_seq_list)) {
struct seq_list *elem;
elem = list_first_entry(&fs_info->tree_mod_seq_list,
struct seq_list, list);
seq = elem->seq;
}
spin_unlock(&fs_info->tree_mod_seq_lock);
node = rb_first(&head->ref_root);
while (node) {
struct btrfs_delayed_ref_node *ref;
ref = rb_entry(node, struct btrfs_delayed_ref_node,
rb_node);
/* We can't merge refs that are outside of our seq count */
if (seq && ref->seq >= seq)
break;
if (merge_ref(trans, delayed_refs, head, ref, seq))
node = rb_first(&head->ref_root);
else
node = rb_next(&ref->rb_node);
}
}
int btrfs_check_delayed_seq(struct btrfs_fs_info *fs_info,
struct btrfs_delayed_ref_root *delayed_refs,
u64 seq)
{
struct seq_list *elem;
int ret = 0;
spin_lock(&fs_info->tree_mod_seq_lock);
if (!list_empty(&fs_info->tree_mod_seq_list)) {
elem = list_first_entry(&fs_info->tree_mod_seq_list,
struct seq_list, list);
if (seq >= elem->seq) {
pr_debug("holding back delayed_ref %#x.%x, lowest is %#x.%x (%p)\n",
(u32)(seq >> 32), (u32)seq,
(u32)(elem->seq >> 32), (u32)elem->seq,
delayed_refs);
ret = 1;
}
}
spin_unlock(&fs_info->tree_mod_seq_lock);
return ret;
}
struct btrfs_delayed_ref_head *
btrfs_select_ref_head(struct btrfs_trans_handle *trans)
{
struct btrfs_delayed_ref_root *delayed_refs;
struct btrfs_delayed_ref_head *head;
u64 start;
bool loop = false;
delayed_refs = &trans->transaction->delayed_refs;
again:
start = delayed_refs->run_delayed_start;
head = find_ref_head(&delayed_refs->href_root, start, 1);
if (!head && !loop) {
delayed_refs->run_delayed_start = 0;
start = 0;
loop = true;
head = find_ref_head(&delayed_refs->href_root, start, 1);
if (!head)
return NULL;
} else if (!head && loop) {
return NULL;
}
while (head->processing) {
struct rb_node *node;
node = rb_next(&head->href_node);
if (!node) {
if (loop)
return NULL;
delayed_refs->run_delayed_start = 0;
start = 0;
loop = true;
goto again;
}
head = rb_entry(node, struct btrfs_delayed_ref_head,
href_node);
}
head->processing = 1;
WARN_ON(delayed_refs->num_heads_ready == 0);
delayed_refs->num_heads_ready--;
delayed_refs->run_delayed_start = head->node.bytenr +
head->node.num_bytes;
return head;
}
/*
* helper function to update an extent delayed ref in the
* rbtree. existing and update must both have the same
* bytenr and parent
*
* This may free existing if the update cancels out whatever
* operation it was doing.
*/
static noinline void
update_existing_ref(struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_root *delayed_refs,
struct btrfs_delayed_ref_head *head,
struct btrfs_delayed_ref_node *existing,
struct btrfs_delayed_ref_node *update)
{
if (update->action != existing->action) {
/*
* this is effectively undoing either an add or a
* drop. We decrement the ref_mod, and if it goes
* down to zero we just delete the entry without
* every changing the extent allocation tree.
*/
existing->ref_mod--;
if (existing->ref_mod == 0)
drop_delayed_ref(trans, delayed_refs, head, existing);
else
WARN_ON(existing->type == BTRFS_TREE_BLOCK_REF_KEY ||
existing->type == BTRFS_SHARED_BLOCK_REF_KEY);
} else {
WARN_ON(existing->type == BTRFS_TREE_BLOCK_REF_KEY ||
existing->type == BTRFS_SHARED_BLOCK_REF_KEY);
/*
* the action on the existing ref matches
* the action on the ref we're trying to add.
* Bump the ref_mod by one so the backref that
* is eventually added/removed has the correct
* reference count
*/
existing->ref_mod += update->ref_mod;
}
}
/*
* helper function to update the accounting in the head ref
* existing and update must have the same bytenr
*/
static noinline void
update_existing_head_ref(struct btrfs_delayed_ref_node *existing,
struct btrfs_delayed_ref_node *update)
{
struct btrfs_delayed_ref_head *existing_ref;
struct btrfs_delayed_ref_head *ref;
existing_ref = btrfs_delayed_node_to_head(existing);
ref = btrfs_delayed_node_to_head(update);
BUG_ON(existing_ref->is_data != ref->is_data);
spin_lock(&existing_ref->lock);
if (ref->must_insert_reserved) {
/* if the extent was freed and then
* reallocated before the delayed ref
* entries were processed, we can end up
* with an existing head ref without
* the must_insert_reserved flag set.
* Set it again here
*/
existing_ref->must_insert_reserved = ref->must_insert_reserved;
/*
* update the num_bytes so we make sure the accounting
* is done correctly
*/
existing->num_bytes = update->num_bytes;
}
if (ref->extent_op) {
if (!existing_ref->extent_op) {
existing_ref->extent_op = ref->extent_op;
} else {
if (ref->extent_op->update_key) {
memcpy(&existing_ref->extent_op->key,
&ref->extent_op->key,
sizeof(ref->extent_op->key));
existing_ref->extent_op->update_key = 1;
}
if (ref->extent_op->update_flags) {
existing_ref->extent_op->flags_to_set |=
ref->extent_op->flags_to_set;
existing_ref->extent_op->update_flags = 1;
}
btrfs_free_delayed_extent_op(ref->extent_op);
}
}
/*
* update the reference mod on the head to reflect this new operation,
* only need the lock for this case cause we could be processing it
* currently, for refs we just added we know we're a-ok.
*/
existing->ref_mod += update->ref_mod;
spin_unlock(&existing_ref->lock);
}
/*
* helper function to actually insert a head node into the rbtree.
* this does all the dirty work in terms of maintaining the correct
* overall modification count.
*/
static noinline struct btrfs_delayed_ref_head *
add_delayed_ref_head(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_node *ref, u64 bytenr,
u64 num_bytes, int action, int is_data)
{
struct btrfs_delayed_ref_head *existing;
struct btrfs_delayed_ref_head *head_ref = NULL;
struct btrfs_delayed_ref_root *delayed_refs;
int count_mod = 1;
int must_insert_reserved = 0;
/*
* the head node stores the sum of all the mods, so dropping a ref
* should drop the sum in the head node by one.
*/
if (action == BTRFS_UPDATE_DELAYED_HEAD)
count_mod = 0;
else if (action == BTRFS_DROP_DELAYED_REF)
count_mod = -1;
/*
* BTRFS_ADD_DELAYED_EXTENT means that we need to update
* the reserved accounting when the extent is finally added, or
* if a later modification deletes the delayed ref without ever
* inserting the extent into the extent allocation tree.
* ref->must_insert_reserved is the flag used to record
* that accounting mods are required.
*
* Once we record must_insert_reserved, switch the action to
* BTRFS_ADD_DELAYED_REF because other special casing is not required.
*/
if (action == BTRFS_ADD_DELAYED_EXTENT)
must_insert_reserved = 1;
else
must_insert_reserved = 0;
delayed_refs = &trans->transaction->delayed_refs;
/* first set the basic ref node struct up */
atomic_set(&ref->refs, 1);
ref->bytenr = bytenr;
ref->num_bytes = num_bytes;
ref->ref_mod = count_mod;
ref->type = 0;
ref->action = 0;
ref->is_head = 1;
ref->in_tree = 1;
ref->seq = 0;
head_ref = btrfs_delayed_node_to_head(ref);
head_ref->must_insert_reserved = must_insert_reserved;
head_ref->is_data = is_data;
head_ref->ref_root = RB_ROOT;
head_ref->processing = 0;
spin_lock_init(&head_ref->lock);
mutex_init(&head_ref->mutex);
trace_add_delayed_ref_head(ref, head_ref, action);
existing = htree_insert(&delayed_refs->href_root,
&head_ref->href_node);
if (existing) {
update_existing_head_ref(&existing->node, ref);
/*
* we've updated the existing ref, free the newly
* allocated ref
*/
kmem_cache_free(btrfs_delayed_ref_head_cachep, head_ref);
head_ref = existing;
} else {
delayed_refs->num_heads++;
delayed_refs->num_heads_ready++;
atomic_inc(&delayed_refs->num_entries);
trans->delayed_ref_updates++;
}
return head_ref;
}
/*
* helper to insert a delayed tree ref into the rbtree.
*/
static noinline void
add_delayed_tree_ref(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_head *head_ref,
struct btrfs_delayed_ref_node *ref, u64 bytenr,
u64 num_bytes, u64 parent, u64 ref_root, int level,
int action, int no_quota)
{
struct btrfs_delayed_ref_node *existing;
struct btrfs_delayed_tree_ref *full_ref;
struct btrfs_delayed_ref_root *delayed_refs;
u64 seq = 0;
if (action == BTRFS_ADD_DELAYED_EXTENT)
action = BTRFS_ADD_DELAYED_REF;
if (is_fstree(ref_root))
seq = atomic64_read(&fs_info->tree_mod_seq);
delayed_refs = &trans->transaction->delayed_refs;
/* first set the basic ref node struct up */
atomic_set(&ref->refs, 1);
ref->bytenr = bytenr;
ref->num_bytes = num_bytes;
ref->ref_mod = 1;
ref->action = action;
ref->is_head = 0;
ref->in_tree = 1;
ref->no_quota = no_quota;
ref->seq = seq;
full_ref = btrfs_delayed_node_to_tree_ref(ref);
full_ref->parent = parent;
full_ref->root = ref_root;
if (parent)
ref->type = BTRFS_SHARED_BLOCK_REF_KEY;
else
ref->type = BTRFS_TREE_BLOCK_REF_KEY;
full_ref->level = level;
trace_add_delayed_tree_ref(ref, full_ref, action);
spin_lock(&head_ref->lock);
existing = tree_insert(&head_ref->ref_root, &ref->rb_node);
if (existing) {
update_existing_ref(trans, delayed_refs, head_ref, existing,
ref);
/*
* we've updated the existing ref, free the newly
* allocated ref
*/
kmem_cache_free(btrfs_delayed_tree_ref_cachep, full_ref);
} else {
atomic_inc(&delayed_refs->num_entries);
trans->delayed_ref_updates++;
}
spin_unlock(&head_ref->lock);
}
/*
* helper to insert a delayed data ref into the rbtree.
*/
static noinline void
add_delayed_data_ref(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
struct btrfs_delayed_ref_head *head_ref,
struct btrfs_delayed_ref_node *ref, u64 bytenr,
u64 num_bytes, u64 parent, u64 ref_root, u64 owner,
u64 offset, int action, int no_quota)
{
struct btrfs_delayed_ref_node *existing;
struct btrfs_delayed_data_ref *full_ref;
struct btrfs_delayed_ref_root *delayed_refs;
u64 seq = 0;
if (action == BTRFS_ADD_DELAYED_EXTENT)
action = BTRFS_ADD_DELAYED_REF;
delayed_refs = &trans->transaction->delayed_refs;
if (is_fstree(ref_root))
seq = atomic64_read(&fs_info->tree_mod_seq);
/* first set the basic ref node struct up */
atomic_set(&ref->refs, 1);
ref->bytenr = bytenr;
ref->num_bytes = num_bytes;
ref->ref_mod = 1;
ref->action = action;
ref->is_head = 0;
ref->in_tree = 1;
ref->no_quota = no_quota;
ref->seq = seq;
full_ref = btrfs_delayed_node_to_data_ref(ref);
full_ref->parent = parent;
full_ref->root = ref_root;
if (parent)
ref->type = BTRFS_SHARED_DATA_REF_KEY;
else
ref->type = BTRFS_EXTENT_DATA_REF_KEY;
full_ref->objectid = owner;
full_ref->offset = offset;
trace_add_delayed_data_ref(ref, full_ref, action);
spin_lock(&head_ref->lock);
existing = tree_insert(&head_ref->ref_root, &ref->rb_node);
if (existing) {
update_existing_ref(trans, delayed_refs, head_ref, existing,
ref);
/*
* we've updated the existing ref, free the newly
* allocated ref
*/
kmem_cache_free(btrfs_delayed_data_ref_cachep, full_ref);
} else {
atomic_inc(&delayed_refs->num_entries);
trans->delayed_ref_updates++;
}
spin_unlock(&head_ref->lock);
}
/*
* add a delayed tree ref. This does all of the accounting required
* to make sure the delayed ref is eventually processed before this
* transaction commits.
*/
int btrfs_add_delayed_tree_ref(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
u64 bytenr, u64 num_bytes, u64 parent,
u64 ref_root, int level, int action,
struct btrfs_delayed_extent_op *extent_op,
int no_quota)
{
struct btrfs_delayed_tree_ref *ref;
struct btrfs_delayed_ref_head *head_ref;
struct btrfs_delayed_ref_root *delayed_refs;
if (!is_fstree(ref_root) || !fs_info->quota_enabled)
no_quota = 0;
BUG_ON(extent_op && extent_op->is_data);
ref = kmem_cache_alloc(btrfs_delayed_tree_ref_cachep, GFP_NOFS);
if (!ref)
return -ENOMEM;
head_ref = kmem_cache_alloc(btrfs_delayed_ref_head_cachep, GFP_NOFS);
if (!head_ref) {
kmem_cache_free(btrfs_delayed_tree_ref_cachep, ref);
return -ENOMEM;
}
head_ref->extent_op = extent_op;
delayed_refs = &trans->transaction->delayed_refs;
spin_lock(&delayed_refs->lock);
/*
* insert both the head node and the new ref without dropping
* the spin lock
*/
head_ref = add_delayed_ref_head(fs_info, trans, &head_ref->node,
bytenr, num_bytes, action, 0);
add_delayed_tree_ref(fs_info, trans, head_ref, &ref->node, bytenr,
num_bytes, parent, ref_root, level, action,
no_quota);
spin_unlock(&delayed_refs->lock);
return 0;
}
/*
* add a delayed data ref. it's similar to btrfs_add_delayed_tree_ref.
*/
int btrfs_add_delayed_data_ref(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
u64 bytenr, u64 num_bytes,
u64 parent, u64 ref_root,
u64 owner, u64 offset, int action,
struct btrfs_delayed_extent_op *extent_op,
int no_quota)
{
struct btrfs_delayed_data_ref *ref;
struct btrfs_delayed_ref_head *head_ref;
struct btrfs_delayed_ref_root *delayed_refs;
if (!is_fstree(ref_root) || !fs_info->quota_enabled)
no_quota = 0;
BUG_ON(extent_op && !extent_op->is_data);
ref = kmem_cache_alloc(btrfs_delayed_data_ref_cachep, GFP_NOFS);
if (!ref)
return -ENOMEM;
head_ref = kmem_cache_alloc(btrfs_delayed_ref_head_cachep, GFP_NOFS);
if (!head_ref) {
kmem_cache_free(btrfs_delayed_data_ref_cachep, ref);
return -ENOMEM;
}
head_ref->extent_op = extent_op;
delayed_refs = &trans->transaction->delayed_refs;
spin_lock(&delayed_refs->lock);
/*
* insert both the head node and the new ref without dropping
* the spin lock
*/
head_ref = add_delayed_ref_head(fs_info, trans, &head_ref->node,
bytenr, num_bytes, action, 1);
add_delayed_data_ref(fs_info, trans, head_ref, &ref->node, bytenr,
num_bytes, parent, ref_root, owner, offset,
action, no_quota);
spin_unlock(&delayed_refs->lock);
return 0;
}
int btrfs_add_delayed_extent_op(struct btrfs_fs_info *fs_info,
struct btrfs_trans_handle *trans,
u64 bytenr, u64 num_bytes,
struct btrfs_delayed_extent_op *extent_op)
{
struct btrfs_delayed_ref_head *head_ref;
struct btrfs_delayed_ref_root *delayed_refs;
head_ref = kmem_cache_alloc(btrfs_delayed_ref_head_cachep, GFP_NOFS);
if (!head_ref)
return -ENOMEM;
head_ref->extent_op = extent_op;
delayed_refs = &trans->transaction->delayed_refs;
spin_lock(&delayed_refs->lock);
add_delayed_ref_head(fs_info, trans, &head_ref->node, bytenr,
num_bytes, BTRFS_UPDATE_DELAYED_HEAD,
extent_op->is_data);
spin_unlock(&delayed_refs->lock);
return 0;
}
/*
* this does a simple search for the head node for a given extent.
* It must be called with the delayed ref spinlock held, and it returns
* the head node if any where found, or NULL if not.
*/
struct btrfs_delayed_ref_head *
btrfs_find_delayed_ref_head(struct btrfs_trans_handle *trans, u64 bytenr)
{
struct btrfs_delayed_ref_root *delayed_refs;
delayed_refs = &trans->transaction->delayed_refs;
return find_ref_head(&delayed_refs->href_root, bytenr, 0);
}
void btrfs_delayed_ref_exit(void)
{
if (btrfs_delayed_ref_head_cachep)
kmem_cache_destroy(btrfs_delayed_ref_head_cachep);
if (btrfs_delayed_tree_ref_cachep)
kmem_cache_destroy(btrfs_delayed_tree_ref_cachep);
if (btrfs_delayed_data_ref_cachep)
kmem_cache_destroy(btrfs_delayed_data_ref_cachep);
if (btrfs_delayed_extent_op_cachep)
kmem_cache_destroy(btrfs_delayed_extent_op_cachep);
}
int btrfs_delayed_ref_init(void)
{
btrfs_delayed_ref_head_cachep = kmem_cache_create(
"btrfs_delayed_ref_head",
sizeof(struct btrfs_delayed_ref_head), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_delayed_ref_head_cachep)
goto fail;
btrfs_delayed_tree_ref_cachep = kmem_cache_create(
"btrfs_delayed_tree_ref",
sizeof(struct btrfs_delayed_tree_ref), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_delayed_tree_ref_cachep)
goto fail;
btrfs_delayed_data_ref_cachep = kmem_cache_create(
"btrfs_delayed_data_ref",
sizeof(struct btrfs_delayed_data_ref), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_delayed_data_ref_cachep)
goto fail;
btrfs_delayed_extent_op_cachep = kmem_cache_create(
"btrfs_delayed_extent_op",
sizeof(struct btrfs_delayed_extent_op), 0,
SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
if (!btrfs_delayed_extent_op_cachep)
goto fail;
return 0;
fail:
btrfs_delayed_ref_exit();
return -ENOMEM;
}
| gpl-2.0 |
mdeejay/virtuous-s4v-kernel | drivers/i2c/busses/i2c-sis5595.c | 1714 | 11883 | /*
Copyright (c) 1998, 1999 Frodo Looijaard <frodol@dds.nl> and
Philip Edelbrock <phil@netroedge.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.
*/
/* Note: we assume there can only be one SIS5595 with one SMBus interface */
/*
Note: all have mfr. ID 0x1039.
SUPPORTED PCI ID
5595 0008
Note: these chips contain a 0008 device which is incompatible with the
5595. We recognize these by the presence of the listed
"blacklist" PCI ID and refuse to load.
NOT SUPPORTED PCI ID BLACKLIST PCI ID
540 0008 0540
550 0008 0550
5513 0008 5511
5581 0008 5597
5582 0008 5597
5597 0008 5597
5598 0008 5597/5598
630 0008 0630
645 0008 0645
646 0008 0646
648 0008 0648
650 0008 0650
651 0008 0651
730 0008 0730
735 0008 0735
745 0008 0745
746 0008 0746
*/
/* TO DO:
* Add Block Transfers (ugly, but supported by the adapter)
* Add adapter resets
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/acpi.h>
#include <linux/io.h>
static int blacklist[] = {
PCI_DEVICE_ID_SI_540,
PCI_DEVICE_ID_SI_550,
PCI_DEVICE_ID_SI_630,
PCI_DEVICE_ID_SI_645,
PCI_DEVICE_ID_SI_646,
PCI_DEVICE_ID_SI_648,
PCI_DEVICE_ID_SI_650,
PCI_DEVICE_ID_SI_651,
PCI_DEVICE_ID_SI_730,
PCI_DEVICE_ID_SI_735,
PCI_DEVICE_ID_SI_745,
PCI_DEVICE_ID_SI_746,
PCI_DEVICE_ID_SI_5511, /* 5513 chip has the 0008 device but that ID
shows up in other chips so we use the 5511
ID for recognition */
PCI_DEVICE_ID_SI_5597,
PCI_DEVICE_ID_SI_5598,
0, /* terminates the list */
};
/* Length of ISA address segment */
#define SIS5595_EXTENT 8
/* SIS5595 SMBus registers */
#define SMB_STS_LO 0x00
#define SMB_STS_HI 0x01
#define SMB_CTL_LO 0x02
#define SMB_CTL_HI 0x03
#define SMB_ADDR 0x04
#define SMB_CMD 0x05
#define SMB_PCNT 0x06
#define SMB_CNT 0x07
#define SMB_BYTE 0x08
#define SMB_DEV 0x10
#define SMB_DB0 0x11
#define SMB_DB1 0x12
#define SMB_HAA 0x13
/* PCI Address Constants */
#define SMB_INDEX 0x38
#define SMB_DAT 0x39
#define SIS5595_ENABLE_REG 0x40
#define ACPI_BASE 0x90
/* Other settings */
#define MAX_TIMEOUT 500
/* SIS5595 constants */
#define SIS5595_QUICK 0x00
#define SIS5595_BYTE 0x02
#define SIS5595_BYTE_DATA 0x04
#define SIS5595_WORD_DATA 0x06
#define SIS5595_PROC_CALL 0x08
#define SIS5595_BLOCK_DATA 0x0A
/* insmod parameters */
/* If force_addr is set to anything different from 0, we forcibly enable
the device at the given address. */
static u16 force_addr;
module_param(force_addr, ushort, 0);
MODULE_PARM_DESC(force_addr, "Initialize the base address of the i2c controller");
static struct pci_driver sis5595_driver;
static unsigned short sis5595_base;
static struct pci_dev *sis5595_pdev;
static u8 sis5595_read(u8 reg)
{
outb(reg, sis5595_base + SMB_INDEX);
return inb(sis5595_base + SMB_DAT);
}
static void sis5595_write(u8 reg, u8 data)
{
outb(reg, sis5595_base + SMB_INDEX);
outb(data, sis5595_base + SMB_DAT);
}
static int __devinit sis5595_setup(struct pci_dev *SIS5595_dev)
{
u16 a;
u8 val;
int *i;
int retval;
/* Look for imposters */
for (i = blacklist; *i != 0; i++) {
struct pci_dev *dev;
dev = pci_get_device(PCI_VENDOR_ID_SI, *i, NULL);
if (dev) {
dev_err(&SIS5595_dev->dev, "Looked for SIS5595 but found unsupported device %.4x\n", *i);
pci_dev_put(dev);
return -ENODEV;
}
}
/* Determine the address of the SMBus areas */
pci_read_config_word(SIS5595_dev, ACPI_BASE, &sis5595_base);
if (sis5595_base == 0 && force_addr == 0) {
dev_err(&SIS5595_dev->dev, "ACPI base address uninitialized - upgrade BIOS or use force_addr=0xaddr\n");
return -ENODEV;
}
if (force_addr)
sis5595_base = force_addr & ~(SIS5595_EXTENT - 1);
dev_dbg(&SIS5595_dev->dev, "ACPI Base address: %04x\n", sis5595_base);
/* NB: We grab just the two SMBus registers here, but this may still
* interfere with ACPI :-( */
retval = acpi_check_region(sis5595_base + SMB_INDEX, 2,
sis5595_driver.name);
if (retval)
return retval;
if (!request_region(sis5595_base + SMB_INDEX, 2,
sis5595_driver.name)) {
dev_err(&SIS5595_dev->dev, "SMBus registers 0x%04x-0x%04x already in use!\n",
sis5595_base + SMB_INDEX, sis5595_base + SMB_INDEX + 1);
return -ENODEV;
}
if (force_addr) {
dev_info(&SIS5595_dev->dev, "forcing ISA address 0x%04X\n", sis5595_base);
if (pci_write_config_word(SIS5595_dev, ACPI_BASE, sis5595_base)
!= PCIBIOS_SUCCESSFUL)
goto error;
if (pci_read_config_word(SIS5595_dev, ACPI_BASE, &a)
!= PCIBIOS_SUCCESSFUL)
goto error;
if ((a & ~(SIS5595_EXTENT - 1)) != sis5595_base) {
/* doesn't work for some chips! */
dev_err(&SIS5595_dev->dev, "force address failed - not supported?\n");
goto error;
}
}
if (pci_read_config_byte(SIS5595_dev, SIS5595_ENABLE_REG, &val)
!= PCIBIOS_SUCCESSFUL)
goto error;
if ((val & 0x80) == 0) {
dev_info(&SIS5595_dev->dev, "enabling ACPI\n");
if (pci_write_config_byte(SIS5595_dev, SIS5595_ENABLE_REG, val | 0x80)
!= PCIBIOS_SUCCESSFUL)
goto error;
if (pci_read_config_byte(SIS5595_dev, SIS5595_ENABLE_REG, &val)
!= PCIBIOS_SUCCESSFUL)
goto error;
if ((val & 0x80) == 0) {
/* doesn't work for some chips? */
dev_err(&SIS5595_dev->dev, "ACPI enable failed - not supported?\n");
goto error;
}
}
/* Everything is happy */
return 0;
error:
release_region(sis5595_base + SMB_INDEX, 2);
return -ENODEV;
}
static int sis5595_transaction(struct i2c_adapter *adap)
{
int temp;
int result = 0;
int timeout = 0;
/* Make sure the SMBus host is ready to start transmitting */
temp = sis5595_read(SMB_STS_LO) + (sis5595_read(SMB_STS_HI) << 8);
if (temp != 0x00) {
dev_dbg(&adap->dev, "SMBus busy (%04x). Resetting...\n", temp);
sis5595_write(SMB_STS_LO, temp & 0xff);
sis5595_write(SMB_STS_HI, temp >> 8);
if ((temp = sis5595_read(SMB_STS_LO) + (sis5595_read(SMB_STS_HI) << 8)) != 0x00) {
dev_dbg(&adap->dev, "Failed! (%02x)\n", temp);
return -EBUSY;
} else {
dev_dbg(&adap->dev, "Successful!\n");
}
}
/* start the transaction by setting bit 4 */
sis5595_write(SMB_CTL_LO, sis5595_read(SMB_CTL_LO) | 0x10);
/* We will always wait for a fraction of a second! */
do {
msleep(1);
temp = sis5595_read(SMB_STS_LO);
} while (!(temp & 0x40) && (timeout++ < MAX_TIMEOUT));
/* If the SMBus is still busy, we give up */
if (timeout > MAX_TIMEOUT) {
dev_dbg(&adap->dev, "SMBus Timeout!\n");
result = -ETIMEDOUT;
}
if (temp & 0x10) {
dev_dbg(&adap->dev, "Error: Failed bus transaction\n");
result = -ENXIO;
}
if (temp & 0x20) {
dev_err(&adap->dev, "Bus collision! SMBus may be locked until "
"next hard reset (or not...)\n");
/* Clock stops and slave is stuck in mid-transmission */
result = -EIO;
}
temp = sis5595_read(SMB_STS_LO) + (sis5595_read(SMB_STS_HI) << 8);
if (temp != 0x00) {
sis5595_write(SMB_STS_LO, temp & 0xff);
sis5595_write(SMB_STS_HI, temp >> 8);
}
temp = sis5595_read(SMB_STS_LO) + (sis5595_read(SMB_STS_HI) << 8);
if (temp != 0x00)
dev_dbg(&adap->dev, "Failed reset at end of transaction (%02x)\n", temp);
return result;
}
/* Return negative errno on error. */
static s32 sis5595_access(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size, union i2c_smbus_data *data)
{
int status;
switch (size) {
case I2C_SMBUS_QUICK:
sis5595_write(SMB_ADDR, ((addr & 0x7f) << 1) | (read_write & 0x01));
size = SIS5595_QUICK;
break;
case I2C_SMBUS_BYTE:
sis5595_write(SMB_ADDR, ((addr & 0x7f) << 1) | (read_write & 0x01));
if (read_write == I2C_SMBUS_WRITE)
sis5595_write(SMB_CMD, command);
size = SIS5595_BYTE;
break;
case I2C_SMBUS_BYTE_DATA:
sis5595_write(SMB_ADDR, ((addr & 0x7f) << 1) | (read_write & 0x01));
sis5595_write(SMB_CMD, command);
if (read_write == I2C_SMBUS_WRITE)
sis5595_write(SMB_BYTE, data->byte);
size = SIS5595_BYTE_DATA;
break;
case I2C_SMBUS_PROC_CALL:
case I2C_SMBUS_WORD_DATA:
sis5595_write(SMB_ADDR, ((addr & 0x7f) << 1) | (read_write & 0x01));
sis5595_write(SMB_CMD, command);
if (read_write == I2C_SMBUS_WRITE) {
sis5595_write(SMB_BYTE, data->word & 0xff);
sis5595_write(SMB_BYTE + 1,
(data->word & 0xff00) >> 8);
}
size = (size == I2C_SMBUS_PROC_CALL) ? SIS5595_PROC_CALL : SIS5595_WORD_DATA;
break;
default:
dev_warn(&adap->dev, "Unsupported transaction %d\n", size);
return -EOPNOTSUPP;
}
sis5595_write(SMB_CTL_LO, ((size & 0x0E)));
status = sis5595_transaction(adap);
if (status)
return status;
if ((size != SIS5595_PROC_CALL) &&
((read_write == I2C_SMBUS_WRITE) || (size == SIS5595_QUICK)))
return 0;
switch (size) {
case SIS5595_BYTE:
case SIS5595_BYTE_DATA:
data->byte = sis5595_read(SMB_BYTE);
break;
case SIS5595_WORD_DATA:
case SIS5595_PROC_CALL:
data->word = sis5595_read(SMB_BYTE) + (sis5595_read(SMB_BYTE + 1) << 8);
break;
}
return 0;
}
static u32 sis5595_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
I2C_FUNC_SMBUS_PROC_CALL;
}
static const struct i2c_algorithm smbus_algorithm = {
.smbus_xfer = sis5595_access,
.functionality = sis5595_func,
};
static struct i2c_adapter sis5595_adapter = {
.owner = THIS_MODULE,
.class = I2C_CLASS_HWMON | I2C_CLASS_SPD,
.algo = &smbus_algorithm,
};
static const struct pci_device_id sis5595_ids[] __devinitconst = {
{ PCI_DEVICE(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_503) },
{ 0, }
};
MODULE_DEVICE_TABLE (pci, sis5595_ids);
static int __devinit sis5595_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
int err;
if (sis5595_setup(dev)) {
dev_err(&dev->dev, "SIS5595 not detected, module not inserted.\n");
return -ENODEV;
}
/* set up the sysfs linkage to our parent device */
sis5595_adapter.dev.parent = &dev->dev;
snprintf(sis5595_adapter.name, sizeof(sis5595_adapter.name),
"SMBus SIS5595 adapter at %04x", sis5595_base + SMB_INDEX);
err = i2c_add_adapter(&sis5595_adapter);
if (err) {
release_region(sis5595_base + SMB_INDEX, 2);
return err;
}
/* Always return failure here. This is to allow other drivers to bind
* to this pci device. We don't really want to have control over the
* pci device, we only wanted to read as few register values from it.
*/
sis5595_pdev = pci_dev_get(dev);
return -ENODEV;
}
static struct pci_driver sis5595_driver = {
.name = "sis5595_smbus",
.id_table = sis5595_ids,
.probe = sis5595_probe,
};
static int __init i2c_sis5595_init(void)
{
return pci_register_driver(&sis5595_driver);
}
static void __exit i2c_sis5595_exit(void)
{
pci_unregister_driver(&sis5595_driver);
if (sis5595_pdev) {
i2c_del_adapter(&sis5595_adapter);
release_region(sis5595_base + SMB_INDEX, 2);
pci_dev_put(sis5595_pdev);
sis5595_pdev = NULL;
}
}
MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>");
MODULE_DESCRIPTION("SIS5595 SMBus driver");
MODULE_LICENSE("GPL");
module_init(i2c_sis5595_init);
module_exit(i2c_sis5595_exit);
| gpl-2.0 |
Ca1ne/Underworld-Sense-Kernel | arch/arm/mach-clps711x/irq.c | 1714 | 3218 | /*
* linux/arch/arm/mach-clps711x/irq.c
*
* Copyright (C) 2000 Deep Blue Solutions Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/list.h>
#include <linux/io.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/hardware/clps7111.h>
static void int1_mask(unsigned int irq)
{
u32 intmr1;
intmr1 = clps_readl(INTMR1);
intmr1 &= ~(1 << irq);
clps_writel(intmr1, INTMR1);
}
static void int1_ack(unsigned int irq)
{
u32 intmr1;
intmr1 = clps_readl(INTMR1);
intmr1 &= ~(1 << irq);
clps_writel(intmr1, INTMR1);
switch (irq) {
case IRQ_CSINT: clps_writel(0, COEOI); break;
case IRQ_TC1OI: clps_writel(0, TC1EOI); break;
case IRQ_TC2OI: clps_writel(0, TC2EOI); break;
case IRQ_RTCMI: clps_writel(0, RTCEOI); break;
case IRQ_TINT: clps_writel(0, TEOI); break;
case IRQ_UMSINT: clps_writel(0, UMSEOI); break;
}
}
static void int1_unmask(unsigned int irq)
{
u32 intmr1;
intmr1 = clps_readl(INTMR1);
intmr1 |= 1 << irq;
clps_writel(intmr1, INTMR1);
}
static struct irq_chip int1_chip = {
.ack = int1_ack,
.mask = int1_mask,
.unmask = int1_unmask,
};
static void int2_mask(unsigned int irq)
{
u32 intmr2;
intmr2 = clps_readl(INTMR2);
intmr2 &= ~(1 << (irq - 16));
clps_writel(intmr2, INTMR2);
}
static void int2_ack(unsigned int irq)
{
u32 intmr2;
intmr2 = clps_readl(INTMR2);
intmr2 &= ~(1 << (irq - 16));
clps_writel(intmr2, INTMR2);
switch (irq) {
case IRQ_KBDINT: clps_writel(0, KBDEOI); break;
}
}
static void int2_unmask(unsigned int irq)
{
u32 intmr2;
intmr2 = clps_readl(INTMR2);
intmr2 |= 1 << (irq - 16);
clps_writel(intmr2, INTMR2);
}
static struct irq_chip int2_chip = {
.ack = int2_ack,
.mask = int2_mask,
.unmask = int2_unmask,
};
void __init clps711x_init_irq(void)
{
unsigned int i;
for (i = 0; i < NR_IRQS; i++) {
if (INT1_IRQS & (1 << i)) {
set_irq_handler(i, handle_level_irq);
set_irq_chip(i, &int1_chip);
set_irq_flags(i, IRQF_VALID | IRQF_PROBE);
}
if (INT2_IRQS & (1 << i)) {
set_irq_handler(i, handle_level_irq);
set_irq_chip(i, &int2_chip);
set_irq_flags(i, IRQF_VALID | IRQF_PROBE);
}
}
/*
* Disable interrupts
*/
clps_writel(0, INTMR1);
clps_writel(0, INTMR2);
/*
* Clear down any pending interrupts
*/
clps_writel(0, COEOI);
clps_writel(0, TC1EOI);
clps_writel(0, TC2EOI);
clps_writel(0, RTCEOI);
clps_writel(0, TEOI);
clps_writel(0, UMSEOI);
clps_writel(0, SYNCIO);
clps_writel(0, KBDEOI);
}
| gpl-2.0 |
Redmi-dev/android_kernel_xiaomi_msm8226 | arch/arm/mach-msm/memory_topology.c | 1970 | 4573 | /* Copyright (c) 2010-2013, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <asm/setup.h>
#include <asm/errno.h>
#include <asm/sizes.h>
#include <asm/pgtable.h>
#include <linux/mutex.h>
#include <linux/memory.h>
#include <mach/msm_memtypes.h>
#include <mach/socinfo.h>
#include <mach/msm_smem.h>
#if defined(CONFIG_ARCH_MSM8960)
#include "rpm_resources.h"
#endif
struct smem_ram_ptn {
char name[16];
unsigned start;
unsigned size;
/* RAM Partition attribute: READ_ONLY, READWRITE etc. */
unsigned attr;
/* RAM Partition category: EBI0, EBI1, IRAM, IMEM */
unsigned category;
/* RAM Partition domain: APPS, MODEM, APPS & MODEM (SHARED) etc. */
unsigned domain;
/* RAM Partition type: system, bootloader, appsboot, apps etc. */
unsigned type;
/* reserved for future expansion without changing version number */
unsigned reserved2, reserved3, reserved4, reserved5;
} __attribute__ ((__packed__));
struct smem_ram_ptable {
#define _SMEM_RAM_PTABLE_MAGIC_1 0x9DA5E0A8
#define _SMEM_RAM_PTABLE_MAGIC_2 0xAF9EC4E2
unsigned magic[2];
unsigned version;
unsigned reserved1;
unsigned len;
struct smem_ram_ptn parts[32];
unsigned buf;
} __attribute__ ((__packed__));
static struct mem_region_t {
u64 start;
u64 size;
/* reserved for future use */
u64 num_partitions;
int state;
} mem_regions[MAX_NR_REGIONS];
static struct mutex mem_regions_mutex;
static unsigned int nr_mem_regions;
static int mem_regions_mask;
enum {
STATE_POWER_DOWN = 0x0,
STATE_ACTIVE = 0x2,
STATE_DEFAULT = STATE_ACTIVE
};
static int default_mask = ~0x0;
/* Return the number of chipselects populated with a memory bank */
/* This is 7x30 only and will be re-implemented in the future */
#if defined(CONFIG_ARCH_MSM7X30)
unsigned int get_num_populated_chipselects()
{
/* Currently, Linux cannot determine the memory toplogy of a target */
/* This is a kludge until all this info is figured out from smem */
/* There is atleast one chipselect populated for hosting the 1st bank */
unsigned int num_chipselects = 1;
int i;
for (i = 0; i < meminfo.nr_banks; i++) {
struct membank *bank = &meminfo.bank[i];
if (bank->start == EBI1_PHYS_OFFSET)
num_chipselects++;
}
return num_chipselects;
}
#endif
unsigned int get_num_memory_banks(void)
{
return nr_mem_regions;
}
unsigned int get_memory_bank_size(unsigned int id)
{
BUG_ON(id >= nr_mem_regions);
return mem_regions[id].size;
}
unsigned int get_memory_bank_start(unsigned int id)
{
BUG_ON(id >= nr_mem_regions);
return mem_regions[id].start;
}
int __init meminfo_init(unsigned int type, unsigned int min_bank_size)
{
unsigned int i, j;
unsigned long bank_size;
unsigned long bank_start;
unsigned long region_size;
struct smem_ram_ptable *ram_ptable;
/* physical memory banks */
unsigned int nr_mem_banks = 0;
/* logical memory regions for dmm */
nr_mem_regions = 0;
ram_ptable = smem_alloc(SMEM_USABLE_RAM_PARTITION_TABLE,
sizeof(struct smem_ram_ptable));
if (!ram_ptable) {
pr_err("Could not read ram partition table\n");
return -EINVAL;
}
pr_info("meminfo_init: smem ram ptable found: ver: %d len: %d\n",
ram_ptable->version, ram_ptable->len);
for (i = 0; i < ram_ptable->len; i++) {
/* A bank is valid only if is greater than min_bank_size. If
* non-valid memory (e.g. modem memory) became greater than
* min_bank_size, there is currently no way to differentiate.
*/
if (ram_ptable->parts[i].type == type &&
ram_ptable->parts[i].size >= min_bank_size) {
bank_start = ram_ptable->parts[i].start;
bank_size = ram_ptable->parts[i].size;
region_size = bank_size / NR_REGIONS_PER_BANK;
for (j = 0; j < NR_REGIONS_PER_BANK; j++) {
mem_regions[nr_mem_regions].start =
bank_start;
mem_regions[nr_mem_regions].size =
region_size;
mem_regions[nr_mem_regions].state =
STATE_DEFAULT;
bank_start += region_size;
nr_mem_regions++;
}
nr_mem_banks++;
}
}
mutex_init(&mem_regions_mutex);
mem_regions_mask = default_mask;
pr_info("Found %d memory banks grouped into %d memory regions\n",
nr_mem_banks, nr_mem_regions);
return 0;
}
| gpl-2.0 |
BlackPole/vuplus-kernel | drivers/video/s3c-fb.c | 2226 | 49146 | /* linux/drivers/video/s3c-fb.c
*
* Copyright 2008 Openmoko Inc.
* Copyright 2008-2010 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
* http://armlinux.simtec.co.uk/
*
* Samsung SoC Framebuffer driver
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software FoundatIon.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/clk.h>
#include <linux/fb.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <linux/interrupt.h>
#include <linux/pm_runtime.h>
#include <mach/map.h>
#include <plat/regs-fb-v4.h>
#include <plat/fb.h>
/* This driver will export a number of framebuffer interfaces depending
* on the configuration passed in via the platform data. Each fb instance
* maps to a hardware window. Currently there is no support for runtime
* setting of the alpha-blending functions that each window has, so only
* window 0 is actually useful.
*
* Window 0 is treated specially, it is used for the basis of the LCD
* output timings and as the control for the output power-down state.
*/
/* note, the previous use of <mach/regs-fb.h> to get platform specific data
* has been replaced by using the platform device name to pick the correct
* configuration data for the system.
*/
#ifdef CONFIG_FB_S3C_DEBUG_REGWRITE
#undef writel
#define writel(v, r) do { \
printk(KERN_DEBUG "%s: %08x => %p\n", __func__, (unsigned int)v, r); \
__raw_writel(v, r); } while (0)
#endif /* FB_S3C_DEBUG_REGWRITE */
/* irq_flags bits */
#define S3C_FB_VSYNC_IRQ_EN 0
#define VSYNC_TIMEOUT_MSEC 50
struct s3c_fb;
#define VALID_BPP(x) (1 << ((x) - 1))
#define OSD_BASE(win, variant) ((variant).osd + ((win) * (variant).osd_stride))
#define VIDOSD_A(win, variant) (OSD_BASE(win, variant) + 0x00)
#define VIDOSD_B(win, variant) (OSD_BASE(win, variant) + 0x04)
#define VIDOSD_C(win, variant) (OSD_BASE(win, variant) + 0x08)
#define VIDOSD_D(win, variant) (OSD_BASE(win, variant) + 0x0C)
/**
* struct s3c_fb_variant - fb variant information
* @is_2443: Set if S3C2443/S3C2416 style hardware.
* @nr_windows: The number of windows.
* @vidtcon: The base for the VIDTCONx registers
* @wincon: The base for the WINxCON registers.
* @winmap: The base for the WINxMAP registers.
* @keycon: The abse for the WxKEYCON registers.
* @buf_start: Offset of buffer start registers.
* @buf_size: Offset of buffer size registers.
* @buf_end: Offset of buffer end registers.
* @osd: The base for the OSD registers.
* @palette: Address of palette memory, or 0 if none.
* @has_prtcon: Set if has PRTCON register.
* @has_shadowcon: Set if has SHADOWCON register.
*/
struct s3c_fb_variant {
unsigned int is_2443:1;
unsigned short nr_windows;
unsigned short vidtcon;
unsigned short wincon;
unsigned short winmap;
unsigned short keycon;
unsigned short buf_start;
unsigned short buf_end;
unsigned short buf_size;
unsigned short osd;
unsigned short osd_stride;
unsigned short palette[S3C_FB_MAX_WIN];
unsigned int has_prtcon:1;
unsigned int has_shadowcon:1;
};
/**
* struct s3c_fb_win_variant
* @has_osd_c: Set if has OSD C register.
* @has_osd_d: Set if has OSD D register.
* @has_osd_alpha: Set if can change alpha transparency for a window.
* @palette_sz: Size of palette in entries.
* @palette_16bpp: Set if palette is 16bits wide.
* @osd_size_off: If != 0, supports setting up OSD for a window; the appropriate
* register is located at the given offset from OSD_BASE.
* @valid_bpp: 1 bit per BPP setting to show valid bits-per-pixel.
*
* valid_bpp bit x is set if (x+1)BPP is supported.
*/
struct s3c_fb_win_variant {
unsigned int has_osd_c:1;
unsigned int has_osd_d:1;
unsigned int has_osd_alpha:1;
unsigned int palette_16bpp:1;
unsigned short osd_size_off;
unsigned short palette_sz;
u32 valid_bpp;
};
/**
* struct s3c_fb_driverdata - per-device type driver data for init time.
* @variant: The variant information for this driver.
* @win: The window information for each window.
*/
struct s3c_fb_driverdata {
struct s3c_fb_variant variant;
struct s3c_fb_win_variant *win[S3C_FB_MAX_WIN];
};
/**
* struct s3c_fb_palette - palette information
* @r: Red bitfield.
* @g: Green bitfield.
* @b: Blue bitfield.
* @a: Alpha bitfield.
*/
struct s3c_fb_palette {
struct fb_bitfield r;
struct fb_bitfield g;
struct fb_bitfield b;
struct fb_bitfield a;
};
/**
* struct s3c_fb_win - per window private data for each framebuffer.
* @windata: The platform data supplied for the window configuration.
* @parent: The hardware that this window is part of.
* @fbinfo: Pointer pack to the framebuffer info for this window.
* @varint: The variant information for this window.
* @palette_buffer: Buffer/cache to hold palette entries.
* @pseudo_palette: For use in TRUECOLOUR modes for entries 0..15/
* @index: The window number of this window.
* @palette: The bitfields for changing r/g/b into a hardware palette entry.
*/
struct s3c_fb_win {
struct s3c_fb_pd_win *windata;
struct s3c_fb *parent;
struct fb_info *fbinfo;
struct s3c_fb_palette palette;
struct s3c_fb_win_variant variant;
u32 *palette_buffer;
u32 pseudo_palette[16];
unsigned int index;
};
/**
* struct s3c_fb_vsync - vsync information
* @wait: a queue for processes waiting for vsync
* @count: vsync interrupt count
*/
struct s3c_fb_vsync {
wait_queue_head_t wait;
unsigned int count;
};
/**
* struct s3c_fb - overall hardware state of the hardware
* @slock: The spinlock protection for this data sturcture.
* @dev: The device that we bound to, for printing, etc.
* @regs_res: The resource we claimed for the IO registers.
* @bus_clk: The clk (hclk) feeding our interface and possibly pixclk.
* @regs: The mapped hardware registers.
* @variant: Variant information for this hardware.
* @enabled: A bitmask of enabled hardware windows.
* @pdata: The platform configuration data passed with the device.
* @windows: The hardware windows that have been claimed.
* @irq_no: IRQ line number
* @irq_flags: irq flags
* @vsync_info: VSYNC-related information (count, queues...)
*/
struct s3c_fb {
spinlock_t slock;
struct device *dev;
struct resource *regs_res;
struct clk *bus_clk;
void __iomem *regs;
struct s3c_fb_variant variant;
unsigned char enabled;
struct s3c_fb_platdata *pdata;
struct s3c_fb_win *windows[S3C_FB_MAX_WIN];
int irq_no;
unsigned long irq_flags;
struct s3c_fb_vsync vsync_info;
};
/**
* s3c_fb_validate_win_bpp - validate the bits-per-pixel for this mode.
* @win: The device window.
* @bpp: The bit depth.
*/
static bool s3c_fb_validate_win_bpp(struct s3c_fb_win *win, unsigned int bpp)
{
return win->variant.valid_bpp & VALID_BPP(bpp);
}
/**
* s3c_fb_check_var() - framebuffer layer request to verify a given mode.
* @var: The screen information to verify.
* @info: The framebuffer device.
*
* Framebuffer layer call to verify the given information and allow us to
* update various information depending on the hardware capabilities.
*/
static int s3c_fb_check_var(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct s3c_fb_win *win = info->par;
struct s3c_fb *sfb = win->parent;
dev_dbg(sfb->dev, "checking parameters\n");
var->xres_virtual = max(var->xres_virtual, var->xres);
var->yres_virtual = max(var->yres_virtual, var->yres);
if (!s3c_fb_validate_win_bpp(win, var->bits_per_pixel)) {
dev_dbg(sfb->dev, "win %d: unsupported bpp %d\n",
win->index, var->bits_per_pixel);
return -EINVAL;
}
/* always ensure these are zero, for drop through cases below */
var->transp.offset = 0;
var->transp.length = 0;
switch (var->bits_per_pixel) {
case 1:
case 2:
case 4:
case 8:
if (sfb->variant.palette[win->index] != 0) {
/* non palletised, A:1,R:2,G:3,B:2 mode */
var->red.offset = 4;
var->green.offset = 2;
var->blue.offset = 0;
var->red.length = 5;
var->green.length = 3;
var->blue.length = 2;
var->transp.offset = 7;
var->transp.length = 1;
} else {
var->red.offset = 0;
var->red.length = var->bits_per_pixel;
var->green = var->red;
var->blue = var->red;
}
break;
case 19:
/* 666 with one bit alpha/transparency */
var->transp.offset = 18;
var->transp.length = 1;
case 18:
var->bits_per_pixel = 32;
/* 666 format */
var->red.offset = 12;
var->green.offset = 6;
var->blue.offset = 0;
var->red.length = 6;
var->green.length = 6;
var->blue.length = 6;
break;
case 16:
/* 16 bpp, 565 format */
var->red.offset = 11;
var->green.offset = 5;
var->blue.offset = 0;
var->red.length = 5;
var->green.length = 6;
var->blue.length = 5;
break;
case 32:
case 28:
case 25:
var->transp.length = var->bits_per_pixel - 24;
var->transp.offset = 24;
/* drop through */
case 24:
/* our 24bpp is unpacked, so 32bpp */
var->bits_per_pixel = 32;
var->red.offset = 16;
var->red.length = 8;
var->green.offset = 8;
var->green.length = 8;
var->blue.offset = 0;
var->blue.length = 8;
break;
default:
dev_err(sfb->dev, "invalid bpp\n");
}
dev_dbg(sfb->dev, "%s: verified parameters\n", __func__);
return 0;
}
/**
* s3c_fb_calc_pixclk() - calculate the divider to create the pixel clock.
* @sfb: The hardware state.
* @pixclock: The pixel clock wanted, in picoseconds.
*
* Given the specified pixel clock, work out the necessary divider to get
* close to the output frequency.
*/
static int s3c_fb_calc_pixclk(struct s3c_fb *sfb, unsigned int pixclk)
{
unsigned long clk = clk_get_rate(sfb->bus_clk);
unsigned long long tmp;
unsigned int result;
tmp = (unsigned long long)clk;
tmp *= pixclk;
do_div(tmp, 1000000000UL);
result = (unsigned int)tmp / 1000;
dev_dbg(sfb->dev, "pixclk=%u, clk=%lu, div=%d (%lu)\n",
pixclk, clk, result, clk / result);
return result;
}
/**
* s3c_fb_align_word() - align pixel count to word boundary
* @bpp: The number of bits per pixel
* @pix: The value to be aligned.
*
* Align the given pixel count so that it will start on an 32bit word
* boundary.
*/
static int s3c_fb_align_word(unsigned int bpp, unsigned int pix)
{
int pix_per_word;
if (bpp > 16)
return pix;
pix_per_word = (8 * 32) / bpp;
return ALIGN(pix, pix_per_word);
}
/**
* vidosd_set_size() - set OSD size for a window
*
* @win: the window to set OSD size for
* @size: OSD size register value
*/
static void vidosd_set_size(struct s3c_fb_win *win, u32 size)
{
struct s3c_fb *sfb = win->parent;
/* OSD can be set up if osd_size_off != 0 for this window */
if (win->variant.osd_size_off)
writel(size, sfb->regs + OSD_BASE(win->index, sfb->variant)
+ win->variant.osd_size_off);
}
/**
* vidosd_set_alpha() - set alpha transparency for a window
*
* @win: the window to set OSD size for
* @alpha: alpha register value
*/
static void vidosd_set_alpha(struct s3c_fb_win *win, u32 alpha)
{
struct s3c_fb *sfb = win->parent;
if (win->variant.has_osd_alpha)
writel(alpha, sfb->regs + VIDOSD_C(win->index, sfb->variant));
}
/**
* shadow_protect_win() - disable updating values from shadow registers at vsync
*
* @win: window to protect registers for
* @protect: 1 to protect (disable updates)
*/
static void shadow_protect_win(struct s3c_fb_win *win, bool protect)
{
struct s3c_fb *sfb = win->parent;
u32 reg;
if (protect) {
if (sfb->variant.has_prtcon) {
writel(PRTCON_PROTECT, sfb->regs + PRTCON);
} else if (sfb->variant.has_shadowcon) {
reg = readl(sfb->regs + SHADOWCON);
writel(reg | SHADOWCON_WINx_PROTECT(win->index),
sfb->regs + SHADOWCON);
}
} else {
if (sfb->variant.has_prtcon) {
writel(0, sfb->regs + PRTCON);
} else if (sfb->variant.has_shadowcon) {
reg = readl(sfb->regs + SHADOWCON);
writel(reg & ~SHADOWCON_WINx_PROTECT(win->index),
sfb->regs + SHADOWCON);
}
}
}
/**
* s3c_fb_set_par() - framebuffer request to set new framebuffer state.
* @info: The framebuffer to change.
*
* Framebuffer layer request to set a new mode for the specified framebuffer
*/
static int s3c_fb_set_par(struct fb_info *info)
{
struct fb_var_screeninfo *var = &info->var;
struct s3c_fb_win *win = info->par;
struct s3c_fb *sfb = win->parent;
void __iomem *regs = sfb->regs;
void __iomem *buf = regs;
int win_no = win->index;
u32 alpha = 0;
u32 data;
u32 pagewidth;
int clkdiv;
dev_dbg(sfb->dev, "setting framebuffer parameters\n");
shadow_protect_win(win, 1);
switch (var->bits_per_pixel) {
case 32:
case 24:
case 16:
case 12:
info->fix.visual = FB_VISUAL_TRUECOLOR;
break;
case 8:
if (win->variant.palette_sz >= 256)
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
else
info->fix.visual = FB_VISUAL_TRUECOLOR;
break;
case 1:
info->fix.visual = FB_VISUAL_MONO01;
break;
default:
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
break;
}
info->fix.line_length = (var->xres_virtual * var->bits_per_pixel) / 8;
info->fix.xpanstep = info->var.xres_virtual > info->var.xres ? 1 : 0;
info->fix.ypanstep = info->var.yres_virtual > info->var.yres ? 1 : 0;
/* disable the window whilst we update it */
writel(0, regs + WINCON(win_no));
/* use platform specified window as the basis for the lcd timings */
if (win_no == sfb->pdata->default_win) {
clkdiv = s3c_fb_calc_pixclk(sfb, var->pixclock);
data = sfb->pdata->vidcon0;
data &= ~(VIDCON0_CLKVAL_F_MASK | VIDCON0_CLKDIR);
if (clkdiv > 1)
data |= VIDCON0_CLKVAL_F(clkdiv-1) | VIDCON0_CLKDIR;
else
data &= ~VIDCON0_CLKDIR; /* 1:1 clock */
/* write the timing data to the panel */
if (sfb->variant.is_2443)
data |= (1 << 5);
data |= VIDCON0_ENVID | VIDCON0_ENVID_F;
writel(data, regs + VIDCON0);
data = VIDTCON0_VBPD(var->upper_margin - 1) |
VIDTCON0_VFPD(var->lower_margin - 1) |
VIDTCON0_VSPW(var->vsync_len - 1);
writel(data, regs + sfb->variant.vidtcon);
data = VIDTCON1_HBPD(var->left_margin - 1) |
VIDTCON1_HFPD(var->right_margin - 1) |
VIDTCON1_HSPW(var->hsync_len - 1);
/* VIDTCON1 */
writel(data, regs + sfb->variant.vidtcon + 4);
data = VIDTCON2_LINEVAL(var->yres - 1) |
VIDTCON2_HOZVAL(var->xres - 1);
writel(data, regs + sfb->variant.vidtcon + 8);
}
/* write the buffer address */
/* start and end registers stride is 8 */
buf = regs + win_no * 8;
writel(info->fix.smem_start, buf + sfb->variant.buf_start);
data = info->fix.smem_start + info->fix.line_length * var->yres;
writel(data, buf + sfb->variant.buf_end);
pagewidth = (var->xres * var->bits_per_pixel) >> 3;
data = VIDW_BUF_SIZE_OFFSET(info->fix.line_length - pagewidth) |
VIDW_BUF_SIZE_PAGEWIDTH(pagewidth);
writel(data, regs + sfb->variant.buf_size + (win_no * 4));
/* write 'OSD' registers to control position of framebuffer */
data = VIDOSDxA_TOPLEFT_X(0) | VIDOSDxA_TOPLEFT_Y(0);
writel(data, regs + VIDOSD_A(win_no, sfb->variant));
data = VIDOSDxB_BOTRIGHT_X(s3c_fb_align_word(var->bits_per_pixel,
var->xres - 1)) |
VIDOSDxB_BOTRIGHT_Y(var->yres - 1);
writel(data, regs + VIDOSD_B(win_no, sfb->variant));
data = var->xres * var->yres;
alpha = VIDISD14C_ALPHA1_R(0xf) |
VIDISD14C_ALPHA1_G(0xf) |
VIDISD14C_ALPHA1_B(0xf);
vidosd_set_alpha(win, alpha);
vidosd_set_size(win, data);
/* Enable DMA channel for this window */
if (sfb->variant.has_shadowcon) {
data = readl(sfb->regs + SHADOWCON);
data |= SHADOWCON_CHx_ENABLE(win_no);
writel(data, sfb->regs + SHADOWCON);
}
data = WINCONx_ENWIN;
/* note, since we have to round up the bits-per-pixel, we end up
* relying on the bitfield information for r/g/b/a to work out
* exactly which mode of operation is intended. */
switch (var->bits_per_pixel) {
case 1:
data |= WINCON0_BPPMODE_1BPP;
data |= WINCONx_BITSWP;
data |= WINCONx_BURSTLEN_4WORD;
break;
case 2:
data |= WINCON0_BPPMODE_2BPP;
data |= WINCONx_BITSWP;
data |= WINCONx_BURSTLEN_8WORD;
break;
case 4:
data |= WINCON0_BPPMODE_4BPP;
data |= WINCONx_BITSWP;
data |= WINCONx_BURSTLEN_8WORD;
break;
case 8:
if (var->transp.length != 0)
data |= WINCON1_BPPMODE_8BPP_1232;
else
data |= WINCON0_BPPMODE_8BPP_PALETTE;
data |= WINCONx_BURSTLEN_8WORD;
data |= WINCONx_BYTSWP;
break;
case 16:
if (var->transp.length != 0)
data |= WINCON1_BPPMODE_16BPP_A1555;
else
data |= WINCON0_BPPMODE_16BPP_565;
data |= WINCONx_HAWSWP;
data |= WINCONx_BURSTLEN_16WORD;
break;
case 24:
case 32:
if (var->red.length == 6) {
if (var->transp.length != 0)
data |= WINCON1_BPPMODE_19BPP_A1666;
else
data |= WINCON1_BPPMODE_18BPP_666;
} else if (var->transp.length == 1)
data |= WINCON1_BPPMODE_25BPP_A1888
| WINCON1_BLD_PIX;
else if (var->transp.length == 4)
data |= WINCON1_BPPMODE_28BPP_A4888
| WINCON1_BLD_PIX | WINCON1_ALPHA_SEL;
else
data |= WINCON0_BPPMODE_24BPP_888;
data |= WINCONx_WSWP;
data |= WINCONx_BURSTLEN_16WORD;
break;
}
/* Enable the colour keying for the window below this one */
if (win_no > 0) {
u32 keycon0_data = 0, keycon1_data = 0;
void __iomem *keycon = regs + sfb->variant.keycon;
keycon0_data = ~(WxKEYCON0_KEYBL_EN |
WxKEYCON0_KEYEN_F |
WxKEYCON0_DIRCON) | WxKEYCON0_COMPKEY(0);
keycon1_data = WxKEYCON1_COLVAL(0xffffff);
keycon += (win_no - 1) * 8;
writel(keycon0_data, keycon + WKEYCON0);
writel(keycon1_data, keycon + WKEYCON1);
}
writel(data, regs + sfb->variant.wincon + (win_no * 4));
writel(0x0, regs + sfb->variant.winmap + (win_no * 4));
shadow_protect_win(win, 0);
return 0;
}
/**
* s3c_fb_update_palette() - set or schedule a palette update.
* @sfb: The hardware information.
* @win: The window being updated.
* @reg: The palette index being changed.
* @value: The computed palette value.
*
* Change the value of a palette register, either by directly writing to
* the palette (this requires the palette RAM to be disconnected from the
* hardware whilst this is in progress) or schedule the update for later.
*
* At the moment, since we have no VSYNC interrupt support, we simply set
* the palette entry directly.
*/
static void s3c_fb_update_palette(struct s3c_fb *sfb,
struct s3c_fb_win *win,
unsigned int reg,
u32 value)
{
void __iomem *palreg;
u32 palcon;
palreg = sfb->regs + sfb->variant.palette[win->index];
dev_dbg(sfb->dev, "%s: win %d, reg %d (%p): %08x\n",
__func__, win->index, reg, palreg, value);
win->palette_buffer[reg] = value;
palcon = readl(sfb->regs + WPALCON);
writel(palcon | WPALCON_PAL_UPDATE, sfb->regs + WPALCON);
if (win->variant.palette_16bpp)
writew(value, palreg + (reg * 2));
else
writel(value, palreg + (reg * 4));
writel(palcon, sfb->regs + WPALCON);
}
static inline unsigned int chan_to_field(unsigned int chan,
struct fb_bitfield *bf)
{
chan &= 0xffff;
chan >>= 16 - bf->length;
return chan << bf->offset;
}
/**
* s3c_fb_setcolreg() - framebuffer layer request to change palette.
* @regno: The palette index to change.
* @red: The red field for the palette data.
* @green: The green field for the palette data.
* @blue: The blue field for the palette data.
* @trans: The transparency (alpha) field for the palette data.
* @info: The framebuffer being changed.
*/
static int s3c_fb_setcolreg(unsigned regno,
unsigned red, unsigned green, unsigned blue,
unsigned transp, struct fb_info *info)
{
struct s3c_fb_win *win = info->par;
struct s3c_fb *sfb = win->parent;
unsigned int val;
dev_dbg(sfb->dev, "%s: win %d: %d => rgb=%d/%d/%d\n",
__func__, win->index, regno, red, green, blue);
switch (info->fix.visual) {
case FB_VISUAL_TRUECOLOR:
/* true-colour, use pseudo-palette */
if (regno < 16) {
u32 *pal = info->pseudo_palette;
val = chan_to_field(red, &info->var.red);
val |= chan_to_field(green, &info->var.green);
val |= chan_to_field(blue, &info->var.blue);
pal[regno] = val;
}
break;
case FB_VISUAL_PSEUDOCOLOR:
if (regno < win->variant.palette_sz) {
val = chan_to_field(red, &win->palette.r);
val |= chan_to_field(green, &win->palette.g);
val |= chan_to_field(blue, &win->palette.b);
s3c_fb_update_palette(sfb, win, regno, val);
}
break;
default:
return 1; /* unknown type */
}
return 0;
}
/**
* s3c_fb_enable() - Set the state of the main LCD output
* @sfb: The main framebuffer state.
* @enable: The state to set.
*/
static void s3c_fb_enable(struct s3c_fb *sfb, int enable)
{
u32 vidcon0 = readl(sfb->regs + VIDCON0);
if (enable)
vidcon0 |= VIDCON0_ENVID | VIDCON0_ENVID_F;
else {
/* see the note in the framebuffer datasheet about
* why you cannot take both of these bits down at the
* same time. */
if (!(vidcon0 & VIDCON0_ENVID))
return;
vidcon0 |= VIDCON0_ENVID;
vidcon0 &= ~VIDCON0_ENVID_F;
}
writel(vidcon0, sfb->regs + VIDCON0);
}
/**
* s3c_fb_blank() - blank or unblank the given window
* @blank_mode: The blank state from FB_BLANK_*
* @info: The framebuffer to blank.
*
* Framebuffer layer request to change the power state.
*/
static int s3c_fb_blank(int blank_mode, struct fb_info *info)
{
struct s3c_fb_win *win = info->par;
struct s3c_fb *sfb = win->parent;
unsigned int index = win->index;
u32 wincon;
dev_dbg(sfb->dev, "blank mode %d\n", blank_mode);
wincon = readl(sfb->regs + sfb->variant.wincon + (index * 4));
switch (blank_mode) {
case FB_BLANK_POWERDOWN:
wincon &= ~WINCONx_ENWIN;
sfb->enabled &= ~(1 << index);
/* fall through to FB_BLANK_NORMAL */
case FB_BLANK_NORMAL:
/* disable the DMA and display 0x0 (black) */
writel(WINxMAP_MAP | WINxMAP_MAP_COLOUR(0x0),
sfb->regs + sfb->variant.winmap + (index * 4));
break;
case FB_BLANK_UNBLANK:
writel(0x0, sfb->regs + sfb->variant.winmap + (index * 4));
wincon |= WINCONx_ENWIN;
sfb->enabled |= (1 << index);
break;
case FB_BLANK_VSYNC_SUSPEND:
case FB_BLANK_HSYNC_SUSPEND:
default:
return 1;
}
writel(wincon, sfb->regs + sfb->variant.wincon + (index * 4));
/* Check the enabled state to see if we need to be running the
* main LCD interface, as if there are no active windows then
* it is highly likely that we also do not need to output
* anything.
*/
/* We could do something like the following code, but the current
* system of using framebuffer events means that we cannot make
* the distinction between just window 0 being inactive and all
* the windows being down.
*
* s3c_fb_enable(sfb, sfb->enabled ? 1 : 0);
*/
/* we're stuck with this until we can do something about overriding
* the power control using the blanking event for a single fb.
*/
if (index == sfb->pdata->default_win)
s3c_fb_enable(sfb, blank_mode != FB_BLANK_POWERDOWN ? 1 : 0);
return 0;
}
/**
* s3c_fb_pan_display() - Pan the display.
*
* Note that the offsets can be written to the device at any time, as their
* values are latched at each vsync automatically. This also means that only
* the last call to this function will have any effect on next vsync, but
* there is no need to sleep waiting for it to prevent tearing.
*
* @var: The screen information to verify.
* @info: The framebuffer device.
*/
static int s3c_fb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct s3c_fb_win *win = info->par;
struct s3c_fb *sfb = win->parent;
void __iomem *buf = sfb->regs + win->index * 8;
unsigned int start_boff, end_boff;
/* Offset in bytes to the start of the displayed area */
start_boff = var->yoffset * info->fix.line_length;
/* X offset depends on the current bpp */
if (info->var.bits_per_pixel >= 8) {
start_boff += var->xoffset * (info->var.bits_per_pixel >> 3);
} else {
switch (info->var.bits_per_pixel) {
case 4:
start_boff += var->xoffset >> 1;
break;
case 2:
start_boff += var->xoffset >> 2;
break;
case 1:
start_boff += var->xoffset >> 3;
break;
default:
dev_err(sfb->dev, "invalid bpp\n");
return -EINVAL;
}
}
/* Offset in bytes to the end of the displayed area */
end_boff = start_boff + var->yres * info->fix.line_length;
/* Temporarily turn off per-vsync update from shadow registers until
* both start and end addresses are updated to prevent corruption */
shadow_protect_win(win, 1);
writel(info->fix.smem_start + start_boff, buf + sfb->variant.buf_start);
writel(info->fix.smem_start + end_boff, buf + sfb->variant.buf_end);
shadow_protect_win(win, 0);
return 0;
}
/**
* s3c_fb_enable_irq() - enable framebuffer interrupts
* @sfb: main hardware state
*/
static void s3c_fb_enable_irq(struct s3c_fb *sfb)
{
void __iomem *regs = sfb->regs;
u32 irq_ctrl_reg;
if (!test_and_set_bit(S3C_FB_VSYNC_IRQ_EN, &sfb->irq_flags)) {
/* IRQ disabled, enable it */
irq_ctrl_reg = readl(regs + VIDINTCON0);
irq_ctrl_reg |= VIDINTCON0_INT_ENABLE;
irq_ctrl_reg |= VIDINTCON0_INT_FRAME;
irq_ctrl_reg &= ~VIDINTCON0_FRAMESEL0_MASK;
irq_ctrl_reg |= VIDINTCON0_FRAMESEL0_VSYNC;
irq_ctrl_reg &= ~VIDINTCON0_FRAMESEL1_MASK;
irq_ctrl_reg |= VIDINTCON0_FRAMESEL1_NONE;
writel(irq_ctrl_reg, regs + VIDINTCON0);
}
}
/**
* s3c_fb_disable_irq() - disable framebuffer interrupts
* @sfb: main hardware state
*/
static void s3c_fb_disable_irq(struct s3c_fb *sfb)
{
void __iomem *regs = sfb->regs;
u32 irq_ctrl_reg;
if (test_and_clear_bit(S3C_FB_VSYNC_IRQ_EN, &sfb->irq_flags)) {
/* IRQ enabled, disable it */
irq_ctrl_reg = readl(regs + VIDINTCON0);
irq_ctrl_reg &= ~VIDINTCON0_INT_FRAME;
irq_ctrl_reg &= ~VIDINTCON0_INT_ENABLE;
writel(irq_ctrl_reg, regs + VIDINTCON0);
}
}
static irqreturn_t s3c_fb_irq(int irq, void *dev_id)
{
struct s3c_fb *sfb = dev_id;
void __iomem *regs = sfb->regs;
u32 irq_sts_reg;
spin_lock(&sfb->slock);
irq_sts_reg = readl(regs + VIDINTCON1);
if (irq_sts_reg & VIDINTCON1_INT_FRAME) {
/* VSYNC interrupt, accept it */
writel(VIDINTCON1_INT_FRAME, regs + VIDINTCON1);
sfb->vsync_info.count++;
wake_up_interruptible(&sfb->vsync_info.wait);
}
/* We only support waiting for VSYNC for now, so it's safe
* to always disable irqs here.
*/
s3c_fb_disable_irq(sfb);
spin_unlock(&sfb->slock);
return IRQ_HANDLED;
}
/**
* s3c_fb_wait_for_vsync() - sleep until next VSYNC interrupt or timeout
* @sfb: main hardware state
* @crtc: head index.
*/
static int s3c_fb_wait_for_vsync(struct s3c_fb *sfb, u32 crtc)
{
unsigned long count;
int ret;
if (crtc != 0)
return -ENODEV;
count = sfb->vsync_info.count;
s3c_fb_enable_irq(sfb);
ret = wait_event_interruptible_timeout(sfb->vsync_info.wait,
count != sfb->vsync_info.count,
msecs_to_jiffies(VSYNC_TIMEOUT_MSEC));
if (ret == 0)
return -ETIMEDOUT;
return 0;
}
static int s3c_fb_ioctl(struct fb_info *info, unsigned int cmd,
unsigned long arg)
{
struct s3c_fb_win *win = info->par;
struct s3c_fb *sfb = win->parent;
int ret;
u32 crtc;
switch (cmd) {
case FBIO_WAITFORVSYNC:
if (get_user(crtc, (u32 __user *)arg)) {
ret = -EFAULT;
break;
}
ret = s3c_fb_wait_for_vsync(sfb, crtc);
break;
default:
ret = -ENOTTY;
}
return ret;
}
static int s3c_fb_open(struct fb_info *info, int user)
{
struct s3c_fb_win *win = info->par;
struct s3c_fb *sfb = win->parent;
pm_runtime_get_sync(sfb->dev);
return 0;
}
static int s3c_fb_release(struct fb_info *info, int user)
{
struct s3c_fb_win *win = info->par;
struct s3c_fb *sfb = win->parent;
pm_runtime_put_sync(sfb->dev);
return 0;
}
static struct fb_ops s3c_fb_ops = {
.owner = THIS_MODULE,
.fb_open = s3c_fb_open,
.fb_release = s3c_fb_release,
.fb_check_var = s3c_fb_check_var,
.fb_set_par = s3c_fb_set_par,
.fb_blank = s3c_fb_blank,
.fb_setcolreg = s3c_fb_setcolreg,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_pan_display = s3c_fb_pan_display,
.fb_ioctl = s3c_fb_ioctl,
};
/**
* s3c_fb_missing_pixclock() - calculates pixel clock
* @mode: The video mode to change.
*
* Calculate the pixel clock when none has been given through platform data.
*/
static void __devinit s3c_fb_missing_pixclock(struct fb_videomode *mode)
{
u64 pixclk = 1000000000000ULL;
u32 div;
div = mode->left_margin + mode->hsync_len + mode->right_margin +
mode->xres;
div *= mode->upper_margin + mode->vsync_len + mode->lower_margin +
mode->yres;
div *= mode->refresh ? : 60;
do_div(pixclk, div);
mode->pixclock = pixclk;
}
/**
* s3c_fb_alloc_memory() - allocate display memory for framebuffer window
* @sfb: The base resources for the hardware.
* @win: The window to initialise memory for.
*
* Allocate memory for the given framebuffer.
*/
static int __devinit s3c_fb_alloc_memory(struct s3c_fb *sfb,
struct s3c_fb_win *win)
{
struct s3c_fb_pd_win *windata = win->windata;
unsigned int real_size, virt_size, size;
struct fb_info *fbi = win->fbinfo;
dma_addr_t map_dma;
dev_dbg(sfb->dev, "allocating memory for display\n");
real_size = windata->win_mode.xres * windata->win_mode.yres;
virt_size = windata->virtual_x * windata->virtual_y;
dev_dbg(sfb->dev, "real_size=%u (%u.%u), virt_size=%u (%u.%u)\n",
real_size, windata->win_mode.xres, windata->win_mode.yres,
virt_size, windata->virtual_x, windata->virtual_y);
size = (real_size > virt_size) ? real_size : virt_size;
size *= (windata->max_bpp > 16) ? 32 : windata->max_bpp;
size /= 8;
fbi->fix.smem_len = size;
size = PAGE_ALIGN(size);
dev_dbg(sfb->dev, "want %u bytes for window\n", size);
fbi->screen_base = dma_alloc_writecombine(sfb->dev, size,
&map_dma, GFP_KERNEL);
if (!fbi->screen_base)
return -ENOMEM;
dev_dbg(sfb->dev, "mapped %x to %p\n",
(unsigned int)map_dma, fbi->screen_base);
memset(fbi->screen_base, 0x0, size);
fbi->fix.smem_start = map_dma;
return 0;
}
/**
* s3c_fb_free_memory() - free the display memory for the given window
* @sfb: The base resources for the hardware.
* @win: The window to free the display memory for.
*
* Free the display memory allocated by s3c_fb_alloc_memory().
*/
static void s3c_fb_free_memory(struct s3c_fb *sfb, struct s3c_fb_win *win)
{
struct fb_info *fbi = win->fbinfo;
if (fbi->screen_base)
dma_free_writecombine(sfb->dev, PAGE_ALIGN(fbi->fix.smem_len),
fbi->screen_base, fbi->fix.smem_start);
}
/**
* s3c_fb_release_win() - release resources for a framebuffer window.
* @win: The window to cleanup the resources for.
*
* Release the resources that where claimed for the hardware window,
* such as the framebuffer instance and any memory claimed for it.
*/
static void s3c_fb_release_win(struct s3c_fb *sfb, struct s3c_fb_win *win)
{
u32 data;
if (win->fbinfo) {
if (sfb->variant.has_shadowcon) {
data = readl(sfb->regs + SHADOWCON);
data &= ~SHADOWCON_CHx_ENABLE(win->index);
data &= ~SHADOWCON_CHx_LOCAL_ENABLE(win->index);
writel(data, sfb->regs + SHADOWCON);
}
unregister_framebuffer(win->fbinfo);
if (win->fbinfo->cmap.len)
fb_dealloc_cmap(&win->fbinfo->cmap);
s3c_fb_free_memory(sfb, win);
framebuffer_release(win->fbinfo);
}
}
/**
* s3c_fb_probe_win() - register an hardware window
* @sfb: The base resources for the hardware
* @variant: The variant information for this window.
* @res: Pointer to where to place the resultant window.
*
* Allocate and do the basic initialisation for one of the hardware's graphics
* windows.
*/
static int __devinit s3c_fb_probe_win(struct s3c_fb *sfb, unsigned int win_no,
struct s3c_fb_win_variant *variant,
struct s3c_fb_win **res)
{
struct fb_var_screeninfo *var;
struct fb_videomode *initmode;
struct s3c_fb_pd_win *windata;
struct s3c_fb_win *win;
struct fb_info *fbinfo;
int palette_size;
int ret;
dev_dbg(sfb->dev, "probing window %d, variant %p\n", win_no, variant);
init_waitqueue_head(&sfb->vsync_info.wait);
palette_size = variant->palette_sz * 4;
fbinfo = framebuffer_alloc(sizeof(struct s3c_fb_win) +
palette_size * sizeof(u32), sfb->dev);
if (!fbinfo) {
dev_err(sfb->dev, "failed to allocate framebuffer\n");
return -ENOENT;
}
windata = sfb->pdata->win[win_no];
initmode = &windata->win_mode;
WARN_ON(windata->max_bpp == 0);
WARN_ON(windata->win_mode.xres == 0);
WARN_ON(windata->win_mode.yres == 0);
win = fbinfo->par;
*res = win;
var = &fbinfo->var;
win->variant = *variant;
win->fbinfo = fbinfo;
win->parent = sfb;
win->windata = windata;
win->index = win_no;
win->palette_buffer = (u32 *)(win + 1);
ret = s3c_fb_alloc_memory(sfb, win);
if (ret) {
dev_err(sfb->dev, "failed to allocate display memory\n");
return ret;
}
/* setup the r/b/g positions for the window's palette */
if (win->variant.palette_16bpp) {
/* Set RGB 5:6:5 as default */
win->palette.r.offset = 11;
win->palette.r.length = 5;
win->palette.g.offset = 5;
win->palette.g.length = 6;
win->palette.b.offset = 0;
win->palette.b.length = 5;
} else {
/* Set 8bpp or 8bpp and 1bit alpha */
win->palette.r.offset = 16;
win->palette.r.length = 8;
win->palette.g.offset = 8;
win->palette.g.length = 8;
win->palette.b.offset = 0;
win->palette.b.length = 8;
}
/* setup the initial video mode from the window */
fb_videomode_to_var(&fbinfo->var, initmode);
fbinfo->fix.type = FB_TYPE_PACKED_PIXELS;
fbinfo->fix.accel = FB_ACCEL_NONE;
fbinfo->var.activate = FB_ACTIVATE_NOW;
fbinfo->var.vmode = FB_VMODE_NONINTERLACED;
fbinfo->var.bits_per_pixel = windata->default_bpp;
fbinfo->fbops = &s3c_fb_ops;
fbinfo->flags = FBINFO_FLAG_DEFAULT;
fbinfo->pseudo_palette = &win->pseudo_palette;
/* prepare to actually start the framebuffer */
ret = s3c_fb_check_var(&fbinfo->var, fbinfo);
if (ret < 0) {
dev_err(sfb->dev, "check_var failed on initial video params\n");
return ret;
}
/* create initial colour map */
ret = fb_alloc_cmap(&fbinfo->cmap, win->variant.palette_sz, 1);
if (ret == 0)
fb_set_cmap(&fbinfo->cmap, fbinfo);
else
dev_err(sfb->dev, "failed to allocate fb cmap\n");
s3c_fb_set_par(fbinfo);
dev_dbg(sfb->dev, "about to register framebuffer\n");
/* run the check_var and set_par on our configuration. */
ret = register_framebuffer(fbinfo);
if (ret < 0) {
dev_err(sfb->dev, "failed to register framebuffer\n");
return ret;
}
dev_info(sfb->dev, "window %d: fb %s\n", win_no, fbinfo->fix.id);
return 0;
}
/**
* s3c_fb_clear_win() - clear hardware window registers.
* @sfb: The base resources for the hardware.
* @win: The window to process.
*
* Reset the specific window registers to a known state.
*/
static void s3c_fb_clear_win(struct s3c_fb *sfb, int win)
{
void __iomem *regs = sfb->regs;
u32 reg;
writel(0, regs + sfb->variant.wincon + (win * 4));
writel(0, regs + VIDOSD_A(win, sfb->variant));
writel(0, regs + VIDOSD_B(win, sfb->variant));
writel(0, regs + VIDOSD_C(win, sfb->variant));
reg = readl(regs + SHADOWCON);
writel(reg & ~SHADOWCON_WINx_PROTECT(win), regs + SHADOWCON);
}
static int __devinit s3c_fb_probe(struct platform_device *pdev)
{
const struct platform_device_id *platid;
struct s3c_fb_driverdata *fbdrv;
struct device *dev = &pdev->dev;
struct s3c_fb_platdata *pd;
struct s3c_fb *sfb;
struct resource *res;
int win;
int ret = 0;
platid = platform_get_device_id(pdev);
fbdrv = (struct s3c_fb_driverdata *)platid->driver_data;
if (fbdrv->variant.nr_windows > S3C_FB_MAX_WIN) {
dev_err(dev, "too many windows, cannot attach\n");
return -EINVAL;
}
pd = pdev->dev.platform_data;
if (!pd) {
dev_err(dev, "no platform data specified\n");
return -EINVAL;
}
sfb = kzalloc(sizeof(struct s3c_fb), GFP_KERNEL);
if (!sfb) {
dev_err(dev, "no memory for framebuffers\n");
return -ENOMEM;
}
dev_dbg(dev, "allocate new framebuffer %p\n", sfb);
sfb->dev = dev;
sfb->pdata = pd;
sfb->variant = fbdrv->variant;
spin_lock_init(&sfb->slock);
sfb->bus_clk = clk_get(dev, "lcd");
if (IS_ERR(sfb->bus_clk)) {
dev_err(dev, "failed to get bus clock\n");
ret = PTR_ERR(sfb->bus_clk);
goto err_sfb;
}
clk_enable(sfb->bus_clk);
pm_runtime_enable(sfb->dev);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(dev, "failed to find registers\n");
ret = -ENOENT;
goto err_clk;
}
sfb->regs_res = request_mem_region(res->start, resource_size(res),
dev_name(dev));
if (!sfb->regs_res) {
dev_err(dev, "failed to claim register region\n");
ret = -ENOENT;
goto err_clk;
}
sfb->regs = ioremap(res->start, resource_size(res));
if (!sfb->regs) {
dev_err(dev, "failed to map registers\n");
ret = -ENXIO;
goto err_req_region;
}
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res) {
dev_err(dev, "failed to acquire irq resource\n");
ret = -ENOENT;
goto err_ioremap;
}
sfb->irq_no = res->start;
ret = request_irq(sfb->irq_no, s3c_fb_irq,
0, "s3c_fb", sfb);
if (ret) {
dev_err(dev, "irq request failed\n");
goto err_ioremap;
}
dev_dbg(dev, "got resources (regs %p), probing windows\n", sfb->regs);
platform_set_drvdata(pdev, sfb);
pm_runtime_get_sync(sfb->dev);
/* setup gpio and output polarity controls */
pd->setup_gpio();
writel(pd->vidcon1, sfb->regs + VIDCON1);
/* zero all windows before we do anything */
for (win = 0; win < fbdrv->variant.nr_windows; win++)
s3c_fb_clear_win(sfb, win);
/* initialise colour key controls */
for (win = 0; win < (fbdrv->variant.nr_windows - 1); win++) {
void __iomem *regs = sfb->regs + sfb->variant.keycon;
regs += (win * 8);
writel(0xffffff, regs + WKEYCON0);
writel(0xffffff, regs + WKEYCON1);
}
/* we have the register setup, start allocating framebuffers */
for (win = 0; win < fbdrv->variant.nr_windows; win++) {
if (!pd->win[win])
continue;
if (!pd->win[win]->win_mode.pixclock)
s3c_fb_missing_pixclock(&pd->win[win]->win_mode);
ret = s3c_fb_probe_win(sfb, win, fbdrv->win[win],
&sfb->windows[win]);
if (ret < 0) {
dev_err(dev, "failed to create window %d\n", win);
for (; win >= 0; win--)
s3c_fb_release_win(sfb, sfb->windows[win]);
goto err_irq;
}
}
platform_set_drvdata(pdev, sfb);
pm_runtime_put_sync(sfb->dev);
return 0;
err_irq:
free_irq(sfb->irq_no, sfb);
err_ioremap:
iounmap(sfb->regs);
err_req_region:
release_mem_region(sfb->regs_res->start, resource_size(sfb->regs_res));
err_clk:
clk_disable(sfb->bus_clk);
clk_put(sfb->bus_clk);
err_sfb:
kfree(sfb);
return ret;
}
/**
* s3c_fb_remove() - Cleanup on module finalisation
* @pdev: The platform device we are bound to.
*
* Shutdown and then release all the resources that the driver allocated
* on initialisation.
*/
static int __devexit s3c_fb_remove(struct platform_device *pdev)
{
struct s3c_fb *sfb = platform_get_drvdata(pdev);
int win;
pm_runtime_get_sync(sfb->dev);
for (win = 0; win < S3C_FB_MAX_WIN; win++)
if (sfb->windows[win])
s3c_fb_release_win(sfb, sfb->windows[win]);
free_irq(sfb->irq_no, sfb);
iounmap(sfb->regs);
clk_disable(sfb->bus_clk);
clk_put(sfb->bus_clk);
release_mem_region(sfb->regs_res->start, resource_size(sfb->regs_res));
pm_runtime_put_sync(sfb->dev);
pm_runtime_disable(sfb->dev);
kfree(sfb);
return 0;
}
#ifdef CONFIG_PM
static int s3c_fb_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct s3c_fb *sfb = platform_get_drvdata(pdev);
struct s3c_fb_win *win;
int win_no;
for (win_no = S3C_FB_MAX_WIN - 1; win_no >= 0; win_no--) {
win = sfb->windows[win_no];
if (!win)
continue;
/* use the blank function to push into power-down */
s3c_fb_blank(FB_BLANK_POWERDOWN, win->fbinfo);
}
clk_disable(sfb->bus_clk);
return 0;
}
static int s3c_fb_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct s3c_fb *sfb = platform_get_drvdata(pdev);
struct s3c_fb_platdata *pd = sfb->pdata;
struct s3c_fb_win *win;
int win_no;
clk_enable(sfb->bus_clk);
/* setup gpio and output polarity controls */
pd->setup_gpio();
writel(pd->vidcon1, sfb->regs + VIDCON1);
/* zero all windows before we do anything */
for (win_no = 0; win_no < sfb->variant.nr_windows; win_no++)
s3c_fb_clear_win(sfb, win_no);
for (win_no = 0; win_no < sfb->variant.nr_windows - 1; win_no++) {
void __iomem *regs = sfb->regs + sfb->variant.keycon;
regs += (win_no * 8);
writel(0xffffff, regs + WKEYCON0);
writel(0xffffff, regs + WKEYCON1);
}
/* restore framebuffers */
for (win_no = 0; win_no < S3C_FB_MAX_WIN; win_no++) {
win = sfb->windows[win_no];
if (!win)
continue;
dev_dbg(&pdev->dev, "resuming window %d\n", win_no);
s3c_fb_set_par(win->fbinfo);
}
return 0;
}
static int s3c_fb_runtime_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct s3c_fb *sfb = platform_get_drvdata(pdev);
struct s3c_fb_win *win;
int win_no;
for (win_no = S3C_FB_MAX_WIN - 1; win_no >= 0; win_no--) {
win = sfb->windows[win_no];
if (!win)
continue;
/* use the blank function to push into power-down */
s3c_fb_blank(FB_BLANK_POWERDOWN, win->fbinfo);
}
clk_disable(sfb->bus_clk);
return 0;
}
static int s3c_fb_runtime_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct s3c_fb *sfb = platform_get_drvdata(pdev);
struct s3c_fb_platdata *pd = sfb->pdata;
struct s3c_fb_win *win;
int win_no;
clk_enable(sfb->bus_clk);
/* setup gpio and output polarity controls */
pd->setup_gpio();
writel(pd->vidcon1, sfb->regs + VIDCON1);
/* zero all windows before we do anything */
for (win_no = 0; win_no < sfb->variant.nr_windows; win_no++)
s3c_fb_clear_win(sfb, win_no);
for (win_no = 0; win_no < sfb->variant.nr_windows - 1; win_no++) {
void __iomem *regs = sfb->regs + sfb->variant.keycon;
regs += (win_no * 8);
writel(0xffffff, regs + WKEYCON0);
writel(0xffffff, regs + WKEYCON1);
}
/* restore framebuffers */
for (win_no = 0; win_no < S3C_FB_MAX_WIN; win_no++) {
win = sfb->windows[win_no];
if (!win)
continue;
dev_dbg(&pdev->dev, "resuming window %d\n", win_no);
s3c_fb_set_par(win->fbinfo);
}
return 0;
}
#else
#define s3c_fb_suspend NULL
#define s3c_fb_resume NULL
#define s3c_fb_runtime_suspend NULL
#define s3c_fb_runtime_resume NULL
#endif
#define VALID_BPP124 (VALID_BPP(1) | VALID_BPP(2) | VALID_BPP(4))
#define VALID_BPP1248 (VALID_BPP124 | VALID_BPP(8))
static struct s3c_fb_win_variant s3c_fb_data_64xx_wins[] = {
[0] = {
.has_osd_c = 1,
.osd_size_off = 0x8,
.palette_sz = 256,
.valid_bpp = (VALID_BPP1248 | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(24)),
},
[1] = {
.has_osd_c = 1,
.has_osd_d = 1,
.osd_size_off = 0xc,
.has_osd_alpha = 1,
.palette_sz = 256,
.valid_bpp = (VALID_BPP1248 | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(19) |
VALID_BPP(24) | VALID_BPP(25) |
VALID_BPP(28)),
},
[2] = {
.has_osd_c = 1,
.has_osd_d = 1,
.osd_size_off = 0xc,
.has_osd_alpha = 1,
.palette_sz = 16,
.palette_16bpp = 1,
.valid_bpp = (VALID_BPP1248 | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(19) |
VALID_BPP(24) | VALID_BPP(25) |
VALID_BPP(28)),
},
[3] = {
.has_osd_c = 1,
.has_osd_alpha = 1,
.palette_sz = 16,
.palette_16bpp = 1,
.valid_bpp = (VALID_BPP124 | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(19) |
VALID_BPP(24) | VALID_BPP(25) |
VALID_BPP(28)),
},
[4] = {
.has_osd_c = 1,
.has_osd_alpha = 1,
.palette_sz = 4,
.palette_16bpp = 1,
.valid_bpp = (VALID_BPP(1) | VALID_BPP(2) |
VALID_BPP(16) | VALID_BPP(18) |
VALID_BPP(19) | VALID_BPP(24) |
VALID_BPP(25) | VALID_BPP(28)),
},
};
static struct s3c_fb_win_variant s3c_fb_data_s5p_wins[] = {
[0] = {
.has_osd_c = 1,
.osd_size_off = 0x8,
.palette_sz = 256,
.valid_bpp = (VALID_BPP1248 | VALID_BPP(13) |
VALID_BPP(15) | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(19) |
VALID_BPP(24) | VALID_BPP(25) |
VALID_BPP(32)),
},
[1] = {
.has_osd_c = 1,
.has_osd_d = 1,
.osd_size_off = 0xc,
.has_osd_alpha = 1,
.palette_sz = 256,
.valid_bpp = (VALID_BPP1248 | VALID_BPP(13) |
VALID_BPP(15) | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(19) |
VALID_BPP(24) | VALID_BPP(25) |
VALID_BPP(32)),
},
[2] = {
.has_osd_c = 1,
.has_osd_d = 1,
.osd_size_off = 0xc,
.has_osd_alpha = 1,
.palette_sz = 256,
.valid_bpp = (VALID_BPP1248 | VALID_BPP(13) |
VALID_BPP(15) | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(19) |
VALID_BPP(24) | VALID_BPP(25) |
VALID_BPP(32)),
},
[3] = {
.has_osd_c = 1,
.has_osd_alpha = 1,
.palette_sz = 256,
.valid_bpp = (VALID_BPP1248 | VALID_BPP(13) |
VALID_BPP(15) | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(19) |
VALID_BPP(24) | VALID_BPP(25) |
VALID_BPP(32)),
},
[4] = {
.has_osd_c = 1,
.has_osd_alpha = 1,
.palette_sz = 256,
.valid_bpp = (VALID_BPP1248 | VALID_BPP(13) |
VALID_BPP(15) | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(19) |
VALID_BPP(24) | VALID_BPP(25) |
VALID_BPP(32)),
},
};
static struct s3c_fb_driverdata s3c_fb_data_64xx = {
.variant = {
.nr_windows = 5,
.vidtcon = VIDTCON0,
.wincon = WINCON(0),
.winmap = WINxMAP(0),
.keycon = WKEYCON,
.osd = VIDOSD_BASE,
.osd_stride = 16,
.buf_start = VIDW_BUF_START(0),
.buf_size = VIDW_BUF_SIZE(0),
.buf_end = VIDW_BUF_END(0),
.palette = {
[0] = 0x400,
[1] = 0x800,
[2] = 0x300,
[3] = 0x320,
[4] = 0x340,
},
.has_prtcon = 1,
},
.win[0] = &s3c_fb_data_64xx_wins[0],
.win[1] = &s3c_fb_data_64xx_wins[1],
.win[2] = &s3c_fb_data_64xx_wins[2],
.win[3] = &s3c_fb_data_64xx_wins[3],
.win[4] = &s3c_fb_data_64xx_wins[4],
};
static struct s3c_fb_driverdata s3c_fb_data_s5pc100 = {
.variant = {
.nr_windows = 5,
.vidtcon = VIDTCON0,
.wincon = WINCON(0),
.winmap = WINxMAP(0),
.keycon = WKEYCON,
.osd = VIDOSD_BASE,
.osd_stride = 16,
.buf_start = VIDW_BUF_START(0),
.buf_size = VIDW_BUF_SIZE(0),
.buf_end = VIDW_BUF_END(0),
.palette = {
[0] = 0x2400,
[1] = 0x2800,
[2] = 0x2c00,
[3] = 0x3000,
[4] = 0x3400,
},
.has_prtcon = 1,
},
.win[0] = &s3c_fb_data_s5p_wins[0],
.win[1] = &s3c_fb_data_s5p_wins[1],
.win[2] = &s3c_fb_data_s5p_wins[2],
.win[3] = &s3c_fb_data_s5p_wins[3],
.win[4] = &s3c_fb_data_s5p_wins[4],
};
static struct s3c_fb_driverdata s3c_fb_data_s5pv210 = {
.variant = {
.nr_windows = 5,
.vidtcon = VIDTCON0,
.wincon = WINCON(0),
.winmap = WINxMAP(0),
.keycon = WKEYCON,
.osd = VIDOSD_BASE,
.osd_stride = 16,
.buf_start = VIDW_BUF_START(0),
.buf_size = VIDW_BUF_SIZE(0),
.buf_end = VIDW_BUF_END(0),
.palette = {
[0] = 0x2400,
[1] = 0x2800,
[2] = 0x2c00,
[3] = 0x3000,
[4] = 0x3400,
},
.has_shadowcon = 1,
},
.win[0] = &s3c_fb_data_s5p_wins[0],
.win[1] = &s3c_fb_data_s5p_wins[1],
.win[2] = &s3c_fb_data_s5p_wins[2],
.win[3] = &s3c_fb_data_s5p_wins[3],
.win[4] = &s3c_fb_data_s5p_wins[4],
};
/* S3C2443/S3C2416 style hardware */
static struct s3c_fb_driverdata s3c_fb_data_s3c2443 = {
.variant = {
.nr_windows = 2,
.is_2443 = 1,
.vidtcon = 0x08,
.wincon = 0x14,
.winmap = 0xd0,
.keycon = 0xb0,
.osd = 0x28,
.osd_stride = 12,
.buf_start = 0x64,
.buf_size = 0x94,
.buf_end = 0x7c,
.palette = {
[0] = 0x400,
[1] = 0x800,
},
},
.win[0] = &(struct s3c_fb_win_variant) {
.palette_sz = 256,
.valid_bpp = VALID_BPP1248 | VALID_BPP(16) | VALID_BPP(24),
},
.win[1] = &(struct s3c_fb_win_variant) {
.has_osd_c = 1,
.has_osd_alpha = 1,
.palette_sz = 256,
.valid_bpp = (VALID_BPP1248 | VALID_BPP(16) |
VALID_BPP(18) | VALID_BPP(19) |
VALID_BPP(24) | VALID_BPP(25) |
VALID_BPP(28)),
},
};
static struct platform_device_id s3c_fb_driver_ids[] = {
{
.name = "s3c-fb",
.driver_data = (unsigned long)&s3c_fb_data_64xx,
}, {
.name = "s5pc100-fb",
.driver_data = (unsigned long)&s3c_fb_data_s5pc100,
}, {
.name = "s5pv210-fb",
.driver_data = (unsigned long)&s3c_fb_data_s5pv210,
}, {
.name = "s3c2443-fb",
.driver_data = (unsigned long)&s3c_fb_data_s3c2443,
},
{},
};
MODULE_DEVICE_TABLE(platform, s3c_fb_driver_ids);
static const struct dev_pm_ops s3cfb_pm_ops = {
.suspend = s3c_fb_suspend,
.resume = s3c_fb_resume,
.runtime_suspend = s3c_fb_runtime_suspend,
.runtime_resume = s3c_fb_runtime_resume,
};
static struct platform_driver s3c_fb_driver = {
.probe = s3c_fb_probe,
.remove = __devexit_p(s3c_fb_remove),
.id_table = s3c_fb_driver_ids,
.driver = {
.name = "s3c-fb",
.owner = THIS_MODULE,
.pm = &s3cfb_pm_ops,
},
};
static int __init s3c_fb_init(void)
{
return platform_driver_register(&s3c_fb_driver);
}
static void __exit s3c_fb_cleanup(void)
{
platform_driver_unregister(&s3c_fb_driver);
}
module_init(s3c_fb_init);
module_exit(s3c_fb_cleanup);
MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
MODULE_DESCRIPTION("Samsung S3C SoC Framebuffer driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:s3c-fb");
| gpl-2.0 |
MoKee/android_kernel_htc_enrc2b | arch/ia64/mm/init.c | 2738 | 19701 | /*
* Initialize MMU support.
*
* Copyright (C) 1998-2003 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/efi.h>
#include <linux/elf.h>
#include <linux/mm.h>
#include <linux/mmzone.h>
#include <linux/module.h>
#include <linux/personality.h>
#include <linux/reboot.h>
#include <linux/slab.h>
#include <linux/swap.h>
#include <linux/proc_fs.h>
#include <linux/bitops.h>
#include <linux/kexec.h>
#include <asm/dma.h>
#include <asm/io.h>
#include <asm/machvec.h>
#include <asm/numa.h>
#include <asm/patch.h>
#include <asm/pgalloc.h>
#include <asm/sal.h>
#include <asm/sections.h>
#include <asm/system.h>
#include <asm/tlb.h>
#include <asm/uaccess.h>
#include <asm/unistd.h>
#include <asm/mca.h>
#include <asm/paravirt.h>
extern void ia64_tlb_init (void);
unsigned long MAX_DMA_ADDRESS = PAGE_OFFSET + 0x100000000UL;
#ifdef CONFIG_VIRTUAL_MEM_MAP
unsigned long VMALLOC_END = VMALLOC_END_INIT;
EXPORT_SYMBOL(VMALLOC_END);
struct page *vmem_map;
EXPORT_SYMBOL(vmem_map);
#endif
struct page *zero_page_memmap_ptr; /* map entry for zero page */
EXPORT_SYMBOL(zero_page_memmap_ptr);
void
__ia64_sync_icache_dcache (pte_t pte)
{
unsigned long addr;
struct page *page;
page = pte_page(pte);
addr = (unsigned long) page_address(page);
if (test_bit(PG_arch_1, &page->flags))
return; /* i-cache is already coherent with d-cache */
flush_icache_range(addr, addr + (PAGE_SIZE << compound_order(page)));
set_bit(PG_arch_1, &page->flags); /* mark page as clean */
}
/*
* Since DMA is i-cache coherent, any (complete) pages that were written via
* DMA can be marked as "clean" so that lazy_mmu_prot_update() doesn't have to
* flush them when they get mapped into an executable vm-area.
*/
void
dma_mark_clean(void *addr, size_t size)
{
unsigned long pg_addr, end;
pg_addr = PAGE_ALIGN((unsigned long) addr);
end = (unsigned long) addr + size;
while (pg_addr + PAGE_SIZE <= end) {
struct page *page = virt_to_page(pg_addr);
set_bit(PG_arch_1, &page->flags);
pg_addr += PAGE_SIZE;
}
}
inline void
ia64_set_rbs_bot (void)
{
unsigned long stack_size = rlimit_max(RLIMIT_STACK) & -16;
if (stack_size > MAX_USER_STACK_SIZE)
stack_size = MAX_USER_STACK_SIZE;
current->thread.rbs_bot = PAGE_ALIGN(current->mm->start_stack - stack_size);
}
/*
* This performs some platform-dependent address space initialization.
* On IA-64, we want to setup the VM area for the register backing
* store (which grows upwards) and install the gateway page which is
* used for signal trampolines, etc.
*/
void
ia64_init_addr_space (void)
{
struct vm_area_struct *vma;
ia64_set_rbs_bot();
/*
* If we're out of memory and kmem_cache_alloc() returns NULL, we simply ignore
* the problem. When the process attempts to write to the register backing store
* for the first time, it will get a SEGFAULT in this case.
*/
vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
if (vma) {
INIT_LIST_HEAD(&vma->anon_vma_chain);
vma->vm_mm = current->mm;
vma->vm_start = current->thread.rbs_bot & PAGE_MASK;
vma->vm_end = vma->vm_start + PAGE_SIZE;
vma->vm_flags = VM_DATA_DEFAULT_FLAGS|VM_GROWSUP|VM_ACCOUNT;
vma->vm_page_prot = vm_get_page_prot(vma->vm_flags);
down_write(¤t->mm->mmap_sem);
if (insert_vm_struct(current->mm, vma)) {
up_write(¤t->mm->mmap_sem);
kmem_cache_free(vm_area_cachep, vma);
return;
}
up_write(¤t->mm->mmap_sem);
}
/* map NaT-page at address zero to speed up speculative dereferencing of NULL: */
if (!(current->personality & MMAP_PAGE_ZERO)) {
vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
if (vma) {
INIT_LIST_HEAD(&vma->anon_vma_chain);
vma->vm_mm = current->mm;
vma->vm_end = PAGE_SIZE;
vma->vm_page_prot = __pgprot(pgprot_val(PAGE_READONLY) | _PAGE_MA_NAT);
vma->vm_flags = VM_READ | VM_MAYREAD | VM_IO | VM_RESERVED;
down_write(¤t->mm->mmap_sem);
if (insert_vm_struct(current->mm, vma)) {
up_write(¤t->mm->mmap_sem);
kmem_cache_free(vm_area_cachep, vma);
return;
}
up_write(¤t->mm->mmap_sem);
}
}
}
void
free_initmem (void)
{
unsigned long addr, eaddr;
addr = (unsigned long) ia64_imva(__init_begin);
eaddr = (unsigned long) ia64_imva(__init_end);
while (addr < eaddr) {
ClearPageReserved(virt_to_page(addr));
init_page_count(virt_to_page(addr));
free_page(addr);
++totalram_pages;
addr += PAGE_SIZE;
}
printk(KERN_INFO "Freeing unused kernel memory: %ldkB freed\n",
(__init_end - __init_begin) >> 10);
}
void __init
free_initrd_mem (unsigned long start, unsigned long end)
{
struct page *page;
/*
* EFI uses 4KB pages while the kernel can use 4KB or bigger.
* Thus EFI and the kernel may have different page sizes. It is
* therefore possible to have the initrd share the same page as
* the end of the kernel (given current setup).
*
* To avoid freeing/using the wrong page (kernel sized) we:
* - align up the beginning of initrd
* - align down the end of initrd
*
* | |
* |=============| a000
* | |
* | |
* | | 9000
* |/////////////|
* |/////////////|
* |=============| 8000
* |///INITRD////|
* |/////////////|
* |/////////////| 7000
* | |
* |KKKKKKKKKKKKK|
* |=============| 6000
* |KKKKKKKKKKKKK|
* |KKKKKKKKKKKKK|
* K=kernel using 8KB pages
*
* In this example, we must free page 8000 ONLY. So we must align up
* initrd_start and keep initrd_end as is.
*/
start = PAGE_ALIGN(start);
end = end & PAGE_MASK;
if (start < end)
printk(KERN_INFO "Freeing initrd memory: %ldkB freed\n", (end - start) >> 10);
for (; start < end; start += PAGE_SIZE) {
if (!virt_addr_valid(start))
continue;
page = virt_to_page(start);
ClearPageReserved(page);
init_page_count(page);
free_page(start);
++totalram_pages;
}
}
/*
* This installs a clean page in the kernel's page table.
*/
static struct page * __init
put_kernel_page (struct page *page, unsigned long address, pgprot_t pgprot)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
if (!PageReserved(page))
printk(KERN_ERR "put_kernel_page: page at 0x%p not in reserved memory\n",
page_address(page));
pgd = pgd_offset_k(address); /* note: this is NOT pgd_offset()! */
{
pud = pud_alloc(&init_mm, pgd, address);
if (!pud)
goto out;
pmd = pmd_alloc(&init_mm, pud, address);
if (!pmd)
goto out;
pte = pte_alloc_kernel(pmd, address);
if (!pte)
goto out;
if (!pte_none(*pte))
goto out;
set_pte(pte, mk_pte(page, pgprot));
}
out:
/* no need for flush_tlb */
return page;
}
static void __init
setup_gate (void)
{
void *gate_section;
struct page *page;
/*
* Map the gate page twice: once read-only to export the ELF
* headers etc. and once execute-only page to enable
* privilege-promotion via "epc":
*/
gate_section = paravirt_get_gate_section();
page = virt_to_page(ia64_imva(gate_section));
put_kernel_page(page, GATE_ADDR, PAGE_READONLY);
#ifdef HAVE_BUGGY_SEGREL
page = virt_to_page(ia64_imva(gate_section + PAGE_SIZE));
put_kernel_page(page, GATE_ADDR + PAGE_SIZE, PAGE_GATE);
#else
put_kernel_page(page, GATE_ADDR + PERCPU_PAGE_SIZE, PAGE_GATE);
/* Fill in the holes (if any) with read-only zero pages: */
{
unsigned long addr;
for (addr = GATE_ADDR + PAGE_SIZE;
addr < GATE_ADDR + PERCPU_PAGE_SIZE;
addr += PAGE_SIZE)
{
put_kernel_page(ZERO_PAGE(0), addr,
PAGE_READONLY);
put_kernel_page(ZERO_PAGE(0), addr + PERCPU_PAGE_SIZE,
PAGE_READONLY);
}
}
#endif
ia64_patch_gate();
}
void __devinit
ia64_mmu_init (void *my_cpu_data)
{
unsigned long pta, impl_va_bits;
extern void __devinit tlb_init (void);
#ifdef CONFIG_DISABLE_VHPT
# define VHPT_ENABLE_BIT 0
#else
# define VHPT_ENABLE_BIT 1
#endif
/*
* Check if the virtually mapped linear page table (VMLPT) overlaps with a mapped
* address space. The IA-64 architecture guarantees that at least 50 bits of
* virtual address space are implemented but if we pick a large enough page size
* (e.g., 64KB), the mapped address space is big enough that it will overlap with
* VMLPT. I assume that once we run on machines big enough to warrant 64KB pages,
* IMPL_VA_MSB will be significantly bigger, so this is unlikely to become a
* problem in practice. Alternatively, we could truncate the top of the mapped
* address space to not permit mappings that would overlap with the VMLPT.
* --davidm 00/12/06
*/
# define pte_bits 3
# define mapped_space_bits (3*(PAGE_SHIFT - pte_bits) + PAGE_SHIFT)
/*
* The virtual page table has to cover the entire implemented address space within
* a region even though not all of this space may be mappable. The reason for
* this is that the Access bit and Dirty bit fault handlers perform
* non-speculative accesses to the virtual page table, so the address range of the
* virtual page table itself needs to be covered by virtual page table.
*/
# define vmlpt_bits (impl_va_bits - PAGE_SHIFT + pte_bits)
# define POW2(n) (1ULL << (n))
impl_va_bits = ffz(~(local_cpu_data->unimpl_va_mask | (7UL << 61)));
if (impl_va_bits < 51 || impl_va_bits > 61)
panic("CPU has bogus IMPL_VA_MSB value of %lu!\n", impl_va_bits - 1);
/*
* mapped_space_bits - PAGE_SHIFT is the total number of ptes we need,
* which must fit into "vmlpt_bits - pte_bits" slots. Second half of
* the test makes sure that our mapped space doesn't overlap the
* unimplemented hole in the middle of the region.
*/
if ((mapped_space_bits - PAGE_SHIFT > vmlpt_bits - pte_bits) ||
(mapped_space_bits > impl_va_bits - 1))
panic("Cannot build a big enough virtual-linear page table"
" to cover mapped address space.\n"
" Try using a smaller page size.\n");
/* place the VMLPT at the end of each page-table mapped region: */
pta = POW2(61) - POW2(vmlpt_bits);
/*
* Set the (virtually mapped linear) page table address. Bit
* 8 selects between the short and long format, bits 2-7 the
* size of the table, and bit 0 whether the VHPT walker is
* enabled.
*/
ia64_set_pta(pta | (0 << 8) | (vmlpt_bits << 2) | VHPT_ENABLE_BIT);
ia64_tlb_init();
#ifdef CONFIG_HUGETLB_PAGE
ia64_set_rr(HPAGE_REGION_BASE, HPAGE_SHIFT << 2);
ia64_srlz_d();
#endif
}
#ifdef CONFIG_VIRTUAL_MEM_MAP
int vmemmap_find_next_valid_pfn(int node, int i)
{
unsigned long end_address, hole_next_pfn;
unsigned long stop_address;
pg_data_t *pgdat = NODE_DATA(node);
end_address = (unsigned long) &vmem_map[pgdat->node_start_pfn + i];
end_address = PAGE_ALIGN(end_address);
stop_address = (unsigned long) &vmem_map[
pgdat->node_start_pfn + pgdat->node_spanned_pages];
do {
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
pgd = pgd_offset_k(end_address);
if (pgd_none(*pgd)) {
end_address += PGDIR_SIZE;
continue;
}
pud = pud_offset(pgd, end_address);
if (pud_none(*pud)) {
end_address += PUD_SIZE;
continue;
}
pmd = pmd_offset(pud, end_address);
if (pmd_none(*pmd)) {
end_address += PMD_SIZE;
continue;
}
pte = pte_offset_kernel(pmd, end_address);
retry_pte:
if (pte_none(*pte)) {
end_address += PAGE_SIZE;
pte++;
if ((end_address < stop_address) &&
(end_address != ALIGN(end_address, 1UL << PMD_SHIFT)))
goto retry_pte;
continue;
}
/* Found next valid vmem_map page */
break;
} while (end_address < stop_address);
end_address = min(end_address, stop_address);
end_address = end_address - (unsigned long) vmem_map + sizeof(struct page) - 1;
hole_next_pfn = end_address / sizeof(struct page);
return hole_next_pfn - pgdat->node_start_pfn;
}
int __init create_mem_map_page_table(u64 start, u64 end, void *arg)
{
unsigned long address, start_page, end_page;
struct page *map_start, *map_end;
int node;
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
map_start = vmem_map + (__pa(start) >> PAGE_SHIFT);
map_end = vmem_map + (__pa(end) >> PAGE_SHIFT);
start_page = (unsigned long) map_start & PAGE_MASK;
end_page = PAGE_ALIGN((unsigned long) map_end);
node = paddr_to_nid(__pa(start));
for (address = start_page; address < end_page; address += PAGE_SIZE) {
pgd = pgd_offset_k(address);
if (pgd_none(*pgd))
pgd_populate(&init_mm, pgd, alloc_bootmem_pages_node(NODE_DATA(node), PAGE_SIZE));
pud = pud_offset(pgd, address);
if (pud_none(*pud))
pud_populate(&init_mm, pud, alloc_bootmem_pages_node(NODE_DATA(node), PAGE_SIZE));
pmd = pmd_offset(pud, address);
if (pmd_none(*pmd))
pmd_populate_kernel(&init_mm, pmd, alloc_bootmem_pages_node(NODE_DATA(node), PAGE_SIZE));
pte = pte_offset_kernel(pmd, address);
if (pte_none(*pte))
set_pte(pte, pfn_pte(__pa(alloc_bootmem_pages_node(NODE_DATA(node), PAGE_SIZE)) >> PAGE_SHIFT,
PAGE_KERNEL));
}
return 0;
}
struct memmap_init_callback_data {
struct page *start;
struct page *end;
int nid;
unsigned long zone;
};
static int __meminit
virtual_memmap_init(u64 start, u64 end, void *arg)
{
struct memmap_init_callback_data *args;
struct page *map_start, *map_end;
args = (struct memmap_init_callback_data *) arg;
map_start = vmem_map + (__pa(start) >> PAGE_SHIFT);
map_end = vmem_map + (__pa(end) >> PAGE_SHIFT);
if (map_start < args->start)
map_start = args->start;
if (map_end > args->end)
map_end = args->end;
/*
* We have to initialize "out of bounds" struct page elements that fit completely
* on the same pages that were allocated for the "in bounds" elements because they
* may be referenced later (and found to be "reserved").
*/
map_start -= ((unsigned long) map_start & (PAGE_SIZE - 1)) / sizeof(struct page);
map_end += ((PAGE_ALIGN((unsigned long) map_end) - (unsigned long) map_end)
/ sizeof(struct page));
if (map_start < map_end)
memmap_init_zone((unsigned long)(map_end - map_start),
args->nid, args->zone, page_to_pfn(map_start),
MEMMAP_EARLY);
return 0;
}
void __meminit
memmap_init (unsigned long size, int nid, unsigned long zone,
unsigned long start_pfn)
{
if (!vmem_map)
memmap_init_zone(size, nid, zone, start_pfn, MEMMAP_EARLY);
else {
struct page *start;
struct memmap_init_callback_data args;
start = pfn_to_page(start_pfn);
args.start = start;
args.end = start + size;
args.nid = nid;
args.zone = zone;
efi_memmap_walk(virtual_memmap_init, &args);
}
}
int
ia64_pfn_valid (unsigned long pfn)
{
char byte;
struct page *pg = pfn_to_page(pfn);
return (__get_user(byte, (char __user *) pg) == 0)
&& ((((u64)pg & PAGE_MASK) == (((u64)(pg + 1) - 1) & PAGE_MASK))
|| (__get_user(byte, (char __user *) (pg + 1) - 1) == 0));
}
EXPORT_SYMBOL(ia64_pfn_valid);
int __init find_largest_hole(u64 start, u64 end, void *arg)
{
u64 *max_gap = arg;
static u64 last_end = PAGE_OFFSET;
/* NOTE: this algorithm assumes efi memmap table is ordered */
if (*max_gap < (start - last_end))
*max_gap = start - last_end;
last_end = end;
return 0;
}
#endif /* CONFIG_VIRTUAL_MEM_MAP */
int __init register_active_ranges(u64 start, u64 len, int nid)
{
u64 end = start + len;
#ifdef CONFIG_KEXEC
if (start > crashk_res.start && start < crashk_res.end)
start = crashk_res.end;
if (end > crashk_res.start && end < crashk_res.end)
end = crashk_res.start;
#endif
if (start < end)
add_active_range(nid, __pa(start) >> PAGE_SHIFT,
__pa(end) >> PAGE_SHIFT);
return 0;
}
static int __init
count_reserved_pages(u64 start, u64 end, void *arg)
{
unsigned long num_reserved = 0;
unsigned long *count = arg;
for (; start < end; start += PAGE_SIZE)
if (PageReserved(virt_to_page(start)))
++num_reserved;
*count += num_reserved;
return 0;
}
int
find_max_min_low_pfn (u64 start, u64 end, void *arg)
{
unsigned long pfn_start, pfn_end;
#ifdef CONFIG_FLATMEM
pfn_start = (PAGE_ALIGN(__pa(start))) >> PAGE_SHIFT;
pfn_end = (PAGE_ALIGN(__pa(end - 1))) >> PAGE_SHIFT;
#else
pfn_start = GRANULEROUNDDOWN(__pa(start)) >> PAGE_SHIFT;
pfn_end = GRANULEROUNDUP(__pa(end - 1)) >> PAGE_SHIFT;
#endif
min_low_pfn = min(min_low_pfn, pfn_start);
max_low_pfn = max(max_low_pfn, pfn_end);
return 0;
}
/*
* Boot command-line option "nolwsys" can be used to disable the use of any light-weight
* system call handler. When this option is in effect, all fsyscalls will end up bubbling
* down into the kernel and calling the normal (heavy-weight) syscall handler. This is
* useful for performance testing, but conceivably could also come in handy for debugging
* purposes.
*/
static int nolwsys __initdata;
static int __init
nolwsys_setup (char *s)
{
nolwsys = 1;
return 1;
}
__setup("nolwsys", nolwsys_setup);
void __init
mem_init (void)
{
long reserved_pages, codesize, datasize, initsize;
pg_data_t *pgdat;
int i;
BUG_ON(PTRS_PER_PGD * sizeof(pgd_t) != PAGE_SIZE);
BUG_ON(PTRS_PER_PMD * sizeof(pmd_t) != PAGE_SIZE);
BUG_ON(PTRS_PER_PTE * sizeof(pte_t) != PAGE_SIZE);
#ifdef CONFIG_PCI
/*
* This needs to be called _after_ the command line has been parsed but _before_
* any drivers that may need the PCI DMA interface are initialized or bootmem has
* been freed.
*/
platform_dma_init();
#endif
#ifdef CONFIG_FLATMEM
BUG_ON(!mem_map);
max_mapnr = max_low_pfn;
#endif
high_memory = __va(max_low_pfn * PAGE_SIZE);
for_each_online_pgdat(pgdat)
if (pgdat->bdata->node_bootmem_map)
totalram_pages += free_all_bootmem_node(pgdat);
reserved_pages = 0;
efi_memmap_walk(count_reserved_pages, &reserved_pages);
codesize = (unsigned long) _etext - (unsigned long) _stext;
datasize = (unsigned long) _edata - (unsigned long) _etext;
initsize = (unsigned long) __init_end - (unsigned long) __init_begin;
printk(KERN_INFO "Memory: %luk/%luk available (%luk code, %luk reserved, "
"%luk data, %luk init)\n", nr_free_pages() << (PAGE_SHIFT - 10),
num_physpages << (PAGE_SHIFT - 10), codesize >> 10,
reserved_pages << (PAGE_SHIFT - 10), datasize >> 10, initsize >> 10);
/*
* For fsyscall entrpoints with no light-weight handler, use the ordinary
* (heavy-weight) handler, but mark it by setting bit 0, so the fsyscall entry
* code can tell them apart.
*/
for (i = 0; i < NR_syscalls; ++i) {
extern unsigned long sys_call_table[NR_syscalls];
unsigned long *fsyscall_table = paravirt_get_fsyscall_table();
if (!fsyscall_table[i] || nolwsys)
fsyscall_table[i] = sys_call_table[i] | 1;
}
setup_gate();
}
#ifdef CONFIG_MEMORY_HOTPLUG
int arch_add_memory(int nid, u64 start, u64 size)
{
pg_data_t *pgdat;
struct zone *zone;
unsigned long start_pfn = start >> PAGE_SHIFT;
unsigned long nr_pages = size >> PAGE_SHIFT;
int ret;
pgdat = NODE_DATA(nid);
zone = pgdat->node_zones + ZONE_NORMAL;
ret = __add_pages(nid, zone, start_pfn, nr_pages);
if (ret)
printk("%s: Problem encountered in __add_pages() as ret=%d\n",
__func__, ret);
return ret;
}
#endif
/*
* Even when CONFIG_IA32_SUPPORT is not enabled it is
* useful to have the Linux/x86 domain registered to
* avoid an attempted module load when emulators call
* personality(PER_LINUX32). This saves several milliseconds
* on each such call.
*/
static struct exec_domain ia32_exec_domain;
static int __init
per_linux32_init(void)
{
ia32_exec_domain.name = "Linux/x86";
ia32_exec_domain.handler = NULL;
ia32_exec_domain.pers_low = PER_LINUX32;
ia32_exec_domain.pers_high = PER_LINUX32;
ia32_exec_domain.signal_map = default_exec_domain.signal_map;
ia32_exec_domain.signal_invmap = default_exec_domain.signal_invmap;
register_exec_domain(&ia32_exec_domain);
return 0;
}
__initcall(per_linux32_init);
| gpl-2.0 |
n1kolaa/kernel_s3ve3g_stock | arch/arm/mach-msm/smd_rpcrouter_xdr.c | 3506 | 9160 | /* Copyright (c) 2010, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
/*
* SMD RPCROUTER XDR module.
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <mach/msm_rpcrouter.h>
int xdr_send_uint32(struct msm_rpc_xdr *xdr, const uint32_t *value)
{
if ((xdr->out_index + sizeof(uint32_t)) > xdr->out_size) {
pr_err("%s: xdr out buffer full\n", __func__);
return -1;
}
*(uint32_t *)(xdr->out_buf + xdr->out_index) = cpu_to_be32(*value);
xdr->out_index += sizeof(uint32_t);
return 0;
}
int xdr_send_int8(struct msm_rpc_xdr *xdr, const int8_t *value)
{
return xdr_send_uint32(xdr, (uint32_t *)value);
}
int xdr_send_uint8(struct msm_rpc_xdr *xdr, const uint8_t *value)
{
return xdr_send_uint32(xdr, (uint32_t *)value);
}
int xdr_send_int16(struct msm_rpc_xdr *xdr, const int16_t *value)
{
return xdr_send_uint32(xdr, (uint32_t *)value);
}
int xdr_send_uint16(struct msm_rpc_xdr *xdr, const uint16_t *value)
{
return xdr_send_uint32(xdr, (uint32_t *)value);
}
int xdr_send_int32(struct msm_rpc_xdr *xdr, const int32_t *value)
{
return xdr_send_uint32(xdr, (uint32_t *)value);
}
int xdr_send_bytes(struct msm_rpc_xdr *xdr, const void **data,
uint32_t *size)
{
void *buf = xdr->out_buf + xdr->out_index;
uint32_t temp;
if (!size || !data || !*data)
return -1;
temp = *size;
if (temp & 0x3)
temp += 4 - (temp & 0x3);
temp += sizeof(uint32_t);
if ((xdr->out_index + temp) > xdr->out_size) {
pr_err("%s: xdr out buffer full\n", __func__);
return -1;
}
*((uint32_t *)buf) = cpu_to_be32(*size);
buf += sizeof(uint32_t);
memcpy(buf, *data, *size);
buf += *size;
if (*size & 0x3) {
memset(buf, 0, 4 - (*size & 0x3));
buf += 4 - (*size & 0x3);
}
xdr->out_index = buf - xdr->out_buf;
return 0;
}
int xdr_recv_uint32(struct msm_rpc_xdr *xdr, uint32_t *value)
{
if ((xdr->in_index + sizeof(uint32_t)) > xdr->in_size) {
pr_err("%s: xdr in buffer full\n", __func__);
return -1;
}
*value = be32_to_cpu(*(uint32_t *)(xdr->in_buf + xdr->in_index));
xdr->in_index += sizeof(uint32_t);
return 0;
}
int xdr_recv_int8(struct msm_rpc_xdr *xdr, int8_t *value)
{
return xdr_recv_uint32(xdr, (uint32_t *)value);
}
int xdr_recv_uint8(struct msm_rpc_xdr *xdr, uint8_t *value)
{
return xdr_recv_uint32(xdr, (uint32_t *)value);
}
int xdr_recv_int16(struct msm_rpc_xdr *xdr, int16_t *value)
{
return xdr_recv_uint32(xdr, (uint32_t *)value);
}
int xdr_recv_uint16(struct msm_rpc_xdr *xdr, uint16_t *value)
{
return xdr_recv_uint32(xdr, (uint32_t *)value);
}
int xdr_recv_int32(struct msm_rpc_xdr *xdr, int32_t *value)
{
return xdr_recv_uint32(xdr, (uint32_t *)value);
}
int xdr_recv_bytes(struct msm_rpc_xdr *xdr, void **data,
uint32_t *size)
{
void *buf = xdr->in_buf + xdr->in_index;
uint32_t temp;
if (!size || !data)
return -1;
*size = be32_to_cpu(*(uint32_t *)buf);
buf += sizeof(uint32_t);
temp = *size;
if (temp & 0x3)
temp += 4 - (temp & 0x3);
temp += sizeof(uint32_t);
if ((xdr->in_index + temp) > xdr->in_size) {
pr_err("%s: xdr in buffer full\n", __func__);
return -1;
}
if (*size) {
*data = kmalloc(*size, GFP_KERNEL);
if (!*data)
return -1;
memcpy(*data, buf, *size);
buf += *size;
if (*size & 0x3)
buf += 4 - (*size & 0x3);
} else
*data = NULL;
xdr->in_index = buf - xdr->in_buf;
return 0;
}
int xdr_send_pointer(struct msm_rpc_xdr *xdr, void **obj,
uint32_t obj_size, void *xdr_op)
{
uint32_t ptr_valid, rc;
ptr_valid = (*obj != NULL);
rc = xdr_send_uint32(xdr, &ptr_valid);
if (rc)
return rc;
if (!ptr_valid)
return 0;
return ((int (*) (struct msm_rpc_xdr *, void *))xdr_op)(xdr, *obj);
}
int xdr_recv_pointer(struct msm_rpc_xdr *xdr, void **obj,
uint32_t obj_size, void *xdr_op)
{
uint32_t rc, ptr_valid = 0;
rc = xdr_recv_uint32(xdr, &ptr_valid);
if (rc)
return rc;
if (!ptr_valid) {
*obj = NULL;
return 0;
}
*obj = kmalloc(obj_size, GFP_KERNEL);
if (!*obj)
return -1;
rc = ((int (*) (struct msm_rpc_xdr *, void *))xdr_op)(xdr, *obj);
if (rc)
kfree(*obj);
return rc;
}
int xdr_send_array(struct msm_rpc_xdr *xdr, void **addr, uint32_t *size,
uint32_t maxsize, uint32_t elm_size, void *xdr_op)
{
int i, rc;
void *tmp_addr = *addr;
if (!size || !tmp_addr || (*size > maxsize) || !xdr_op)
return -1;
rc = xdr_send_uint32(xdr, size);
if (rc)
return rc;
for (i = 0; i < *size; i++) {
rc = ((int (*) (struct msm_rpc_xdr *, void *))xdr_op)
(xdr, tmp_addr);
if (rc)
return rc;
tmp_addr += elm_size;
}
return 0;
}
int xdr_recv_array(struct msm_rpc_xdr *xdr, void **addr, uint32_t *size,
uint32_t maxsize, uint32_t elm_size, void *xdr_op)
{
int i, rc;
void *tmp_addr;
if (!size || !xdr_op)
return -1;
rc = xdr_recv_uint32(xdr, size);
if (rc)
return rc;
if (*size > maxsize)
return -1;
tmp_addr = kmalloc((*size * elm_size), GFP_KERNEL);
if (!tmp_addr)
return -1;
*addr = tmp_addr;
for (i = 0; i < *size; i++) {
rc = ((int (*) (struct msm_rpc_xdr *, void *))xdr_op)
(xdr, tmp_addr);
if (rc) {
kfree(*addr);
*addr = NULL;
return rc;
}
tmp_addr += elm_size;
}
return 0;
}
int xdr_recv_req(struct msm_rpc_xdr *xdr, struct rpc_request_hdr *req)
{
int rc = 0;
if (!req)
return -1;
rc |= xdr_recv_uint32(xdr, &req->xid); /* xid */
rc |= xdr_recv_uint32(xdr, &req->type); /* type */
rc |= xdr_recv_uint32(xdr, &req->rpc_vers); /* rpc_vers */
rc |= xdr_recv_uint32(xdr, &req->prog); /* prog */
rc |= xdr_recv_uint32(xdr, &req->vers); /* vers */
rc |= xdr_recv_uint32(xdr, &req->procedure); /* procedure */
rc |= xdr_recv_uint32(xdr, &req->cred_flavor); /* cred_flavor */
rc |= xdr_recv_uint32(xdr, &req->cred_length); /* cred_length */
rc |= xdr_recv_uint32(xdr, &req->verf_flavor); /* verf_flavor */
rc |= xdr_recv_uint32(xdr, &req->verf_length); /* verf_length */
return rc;
}
int xdr_recv_reply(struct msm_rpc_xdr *xdr, struct rpc_reply_hdr *reply)
{
int rc = 0;
if (!reply)
return -1;
rc |= xdr_recv_uint32(xdr, &reply->xid); /* xid */
rc |= xdr_recv_uint32(xdr, &reply->type); /* type */
rc |= xdr_recv_uint32(xdr, &reply->reply_stat); /* reply_stat */
/* acc_hdr */
if (reply->reply_stat == RPCMSG_REPLYSTAT_ACCEPTED) {
rc |= xdr_recv_uint32(xdr, &reply->data.acc_hdr.verf_flavor);
rc |= xdr_recv_uint32(xdr, &reply->data.acc_hdr.verf_length);
rc |= xdr_recv_uint32(xdr, &reply->data.acc_hdr.accept_stat);
}
return rc;
}
int xdr_start_request(struct msm_rpc_xdr *xdr, uint32_t prog,
uint32_t ver, uint32_t proc)
{
mutex_lock(&xdr->out_lock);
/* TODO: replace below function with its implementation */
msm_rpc_setup_req((struct rpc_request_hdr *)xdr->out_buf,
prog, ver, proc);
xdr->out_index = sizeof(struct rpc_request_hdr);
return 0;
}
int xdr_start_accepted_reply(struct msm_rpc_xdr *xdr, uint32_t accept_status)
{
struct rpc_reply_hdr *reply;
mutex_lock(&xdr->out_lock);
/* TODO: err if xdr is not cb xdr */
reply = (struct rpc_reply_hdr *)xdr->out_buf;
/* TODO: use xdr functions instead */
reply->xid = ((struct rpc_request_hdr *)(xdr->in_buf))->xid;
reply->type = cpu_to_be32(1); /* reply */
reply->reply_stat = cpu_to_be32(RPCMSG_REPLYSTAT_ACCEPTED);
reply->data.acc_hdr.accept_stat = cpu_to_be32(accept_status);
reply->data.acc_hdr.verf_flavor = 0;
reply->data.acc_hdr.verf_length = 0;
xdr->out_index = sizeof(*reply);
return 0;
}
int xdr_send_msg(struct msm_rpc_xdr *xdr)
{
int rc = 0;
rc = msm_rpc_write(xdr->ept, xdr->out_buf,
xdr->out_index);
if (rc > 0)
rc = 0;
mutex_unlock(&xdr->out_lock);
return rc;
}
void xdr_init(struct msm_rpc_xdr *xdr)
{
mutex_init(&xdr->out_lock);
init_waitqueue_head(&xdr->in_buf_wait_q);
xdr->in_buf = NULL;
xdr->in_size = 0;
xdr->in_index = 0;
xdr->out_buf = NULL;
xdr->out_size = 0;
xdr->out_index = 0;
}
void xdr_init_input(struct msm_rpc_xdr *xdr, void *buf, uint32_t size)
{
wait_event(xdr->in_buf_wait_q, !(xdr->in_buf));
xdr->in_buf = buf;
xdr->in_size = size;
xdr->in_index = 0;
}
void xdr_init_output(struct msm_rpc_xdr *xdr, void *buf, uint32_t size)
{
xdr->out_buf = buf;
xdr->out_size = size;
xdr->out_index = 0;
}
void xdr_clean_input(struct msm_rpc_xdr *xdr)
{
kfree(xdr->in_buf);
xdr->in_size = 0;
xdr->in_index = 0;
xdr->in_buf = NULL;
wake_up(&xdr->in_buf_wait_q);
}
void xdr_clean_output(struct msm_rpc_xdr *xdr)
{
kfree(xdr->out_buf);
xdr->out_buf = NULL;
xdr->out_size = 0;
xdr->out_index = 0;
}
uint32_t xdr_read_avail(struct msm_rpc_xdr *xdr)
{
return xdr->in_size;
}
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_n1 | arch/powerpc/platforms/ps3/repository.c | 4530 | 28960 | /*
* PS3 repository routines.
*
* Copyright (C) 2006 Sony Computer Entertainment Inc.
* Copyright 2006 Sony 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; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <asm/lv1call.h>
#include "platform.h"
enum ps3_vendor_id {
PS3_VENDOR_ID_NONE = 0,
PS3_VENDOR_ID_SONY = 0x8000000000000000UL,
};
enum ps3_lpar_id {
PS3_LPAR_ID_CURRENT = 0,
PS3_LPAR_ID_PME = 1,
};
#define dump_field(_a, _b) _dump_field(_a, _b, __func__, __LINE__)
static void _dump_field(const char *hdr, u64 n, const char *func, int line)
{
#if defined(DEBUG)
char s[16];
const char *const in = (const char *)&n;
unsigned int i;
for (i = 0; i < 8; i++)
s[i] = (in[i] <= 126 && in[i] >= 32) ? in[i] : '.';
s[i] = 0;
pr_debug("%s:%d: %s%016llx : %s\n", func, line, hdr, n, s);
#endif
}
#define dump_node_name(_a, _b, _c, _d, _e) \
_dump_node_name(_a, _b, _c, _d, _e, __func__, __LINE__)
static void _dump_node_name(unsigned int lpar_id, u64 n1, u64 n2, u64 n3,
u64 n4, const char *func, int line)
{
pr_debug("%s:%d: lpar: %u\n", func, line, lpar_id);
_dump_field("n1: ", n1, func, line);
_dump_field("n2: ", n2, func, line);
_dump_field("n3: ", n3, func, line);
_dump_field("n4: ", n4, func, line);
}
#define dump_node(_a, _b, _c, _d, _e, _f, _g) \
_dump_node(_a, _b, _c, _d, _e, _f, _g, __func__, __LINE__)
static void _dump_node(unsigned int lpar_id, u64 n1, u64 n2, u64 n3, u64 n4,
u64 v1, u64 v2, const char *func, int line)
{
pr_debug("%s:%d: lpar: %u\n", func, line, lpar_id);
_dump_field("n1: ", n1, func, line);
_dump_field("n2: ", n2, func, line);
_dump_field("n3: ", n3, func, line);
_dump_field("n4: ", n4, func, line);
pr_debug("%s:%d: v1: %016llx\n", func, line, v1);
pr_debug("%s:%d: v2: %016llx\n", func, line, v2);
}
/**
* make_first_field - Make the first field of a repository node name.
* @text: Text portion of the field.
* @index: Numeric index portion of the field. Use zero for 'don't care'.
*
* This routine sets the vendor id to zero (non-vendor specific).
* Returns field value.
*/
static u64 make_first_field(const char *text, u64 index)
{
u64 n;
strncpy((char *)&n, text, 8);
return PS3_VENDOR_ID_NONE + (n >> 32) + index;
}
/**
* make_field - Make subsequent fields of a repository node name.
* @text: Text portion of the field. Use "" for 'don't care'.
* @index: Numeric index portion of the field. Use zero for 'don't care'.
*
* Returns field value.
*/
static u64 make_field(const char *text, u64 index)
{
u64 n;
strncpy((char *)&n, text, 8);
return n + index;
}
/**
* read_node - Read a repository node from raw fields.
* @n1: First field of node name.
* @n2: Second field of node name. Use zero for 'don't care'.
* @n3: Third field of node name. Use zero for 'don't care'.
* @n4: Fourth field of node name. Use zero for 'don't care'.
* @v1: First repository value (high word).
* @v2: Second repository value (low word). Optional parameter, use zero
* for 'don't care'.
*/
static int read_node(unsigned int lpar_id, u64 n1, u64 n2, u64 n3, u64 n4,
u64 *_v1, u64 *_v2)
{
int result;
u64 v1;
u64 v2;
if (lpar_id == PS3_LPAR_ID_CURRENT) {
u64 id;
lv1_get_logical_partition_id(&id);
lpar_id = id;
}
result = lv1_get_repository_node_value(lpar_id, n1, n2, n3, n4, &v1,
&v2);
if (result) {
pr_debug("%s:%d: lv1_get_repository_node_value failed: %s\n",
__func__, __LINE__, ps3_result(result));
dump_node_name(lpar_id, n1, n2, n3, n4);
return -ENOENT;
}
dump_node(lpar_id, n1, n2, n3, n4, v1, v2);
if (_v1)
*_v1 = v1;
if (_v2)
*_v2 = v2;
if (v1 && !_v1)
pr_debug("%s:%d: warning: discarding non-zero v1: %016llx\n",
__func__, __LINE__, v1);
if (v2 && !_v2)
pr_debug("%s:%d: warning: discarding non-zero v2: %016llx\n",
__func__, __LINE__, v2);
return 0;
}
int ps3_repository_read_bus_str(unsigned int bus_index, const char *bus_str,
u64 *value)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field(bus_str, 0),
0, 0,
value, NULL);
}
int ps3_repository_read_bus_id(unsigned int bus_index, u64 *bus_id)
{
int result;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("id", 0),
0, 0,
bus_id, NULL);
return result;
}
int ps3_repository_read_bus_type(unsigned int bus_index,
enum ps3_bus_type *bus_type)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("type", 0),
0, 0,
&v1, NULL);
*bus_type = v1;
return result;
}
int ps3_repository_read_bus_num_dev(unsigned int bus_index,
unsigned int *num_dev)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("num_dev", 0),
0, 0,
&v1, NULL);
*num_dev = v1;
return result;
}
int ps3_repository_read_dev_str(unsigned int bus_index,
unsigned int dev_index, const char *dev_str, u64 *value)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field(dev_str, 0),
0,
value, NULL);
}
int ps3_repository_read_dev_id(unsigned int bus_index, unsigned int dev_index,
u64 *dev_id)
{
int result;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("id", 0),
0,
dev_id, NULL);
return result;
}
int ps3_repository_read_dev_type(unsigned int bus_index,
unsigned int dev_index, enum ps3_dev_type *dev_type)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("type", 0),
0,
&v1, NULL);
*dev_type = v1;
return result;
}
int ps3_repository_read_dev_intr(unsigned int bus_index,
unsigned int dev_index, unsigned int intr_index,
enum ps3_interrupt_type *intr_type, unsigned int *interrupt_id)
{
int result;
u64 v1;
u64 v2;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("intr", intr_index),
0,
&v1, &v2);
*intr_type = v1;
*interrupt_id = v2;
return result;
}
int ps3_repository_read_dev_reg_type(unsigned int bus_index,
unsigned int dev_index, unsigned int reg_index,
enum ps3_reg_type *reg_type)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("reg", reg_index),
make_field("type", 0),
&v1, NULL);
*reg_type = v1;
return result;
}
int ps3_repository_read_dev_reg_addr(unsigned int bus_index,
unsigned int dev_index, unsigned int reg_index, u64 *bus_addr, u64 *len)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("reg", reg_index),
make_field("data", 0),
bus_addr, len);
}
int ps3_repository_read_dev_reg(unsigned int bus_index,
unsigned int dev_index, unsigned int reg_index,
enum ps3_reg_type *reg_type, u64 *bus_addr, u64 *len)
{
int result = ps3_repository_read_dev_reg_type(bus_index, dev_index,
reg_index, reg_type);
return result ? result
: ps3_repository_read_dev_reg_addr(bus_index, dev_index,
reg_index, bus_addr, len);
}
int ps3_repository_find_device(struct ps3_repository_device *repo)
{
int result;
struct ps3_repository_device tmp = *repo;
unsigned int num_dev;
BUG_ON(repo->bus_index > 10);
BUG_ON(repo->dev_index > 10);
result = ps3_repository_read_bus_num_dev(tmp.bus_index, &num_dev);
if (result) {
pr_debug("%s:%d read_bus_num_dev failed\n", __func__, __LINE__);
return result;
}
pr_debug("%s:%d: bus_type %u, bus_index %u, bus_id %llu, num_dev %u\n",
__func__, __LINE__, tmp.bus_type, tmp.bus_index, tmp.bus_id,
num_dev);
if (tmp.dev_index >= num_dev) {
pr_debug("%s:%d: no device found\n", __func__, __LINE__);
return -ENODEV;
}
result = ps3_repository_read_dev_type(tmp.bus_index, tmp.dev_index,
&tmp.dev_type);
if (result) {
pr_debug("%s:%d read_dev_type failed\n", __func__, __LINE__);
return result;
}
result = ps3_repository_read_dev_id(tmp.bus_index, tmp.dev_index,
&tmp.dev_id);
if (result) {
pr_debug("%s:%d ps3_repository_read_dev_id failed\n", __func__,
__LINE__);
return result;
}
pr_debug("%s:%d: found: dev_type %u, dev_index %u, dev_id %llu\n",
__func__, __LINE__, tmp.dev_type, tmp.dev_index, tmp.dev_id);
*repo = tmp;
return 0;
}
int ps3_repository_find_device_by_id(struct ps3_repository_device *repo,
u64 bus_id, u64 dev_id)
{
int result = -ENODEV;
struct ps3_repository_device tmp;
unsigned int num_dev;
pr_debug(" -> %s:%u: find device by id %llu:%llu\n", __func__, __LINE__,
bus_id, dev_id);
for (tmp.bus_index = 0; tmp.bus_index < 10; tmp.bus_index++) {
result = ps3_repository_read_bus_id(tmp.bus_index,
&tmp.bus_id);
if (result) {
pr_debug("%s:%u read_bus_id(%u) failed\n", __func__,
__LINE__, tmp.bus_index);
return result;
}
if (tmp.bus_id == bus_id)
goto found_bus;
pr_debug("%s:%u: skip, bus_id %llu\n", __func__, __LINE__,
tmp.bus_id);
}
pr_debug(" <- %s:%u: bus not found\n", __func__, __LINE__);
return result;
found_bus:
result = ps3_repository_read_bus_type(tmp.bus_index, &tmp.bus_type);
if (result) {
pr_debug("%s:%u read_bus_type(%u) failed\n", __func__,
__LINE__, tmp.bus_index);
return result;
}
result = ps3_repository_read_bus_num_dev(tmp.bus_index, &num_dev);
if (result) {
pr_debug("%s:%u read_bus_num_dev failed\n", __func__,
__LINE__);
return result;
}
for (tmp.dev_index = 0; tmp.dev_index < num_dev; tmp.dev_index++) {
result = ps3_repository_read_dev_id(tmp.bus_index,
tmp.dev_index,
&tmp.dev_id);
if (result) {
pr_debug("%s:%u read_dev_id(%u:%u) failed\n", __func__,
__LINE__, tmp.bus_index, tmp.dev_index);
return result;
}
if (tmp.dev_id == dev_id)
goto found_dev;
pr_debug("%s:%u: skip, dev_id %llu\n", __func__, __LINE__,
tmp.dev_id);
}
pr_debug(" <- %s:%u: dev not found\n", __func__, __LINE__);
return result;
found_dev:
result = ps3_repository_read_dev_type(tmp.bus_index, tmp.dev_index,
&tmp.dev_type);
if (result) {
pr_debug("%s:%u read_dev_type failed\n", __func__, __LINE__);
return result;
}
pr_debug(" <- %s:%u: found: type (%u:%u) index (%u:%u) id (%llu:%llu)\n",
__func__, __LINE__, tmp.bus_type, tmp.dev_type, tmp.bus_index,
tmp.dev_index, tmp.bus_id, tmp.dev_id);
*repo = tmp;
return 0;
}
int __devinit ps3_repository_find_devices(enum ps3_bus_type bus_type,
int (*callback)(const struct ps3_repository_device *repo))
{
int result = 0;
struct ps3_repository_device repo;
pr_debug(" -> %s:%d: find bus_type %u\n", __func__, __LINE__, bus_type);
repo.bus_type = bus_type;
result = ps3_repository_find_bus(repo.bus_type, 0, &repo.bus_index);
if (result) {
pr_debug(" <- %s:%u: bus not found\n", __func__, __LINE__);
return result;
}
result = ps3_repository_read_bus_id(repo.bus_index, &repo.bus_id);
if (result) {
pr_debug("%s:%d read_bus_id(%u) failed\n", __func__, __LINE__,
repo.bus_index);
return result;
}
for (repo.dev_index = 0; ; repo.dev_index++) {
result = ps3_repository_find_device(&repo);
if (result == -ENODEV) {
result = 0;
break;
} else if (result)
break;
result = callback(&repo);
if (result) {
pr_debug("%s:%d: abort at callback\n", __func__,
__LINE__);
break;
}
}
pr_debug(" <- %s:%d\n", __func__, __LINE__);
return result;
}
int ps3_repository_find_bus(enum ps3_bus_type bus_type, unsigned int from,
unsigned int *bus_index)
{
unsigned int i;
enum ps3_bus_type type;
int error;
for (i = from; i < 10; i++) {
error = ps3_repository_read_bus_type(i, &type);
if (error) {
pr_debug("%s:%d read_bus_type failed\n",
__func__, __LINE__);
*bus_index = UINT_MAX;
return error;
}
if (type == bus_type) {
*bus_index = i;
return 0;
}
}
*bus_index = UINT_MAX;
return -ENODEV;
}
int ps3_repository_find_interrupt(const struct ps3_repository_device *repo,
enum ps3_interrupt_type intr_type, unsigned int *interrupt_id)
{
int result = 0;
unsigned int res_index;
pr_debug("%s:%d: find intr_type %u\n", __func__, __LINE__, intr_type);
*interrupt_id = UINT_MAX;
for (res_index = 0; res_index < 10; res_index++) {
enum ps3_interrupt_type t;
unsigned int id;
result = ps3_repository_read_dev_intr(repo->bus_index,
repo->dev_index, res_index, &t, &id);
if (result) {
pr_debug("%s:%d read_dev_intr failed\n",
__func__, __LINE__);
return result;
}
if (t == intr_type) {
*interrupt_id = id;
break;
}
}
if (res_index == 10)
return -ENODEV;
pr_debug("%s:%d: found intr_type %u at res_index %u\n",
__func__, __LINE__, intr_type, res_index);
return result;
}
int ps3_repository_find_reg(const struct ps3_repository_device *repo,
enum ps3_reg_type reg_type, u64 *bus_addr, u64 *len)
{
int result = 0;
unsigned int res_index;
pr_debug("%s:%d: find reg_type %u\n", __func__, __LINE__, reg_type);
*bus_addr = *len = 0;
for (res_index = 0; res_index < 10; res_index++) {
enum ps3_reg_type t;
u64 a;
u64 l;
result = ps3_repository_read_dev_reg(repo->bus_index,
repo->dev_index, res_index, &t, &a, &l);
if (result) {
pr_debug("%s:%d read_dev_reg failed\n",
__func__, __LINE__);
return result;
}
if (t == reg_type) {
*bus_addr = a;
*len = l;
break;
}
}
if (res_index == 10)
return -ENODEV;
pr_debug("%s:%d: found reg_type %u at res_index %u\n",
__func__, __LINE__, reg_type, res_index);
return result;
}
int ps3_repository_read_stor_dev_port(unsigned int bus_index,
unsigned int dev_index, u64 *port)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("port", 0),
0, port, NULL);
}
int ps3_repository_read_stor_dev_blk_size(unsigned int bus_index,
unsigned int dev_index, u64 *blk_size)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("blk_size", 0),
0, blk_size, NULL);
}
int ps3_repository_read_stor_dev_num_blocks(unsigned int bus_index,
unsigned int dev_index, u64 *num_blocks)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("n_blocks", 0),
0, num_blocks, NULL);
}
int ps3_repository_read_stor_dev_num_regions(unsigned int bus_index,
unsigned int dev_index, unsigned int *num_regions)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("n_regs", 0),
0, &v1, NULL);
*num_regions = v1;
return result;
}
int ps3_repository_read_stor_dev_region_id(unsigned int bus_index,
unsigned int dev_index, unsigned int region_index,
unsigned int *region_id)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("region", region_index),
make_field("id", 0),
&v1, NULL);
*region_id = v1;
return result;
}
int ps3_repository_read_stor_dev_region_size(unsigned int bus_index,
unsigned int dev_index, unsigned int region_index, u64 *region_size)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("region", region_index),
make_field("size", 0),
region_size, NULL);
}
int ps3_repository_read_stor_dev_region_start(unsigned int bus_index,
unsigned int dev_index, unsigned int region_index, u64 *region_start)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("bus", bus_index),
make_field("dev", dev_index),
make_field("region", region_index),
make_field("start", 0),
region_start, NULL);
}
int ps3_repository_read_stor_dev_info(unsigned int bus_index,
unsigned int dev_index, u64 *port, u64 *blk_size,
u64 *num_blocks, unsigned int *num_regions)
{
int result;
result = ps3_repository_read_stor_dev_port(bus_index, dev_index, port);
if (result)
return result;
result = ps3_repository_read_stor_dev_blk_size(bus_index, dev_index,
blk_size);
if (result)
return result;
result = ps3_repository_read_stor_dev_num_blocks(bus_index, dev_index,
num_blocks);
if (result)
return result;
result = ps3_repository_read_stor_dev_num_regions(bus_index, dev_index,
num_regions);
return result;
}
int ps3_repository_read_stor_dev_region(unsigned int bus_index,
unsigned int dev_index, unsigned int region_index,
unsigned int *region_id, u64 *region_start, u64 *region_size)
{
int result;
result = ps3_repository_read_stor_dev_region_id(bus_index, dev_index,
region_index, region_id);
if (result)
return result;
result = ps3_repository_read_stor_dev_region_start(bus_index, dev_index,
region_index, region_start);
if (result)
return result;
result = ps3_repository_read_stor_dev_region_size(bus_index, dev_index,
region_index, region_size);
return result;
}
/**
* ps3_repository_read_num_pu - Number of logical PU processors for this lpar.
*/
int ps3_repository_read_num_pu(u64 *num_pu)
{
*num_pu = 0;
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("pun", 0),
0, 0,
num_pu, NULL);
}
/**
* ps3_repository_read_pu_id - Read the logical PU id.
* @pu_index: Zero based index.
* @pu_id: The logical PU id.
*/
int ps3_repository_read_pu_id(unsigned int pu_index, u64 *pu_id)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("pu", pu_index),
0, 0,
pu_id, NULL);
}
int ps3_repository_read_rm_size(unsigned int ppe_id, u64 *rm_size)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("pu", 0),
ppe_id,
make_field("rm_size", 0),
rm_size, NULL);
}
int ps3_repository_read_region_total(u64 *region_total)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("rgntotal", 0),
0, 0,
region_total, NULL);
}
/**
* ps3_repository_read_mm_info - Read mm info for single pu system.
* @rm_base: Real mode memory base address.
* @rm_size: Real mode memory size.
* @region_total: Maximum memory region size.
*/
int ps3_repository_read_mm_info(u64 *rm_base, u64 *rm_size, u64 *region_total)
{
int result;
u64 ppe_id;
lv1_get_logical_ppe_id(&ppe_id);
*rm_base = 0;
result = ps3_repository_read_rm_size(ppe_id, rm_size);
return result ? result
: ps3_repository_read_region_total(region_total);
}
/**
* ps3_repository_read_num_spu_reserved - Number of physical spus reserved.
* @num_spu: Number of physical spus.
*/
int ps3_repository_read_num_spu_reserved(unsigned int *num_spu_reserved)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("spun", 0),
0, 0,
&v1, NULL);
*num_spu_reserved = v1;
return result;
}
/**
* ps3_repository_read_num_spu_resource_id - Number of spu resource reservations.
* @num_resource_id: Number of spu resource ids.
*/
int ps3_repository_read_num_spu_resource_id(unsigned int *num_resource_id)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("spursvn", 0),
0, 0,
&v1, NULL);
*num_resource_id = v1;
return result;
}
/**
* ps3_repository_read_spu_resource_id - spu resource reservation id value.
* @res_index: Resource reservation index.
* @resource_type: Resource reservation type.
* @resource_id: Resource reservation id.
*/
int ps3_repository_read_spu_resource_id(unsigned int res_index,
enum ps3_spu_resource_type *resource_type, unsigned int *resource_id)
{
int result;
u64 v1;
u64 v2;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("spursv", 0),
res_index,
0,
&v1, &v2);
*resource_type = v1;
*resource_id = v2;
return result;
}
static int ps3_repository_read_boot_dat_address(u64 *address)
{
return read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("boot_dat", 0),
make_field("address", 0),
0,
address, NULL);
}
int ps3_repository_read_boot_dat_size(unsigned int *size)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("boot_dat", 0),
make_field("size", 0),
0,
&v1, NULL);
*size = v1;
return result;
}
int ps3_repository_read_vuart_av_port(unsigned int *port)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("vir_uart", 0),
make_field("port", 0),
make_field("avset", 0),
&v1, NULL);
*port = v1;
return result;
}
int ps3_repository_read_vuart_sysmgr_port(unsigned int *port)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_CURRENT,
make_first_field("bi", 0),
make_field("vir_uart", 0),
make_field("port", 0),
make_field("sysmgr", 0),
&v1, NULL);
*port = v1;
return result;
}
/**
* ps3_repository_read_boot_dat_info - Get address and size of cell_ext_os_area.
* address: lpar address of cell_ext_os_area
* @size: size of cell_ext_os_area
*/
int ps3_repository_read_boot_dat_info(u64 *lpar_addr, unsigned int *size)
{
int result;
*size = 0;
result = ps3_repository_read_boot_dat_address(lpar_addr);
return result ? result
: ps3_repository_read_boot_dat_size(size);
}
/**
* ps3_repository_read_num_be - Number of physical BE processors in the system.
*/
int ps3_repository_read_num_be(unsigned int *num_be)
{
int result;
u64 v1;
result = read_node(PS3_LPAR_ID_PME,
make_first_field("ben", 0),
0,
0,
0,
&v1, NULL);
*num_be = v1;
return result;
}
/**
* ps3_repository_read_be_node_id - Read the physical BE processor node id.
* @be_index: Zero based index.
* @node_id: The BE processor node id.
*/
int ps3_repository_read_be_node_id(unsigned int be_index, u64 *node_id)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("be", be_index),
0,
0,
0,
node_id, NULL);
}
/**
* ps3_repository_read_be_id - Read the physical BE processor id.
* @node_id: The BE processor node id.
* @be_id: The BE processor id.
*/
int ps3_repository_read_be_id(u64 node_id, u64 *be_id)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("be", 0),
node_id,
0,
0,
be_id, NULL);
}
int ps3_repository_read_tb_freq(u64 node_id, u64 *tb_freq)
{
return read_node(PS3_LPAR_ID_PME,
make_first_field("be", 0),
node_id,
make_field("clock", 0),
0,
tb_freq, NULL);
}
int ps3_repository_read_be_tb_freq(unsigned int be_index, u64 *tb_freq)
{
int result;
u64 node_id;
*tb_freq = 0;
result = ps3_repository_read_be_node_id(be_index, &node_id);
return result ? result
: ps3_repository_read_tb_freq(node_id, tb_freq);
}
int ps3_repository_read_lpm_privileges(unsigned int be_index, u64 *lpar,
u64 *rights)
{
int result;
u64 node_id;
*lpar = 0;
*rights = 0;
result = ps3_repository_read_be_node_id(be_index, &node_id);
return result ? result
: read_node(PS3_LPAR_ID_PME,
make_first_field("be", 0),
node_id,
make_field("lpm", 0),
make_field("priv", 0),
lpar, rights);
}
#if defined(DEBUG)
int ps3_repository_dump_resource_info(const struct ps3_repository_device *repo)
{
int result = 0;
unsigned int res_index;
pr_debug(" -> %s:%d: (%u:%u)\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
for (res_index = 0; res_index < 10; res_index++) {
enum ps3_interrupt_type intr_type;
unsigned int interrupt_id;
result = ps3_repository_read_dev_intr(repo->bus_index,
repo->dev_index, res_index, &intr_type, &interrupt_id);
if (result) {
if (result != LV1_NO_ENTRY)
pr_debug("%s:%d ps3_repository_read_dev_intr"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
break;
}
pr_debug("%s:%d (%u:%u) intr_type %u, interrupt_id %u\n",
__func__, __LINE__, repo->bus_index, repo->dev_index,
intr_type, interrupt_id);
}
for (res_index = 0; res_index < 10; res_index++) {
enum ps3_reg_type reg_type;
u64 bus_addr;
u64 len;
result = ps3_repository_read_dev_reg(repo->bus_index,
repo->dev_index, res_index, ®_type, &bus_addr, &len);
if (result) {
if (result != LV1_NO_ENTRY)
pr_debug("%s:%d ps3_repository_read_dev_reg"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
break;
}
pr_debug("%s:%d (%u:%u) reg_type %u, bus_addr %lxh, len %lxh\n",
__func__, __LINE__, repo->bus_index, repo->dev_index,
reg_type, bus_addr, len);
}
pr_debug(" <- %s:%d\n", __func__, __LINE__);
return result;
}
static int dump_stor_dev_info(struct ps3_repository_device *repo)
{
int result = 0;
unsigned int num_regions, region_index;
u64 port, blk_size, num_blocks;
pr_debug(" -> %s:%d: (%u:%u)\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
result = ps3_repository_read_stor_dev_info(repo->bus_index,
repo->dev_index, &port, &blk_size, &num_blocks, &num_regions);
if (result) {
pr_debug("%s:%d ps3_repository_read_stor_dev_info"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
goto out;
}
pr_debug("%s:%d (%u:%u): port %lu, blk_size %lu, num_blocks "
"%lu, num_regions %u\n",
__func__, __LINE__, repo->bus_index, repo->dev_index, port,
blk_size, num_blocks, num_regions);
for (region_index = 0; region_index < num_regions; region_index++) {
unsigned int region_id;
u64 region_start, region_size;
result = ps3_repository_read_stor_dev_region(repo->bus_index,
repo->dev_index, region_index, ®ion_id,
®ion_start, ®ion_size);
if (result) {
pr_debug("%s:%d ps3_repository_read_stor_dev_region"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
break;
}
pr_debug("%s:%d (%u:%u) region_id %u, start %lxh, size %lxh\n",
__func__, __LINE__, repo->bus_index, repo->dev_index,
region_id, region_start, region_size);
}
out:
pr_debug(" <- %s:%d\n", __func__, __LINE__);
return result;
}
static int dump_device_info(struct ps3_repository_device *repo,
unsigned int num_dev)
{
int result = 0;
pr_debug(" -> %s:%d: bus_%u\n", __func__, __LINE__, repo->bus_index);
for (repo->dev_index = 0; repo->dev_index < num_dev;
repo->dev_index++) {
result = ps3_repository_read_dev_type(repo->bus_index,
repo->dev_index, &repo->dev_type);
if (result) {
pr_debug("%s:%d ps3_repository_read_dev_type"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
break;
}
result = ps3_repository_read_dev_id(repo->bus_index,
repo->dev_index, &repo->dev_id);
if (result) {
pr_debug("%s:%d ps3_repository_read_dev_id"
" (%u:%u) failed\n", __func__, __LINE__,
repo->bus_index, repo->dev_index);
continue;
}
pr_debug("%s:%d (%u:%u): dev_type %u, dev_id %lu\n", __func__,
__LINE__, repo->bus_index, repo->dev_index,
repo->dev_type, repo->dev_id);
ps3_repository_dump_resource_info(repo);
if (repo->bus_type == PS3_BUS_TYPE_STORAGE)
dump_stor_dev_info(repo);
}
pr_debug(" <- %s:%d\n", __func__, __LINE__);
return result;
}
int ps3_repository_dump_bus_info(void)
{
int result = 0;
struct ps3_repository_device repo;
pr_debug(" -> %s:%d\n", __func__, __LINE__);
memset(&repo, 0, sizeof(repo));
for (repo.bus_index = 0; repo.bus_index < 10; repo.bus_index++) {
unsigned int num_dev;
result = ps3_repository_read_bus_type(repo.bus_index,
&repo.bus_type);
if (result) {
pr_debug("%s:%d read_bus_type(%u) failed\n",
__func__, __LINE__, repo.bus_index);
break;
}
result = ps3_repository_read_bus_id(repo.bus_index,
&repo.bus_id);
if (result) {
pr_debug("%s:%d read_bus_id(%u) failed\n",
__func__, __LINE__, repo.bus_index);
continue;
}
if (repo.bus_index != repo.bus_id)
pr_debug("%s:%d bus_index != bus_id\n",
__func__, __LINE__);
result = ps3_repository_read_bus_num_dev(repo.bus_index,
&num_dev);
if (result) {
pr_debug("%s:%d read_bus_num_dev(%u) failed\n",
__func__, __LINE__, repo.bus_index);
continue;
}
pr_debug("%s:%d bus_%u: bus_type %u, bus_id %lu, num_dev %u\n",
__func__, __LINE__, repo.bus_index, repo.bus_type,
repo.bus_id, num_dev);
dump_device_info(&repo, num_dev);
}
pr_debug(" <- %s:%d\n", __func__, __LINE__);
return result;
}
#endif /* defined(DEBUG) */
| gpl-2.0 |
davidmueller13/valexKernel-lt03wifi | net/nfc/nci/core.c | 4786 | 21246 | /*
* The NFC Controller Interface is the communication protocol between an
* NFC Controller (NFCC) and a Device Host (DH).
*
* Copyright (C) 2011 Texas Instruments, Inc.
*
* Written by Ilan Elias <ilane@ti.com>
*
* Acknowledgements:
* This file is based on hci_core.c, which was written
* by Maxim Krasnyansky.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": %s: " fmt, __func__
#include <linux/types.h>
#include <linux/workqueue.h>
#include <linux/completion.h>
#include <linux/export.h>
#include <linux/sched.h>
#include <linux/bitops.h>
#include <linux/skbuff.h>
#include "../nfc.h"
#include <net/nfc/nci.h>
#include <net/nfc/nci_core.h>
#include <linux/nfc.h>
static void nci_cmd_work(struct work_struct *work);
static void nci_rx_work(struct work_struct *work);
static void nci_tx_work(struct work_struct *work);
/* ---- NCI requests ---- */
void nci_req_complete(struct nci_dev *ndev, int result)
{
if (ndev->req_status == NCI_REQ_PEND) {
ndev->req_result = result;
ndev->req_status = NCI_REQ_DONE;
complete(&ndev->req_completion);
}
}
static void nci_req_cancel(struct nci_dev *ndev, int err)
{
if (ndev->req_status == NCI_REQ_PEND) {
ndev->req_result = err;
ndev->req_status = NCI_REQ_CANCELED;
complete(&ndev->req_completion);
}
}
/* Execute request and wait for completion. */
static int __nci_request(struct nci_dev *ndev,
void (*req)(struct nci_dev *ndev, unsigned long opt),
unsigned long opt, __u32 timeout)
{
int rc = 0;
long completion_rc;
ndev->req_status = NCI_REQ_PEND;
init_completion(&ndev->req_completion);
req(ndev, opt);
completion_rc =
wait_for_completion_interruptible_timeout(&ndev->req_completion,
timeout);
pr_debug("wait_for_completion return %ld\n", completion_rc);
if (completion_rc > 0) {
switch (ndev->req_status) {
case NCI_REQ_DONE:
rc = nci_to_errno(ndev->req_result);
break;
case NCI_REQ_CANCELED:
rc = -ndev->req_result;
break;
default:
rc = -ETIMEDOUT;
break;
}
} else {
pr_err("wait_for_completion_interruptible_timeout failed %ld\n",
completion_rc);
rc = ((completion_rc == 0) ? (-ETIMEDOUT) : (completion_rc));
}
ndev->req_status = ndev->req_result = 0;
return rc;
}
static inline int nci_request(struct nci_dev *ndev,
void (*req)(struct nci_dev *ndev,
unsigned long opt),
unsigned long opt, __u32 timeout)
{
int rc;
if (!test_bit(NCI_UP, &ndev->flags))
return -ENETDOWN;
/* Serialize all requests */
mutex_lock(&ndev->req_lock);
rc = __nci_request(ndev, req, opt, timeout);
mutex_unlock(&ndev->req_lock);
return rc;
}
static void nci_reset_req(struct nci_dev *ndev, unsigned long opt)
{
struct nci_core_reset_cmd cmd;
cmd.reset_type = NCI_RESET_TYPE_RESET_CONFIG;
nci_send_cmd(ndev, NCI_OP_CORE_RESET_CMD, 1, &cmd);
}
static void nci_init_req(struct nci_dev *ndev, unsigned long opt)
{
nci_send_cmd(ndev, NCI_OP_CORE_INIT_CMD, 0, NULL);
}
static void nci_init_complete_req(struct nci_dev *ndev, unsigned long opt)
{
struct nci_rf_disc_map_cmd cmd;
struct disc_map_config *cfg = cmd.mapping_configs;
__u8 *num = &cmd.num_mapping_configs;
int i;
/* set rf mapping configurations */
*num = 0;
/* by default mapping is set to NCI_RF_INTERFACE_FRAME */
for (i = 0; i < ndev->num_supported_rf_interfaces; i++) {
if (ndev->supported_rf_interfaces[i] ==
NCI_RF_INTERFACE_ISO_DEP) {
cfg[*num].rf_protocol = NCI_RF_PROTOCOL_ISO_DEP;
cfg[*num].mode = NCI_DISC_MAP_MODE_POLL |
NCI_DISC_MAP_MODE_LISTEN;
cfg[*num].rf_interface = NCI_RF_INTERFACE_ISO_DEP;
(*num)++;
} else if (ndev->supported_rf_interfaces[i] ==
NCI_RF_INTERFACE_NFC_DEP) {
cfg[*num].rf_protocol = NCI_RF_PROTOCOL_NFC_DEP;
cfg[*num].mode = NCI_DISC_MAP_MODE_POLL |
NCI_DISC_MAP_MODE_LISTEN;
cfg[*num].rf_interface = NCI_RF_INTERFACE_NFC_DEP;
(*num)++;
}
if (*num == NCI_MAX_NUM_MAPPING_CONFIGS)
break;
}
nci_send_cmd(ndev, NCI_OP_RF_DISCOVER_MAP_CMD,
(1 + ((*num) * sizeof(struct disc_map_config))), &cmd);
}
static void nci_rf_discover_req(struct nci_dev *ndev, unsigned long opt)
{
struct nci_rf_disc_cmd cmd;
__u32 protocols = opt;
cmd.num_disc_configs = 0;
if ((cmd.num_disc_configs < NCI_MAX_NUM_RF_CONFIGS) &&
(protocols & NFC_PROTO_JEWEL_MASK
|| protocols & NFC_PROTO_MIFARE_MASK
|| protocols & NFC_PROTO_ISO14443_MASK
|| protocols & NFC_PROTO_NFC_DEP_MASK)) {
cmd.disc_configs[cmd.num_disc_configs].rf_tech_and_mode =
NCI_NFC_A_PASSIVE_POLL_MODE;
cmd.disc_configs[cmd.num_disc_configs].frequency = 1;
cmd.num_disc_configs++;
}
if ((cmd.num_disc_configs < NCI_MAX_NUM_RF_CONFIGS) &&
(protocols & NFC_PROTO_ISO14443_MASK)) {
cmd.disc_configs[cmd.num_disc_configs].rf_tech_and_mode =
NCI_NFC_B_PASSIVE_POLL_MODE;
cmd.disc_configs[cmd.num_disc_configs].frequency = 1;
cmd.num_disc_configs++;
}
if ((cmd.num_disc_configs < NCI_MAX_NUM_RF_CONFIGS) &&
(protocols & NFC_PROTO_FELICA_MASK
|| protocols & NFC_PROTO_NFC_DEP_MASK)) {
cmd.disc_configs[cmd.num_disc_configs].rf_tech_and_mode =
NCI_NFC_F_PASSIVE_POLL_MODE;
cmd.disc_configs[cmd.num_disc_configs].frequency = 1;
cmd.num_disc_configs++;
}
nci_send_cmd(ndev, NCI_OP_RF_DISCOVER_CMD,
(1 + (cmd.num_disc_configs * sizeof(struct disc_config))),
&cmd);
}
struct nci_rf_discover_select_param {
__u8 rf_discovery_id;
__u8 rf_protocol;
};
static void nci_rf_discover_select_req(struct nci_dev *ndev, unsigned long opt)
{
struct nci_rf_discover_select_param *param =
(struct nci_rf_discover_select_param *)opt;
struct nci_rf_discover_select_cmd cmd;
cmd.rf_discovery_id = param->rf_discovery_id;
cmd.rf_protocol = param->rf_protocol;
switch (cmd.rf_protocol) {
case NCI_RF_PROTOCOL_ISO_DEP:
cmd.rf_interface = NCI_RF_INTERFACE_ISO_DEP;
break;
case NCI_RF_PROTOCOL_NFC_DEP:
cmd.rf_interface = NCI_RF_INTERFACE_NFC_DEP;
break;
default:
cmd.rf_interface = NCI_RF_INTERFACE_FRAME;
break;
}
nci_send_cmd(ndev, NCI_OP_RF_DISCOVER_SELECT_CMD,
sizeof(struct nci_rf_discover_select_cmd), &cmd);
}
static void nci_rf_deactivate_req(struct nci_dev *ndev, unsigned long opt)
{
struct nci_rf_deactivate_cmd cmd;
cmd.type = NCI_DEACTIVATE_TYPE_IDLE_MODE;
nci_send_cmd(ndev, NCI_OP_RF_DEACTIVATE_CMD,
sizeof(struct nci_rf_deactivate_cmd), &cmd);
}
static int nci_open_device(struct nci_dev *ndev)
{
int rc = 0;
mutex_lock(&ndev->req_lock);
if (test_bit(NCI_UP, &ndev->flags)) {
rc = -EALREADY;
goto done;
}
if (ndev->ops->open(ndev)) {
rc = -EIO;
goto done;
}
atomic_set(&ndev->cmd_cnt, 1);
set_bit(NCI_INIT, &ndev->flags);
rc = __nci_request(ndev, nci_reset_req, 0,
msecs_to_jiffies(NCI_RESET_TIMEOUT));
if (!rc) {
rc = __nci_request(ndev, nci_init_req, 0,
msecs_to_jiffies(NCI_INIT_TIMEOUT));
}
if (!rc) {
rc = __nci_request(ndev, nci_init_complete_req, 0,
msecs_to_jiffies(NCI_INIT_TIMEOUT));
}
clear_bit(NCI_INIT, &ndev->flags);
if (!rc) {
set_bit(NCI_UP, &ndev->flags);
nci_clear_target_list(ndev);
atomic_set(&ndev->state, NCI_IDLE);
} else {
/* Init failed, cleanup */
skb_queue_purge(&ndev->cmd_q);
skb_queue_purge(&ndev->rx_q);
skb_queue_purge(&ndev->tx_q);
ndev->ops->close(ndev);
ndev->flags = 0;
}
done:
mutex_unlock(&ndev->req_lock);
return rc;
}
static int nci_close_device(struct nci_dev *ndev)
{
nci_req_cancel(ndev, ENODEV);
mutex_lock(&ndev->req_lock);
if (!test_and_clear_bit(NCI_UP, &ndev->flags)) {
del_timer_sync(&ndev->cmd_timer);
del_timer_sync(&ndev->data_timer);
mutex_unlock(&ndev->req_lock);
return 0;
}
/* Drop RX and TX queues */
skb_queue_purge(&ndev->rx_q);
skb_queue_purge(&ndev->tx_q);
/* Flush RX and TX wq */
flush_workqueue(ndev->rx_wq);
flush_workqueue(ndev->tx_wq);
/* Reset device */
skb_queue_purge(&ndev->cmd_q);
atomic_set(&ndev->cmd_cnt, 1);
set_bit(NCI_INIT, &ndev->flags);
__nci_request(ndev, nci_reset_req, 0,
msecs_to_jiffies(NCI_RESET_TIMEOUT));
clear_bit(NCI_INIT, &ndev->flags);
/* Flush cmd wq */
flush_workqueue(ndev->cmd_wq);
/* After this point our queues are empty
* and no works are scheduled. */
ndev->ops->close(ndev);
/* Clear flags */
ndev->flags = 0;
mutex_unlock(&ndev->req_lock);
return 0;
}
/* NCI command timer function */
static void nci_cmd_timer(unsigned long arg)
{
struct nci_dev *ndev = (void *) arg;
atomic_set(&ndev->cmd_cnt, 1);
queue_work(ndev->cmd_wq, &ndev->cmd_work);
}
/* NCI data exchange timer function */
static void nci_data_timer(unsigned long arg)
{
struct nci_dev *ndev = (void *) arg;
set_bit(NCI_DATA_EXCHANGE_TO, &ndev->flags);
queue_work(ndev->rx_wq, &ndev->rx_work);
}
static int nci_dev_up(struct nfc_dev *nfc_dev)
{
struct nci_dev *ndev = nfc_get_drvdata(nfc_dev);
return nci_open_device(ndev);
}
static int nci_dev_down(struct nfc_dev *nfc_dev)
{
struct nci_dev *ndev = nfc_get_drvdata(nfc_dev);
return nci_close_device(ndev);
}
static int nci_start_poll(struct nfc_dev *nfc_dev, __u32 protocols)
{
struct nci_dev *ndev = nfc_get_drvdata(nfc_dev);
int rc;
if ((atomic_read(&ndev->state) == NCI_DISCOVERY) ||
(atomic_read(&ndev->state) == NCI_W4_ALL_DISCOVERIES)) {
pr_err("unable to start poll, since poll is already active\n");
return -EBUSY;
}
if (ndev->target_active_prot) {
pr_err("there is an active target\n");
return -EBUSY;
}
if ((atomic_read(&ndev->state) == NCI_W4_HOST_SELECT) ||
(atomic_read(&ndev->state) == NCI_POLL_ACTIVE)) {
pr_debug("target active or w4 select, implicitly deactivate\n");
rc = nci_request(ndev, nci_rf_deactivate_req, 0,
msecs_to_jiffies(NCI_RF_DEACTIVATE_TIMEOUT));
if (rc)
return -EBUSY;
}
rc = nci_request(ndev, nci_rf_discover_req, protocols,
msecs_to_jiffies(NCI_RF_DISC_TIMEOUT));
if (!rc)
ndev->poll_prots = protocols;
return rc;
}
static void nci_stop_poll(struct nfc_dev *nfc_dev)
{
struct nci_dev *ndev = nfc_get_drvdata(nfc_dev);
if ((atomic_read(&ndev->state) != NCI_DISCOVERY) &&
(atomic_read(&ndev->state) != NCI_W4_ALL_DISCOVERIES)) {
pr_err("unable to stop poll, since poll is not active\n");
return;
}
nci_request(ndev, nci_rf_deactivate_req, 0,
msecs_to_jiffies(NCI_RF_DEACTIVATE_TIMEOUT));
}
static int nci_activate_target(struct nfc_dev *nfc_dev, __u32 target_idx,
__u32 protocol)
{
struct nci_dev *ndev = nfc_get_drvdata(nfc_dev);
struct nci_rf_discover_select_param param;
struct nfc_target *target = NULL;
int i;
int rc = 0;
pr_debug("target_idx %d, protocol 0x%x\n", target_idx, protocol);
if ((atomic_read(&ndev->state) != NCI_W4_HOST_SELECT) &&
(atomic_read(&ndev->state) != NCI_POLL_ACTIVE)) {
pr_err("there is no available target to activate\n");
return -EINVAL;
}
if (ndev->target_active_prot) {
pr_err("there is already an active target\n");
return -EBUSY;
}
for (i = 0; i < ndev->n_targets; i++) {
if (ndev->targets[i].idx == target_idx) {
target = &ndev->targets[i];
break;
}
}
if (!target) {
pr_err("unable to find the selected target\n");
return -EINVAL;
}
if (!(target->supported_protocols & (1 << protocol))) {
pr_err("target does not support the requested protocol 0x%x\n",
protocol);
return -EINVAL;
}
if (atomic_read(&ndev->state) == NCI_W4_HOST_SELECT) {
param.rf_discovery_id = target->idx;
if (protocol == NFC_PROTO_JEWEL)
param.rf_protocol = NCI_RF_PROTOCOL_T1T;
else if (protocol == NFC_PROTO_MIFARE)
param.rf_protocol = NCI_RF_PROTOCOL_T2T;
else if (protocol == NFC_PROTO_FELICA)
param.rf_protocol = NCI_RF_PROTOCOL_T3T;
else if (protocol == NFC_PROTO_ISO14443)
param.rf_protocol = NCI_RF_PROTOCOL_ISO_DEP;
else
param.rf_protocol = NCI_RF_PROTOCOL_NFC_DEP;
rc = nci_request(ndev, nci_rf_discover_select_req,
(unsigned long)¶m,
msecs_to_jiffies(NCI_RF_DISC_SELECT_TIMEOUT));
}
if (!rc)
ndev->target_active_prot = protocol;
return rc;
}
static void nci_deactivate_target(struct nfc_dev *nfc_dev, __u32 target_idx)
{
struct nci_dev *ndev = nfc_get_drvdata(nfc_dev);
pr_debug("target_idx %d\n", target_idx);
if (!ndev->target_active_prot) {
pr_err("unable to deactivate target, no active target\n");
return;
}
ndev->target_active_prot = 0;
if (atomic_read(&ndev->state) == NCI_POLL_ACTIVE) {
nci_request(ndev, nci_rf_deactivate_req, 0,
msecs_to_jiffies(NCI_RF_DEACTIVATE_TIMEOUT));
}
}
static int nci_data_exchange(struct nfc_dev *nfc_dev, __u32 target_idx,
struct sk_buff *skb,
data_exchange_cb_t cb, void *cb_context)
{
struct nci_dev *ndev = nfc_get_drvdata(nfc_dev);
int rc;
pr_debug("target_idx %d, len %d\n", target_idx, skb->len);
if (!ndev->target_active_prot) {
pr_err("unable to exchange data, no active target\n");
return -EINVAL;
}
if (test_and_set_bit(NCI_DATA_EXCHANGE, &ndev->flags))
return -EBUSY;
/* store cb and context to be used on receiving data */
ndev->data_exchange_cb = cb;
ndev->data_exchange_cb_context = cb_context;
rc = nci_send_data(ndev, NCI_STATIC_RF_CONN_ID, skb);
if (rc)
clear_bit(NCI_DATA_EXCHANGE, &ndev->flags);
return rc;
}
static struct nfc_ops nci_nfc_ops = {
.dev_up = nci_dev_up,
.dev_down = nci_dev_down,
.start_poll = nci_start_poll,
.stop_poll = nci_stop_poll,
.activate_target = nci_activate_target,
.deactivate_target = nci_deactivate_target,
.data_exchange = nci_data_exchange,
};
/* ---- Interface to NCI drivers ---- */
/**
* nci_allocate_device - allocate a new nci device
*
* @ops: device operations
* @supported_protocols: NFC protocols supported by the device
*/
struct nci_dev *nci_allocate_device(struct nci_ops *ops,
__u32 supported_protocols,
int tx_headroom, int tx_tailroom)
{
struct nci_dev *ndev;
pr_debug("supported_protocols 0x%x\n", supported_protocols);
if (!ops->open || !ops->close || !ops->send)
return NULL;
if (!supported_protocols)
return NULL;
ndev = kzalloc(sizeof(struct nci_dev), GFP_KERNEL);
if (!ndev)
return NULL;
ndev->ops = ops;
ndev->tx_headroom = tx_headroom;
ndev->tx_tailroom = tx_tailroom;
ndev->nfc_dev = nfc_allocate_device(&nci_nfc_ops,
supported_protocols,
tx_headroom + NCI_DATA_HDR_SIZE,
tx_tailroom);
if (!ndev->nfc_dev)
goto free_exit;
nfc_set_drvdata(ndev->nfc_dev, ndev);
return ndev;
free_exit:
kfree(ndev);
return NULL;
}
EXPORT_SYMBOL(nci_allocate_device);
/**
* nci_free_device - deallocate nci device
*
* @ndev: The nci device to deallocate
*/
void nci_free_device(struct nci_dev *ndev)
{
nfc_free_device(ndev->nfc_dev);
kfree(ndev);
}
EXPORT_SYMBOL(nci_free_device);
/**
* nci_register_device - register a nci device in the nfc subsystem
*
* @dev: The nci device to register
*/
int nci_register_device(struct nci_dev *ndev)
{
int rc;
struct device *dev = &ndev->nfc_dev->dev;
char name[32];
rc = nfc_register_device(ndev->nfc_dev);
if (rc)
goto exit;
ndev->flags = 0;
INIT_WORK(&ndev->cmd_work, nci_cmd_work);
snprintf(name, sizeof(name), "%s_nci_cmd_wq", dev_name(dev));
ndev->cmd_wq = create_singlethread_workqueue(name);
if (!ndev->cmd_wq) {
rc = -ENOMEM;
goto unreg_exit;
}
INIT_WORK(&ndev->rx_work, nci_rx_work);
snprintf(name, sizeof(name), "%s_nci_rx_wq", dev_name(dev));
ndev->rx_wq = create_singlethread_workqueue(name);
if (!ndev->rx_wq) {
rc = -ENOMEM;
goto destroy_cmd_wq_exit;
}
INIT_WORK(&ndev->tx_work, nci_tx_work);
snprintf(name, sizeof(name), "%s_nci_tx_wq", dev_name(dev));
ndev->tx_wq = create_singlethread_workqueue(name);
if (!ndev->tx_wq) {
rc = -ENOMEM;
goto destroy_rx_wq_exit;
}
skb_queue_head_init(&ndev->cmd_q);
skb_queue_head_init(&ndev->rx_q);
skb_queue_head_init(&ndev->tx_q);
setup_timer(&ndev->cmd_timer, nci_cmd_timer,
(unsigned long) ndev);
setup_timer(&ndev->data_timer, nci_data_timer,
(unsigned long) ndev);
mutex_init(&ndev->req_lock);
goto exit;
destroy_rx_wq_exit:
destroy_workqueue(ndev->rx_wq);
destroy_cmd_wq_exit:
destroy_workqueue(ndev->cmd_wq);
unreg_exit:
nfc_unregister_device(ndev->nfc_dev);
exit:
return rc;
}
EXPORT_SYMBOL(nci_register_device);
/**
* nci_unregister_device - unregister a nci device in the nfc subsystem
*
* @dev: The nci device to unregister
*/
void nci_unregister_device(struct nci_dev *ndev)
{
nci_close_device(ndev);
destroy_workqueue(ndev->cmd_wq);
destroy_workqueue(ndev->rx_wq);
destroy_workqueue(ndev->tx_wq);
nfc_unregister_device(ndev->nfc_dev);
}
EXPORT_SYMBOL(nci_unregister_device);
/**
* nci_recv_frame - receive frame from NCI drivers
*
* @skb: The sk_buff to receive
*/
int nci_recv_frame(struct sk_buff *skb)
{
struct nci_dev *ndev = (struct nci_dev *) skb->dev;
pr_debug("len %d\n", skb->len);
if (!ndev || (!test_bit(NCI_UP, &ndev->flags)
&& !test_bit(NCI_INIT, &ndev->flags))) {
kfree_skb(skb);
return -ENXIO;
}
/* Queue frame for rx worker thread */
skb_queue_tail(&ndev->rx_q, skb);
queue_work(ndev->rx_wq, &ndev->rx_work);
return 0;
}
EXPORT_SYMBOL(nci_recv_frame);
static int nci_send_frame(struct sk_buff *skb)
{
struct nci_dev *ndev = (struct nci_dev *) skb->dev;
pr_debug("len %d\n", skb->len);
if (!ndev) {
kfree_skb(skb);
return -ENODEV;
}
/* Get rid of skb owner, prior to sending to the driver. */
skb_orphan(skb);
return ndev->ops->send(skb);
}
/* Send NCI command */
int nci_send_cmd(struct nci_dev *ndev, __u16 opcode, __u8 plen, void *payload)
{
struct nci_ctrl_hdr *hdr;
struct sk_buff *skb;
pr_debug("opcode 0x%x, plen %d\n", opcode, plen);
skb = nci_skb_alloc(ndev, (NCI_CTRL_HDR_SIZE + plen), GFP_KERNEL);
if (!skb) {
pr_err("no memory for command\n");
return -ENOMEM;
}
hdr = (struct nci_ctrl_hdr *) skb_put(skb, NCI_CTRL_HDR_SIZE);
hdr->gid = nci_opcode_gid(opcode);
hdr->oid = nci_opcode_oid(opcode);
hdr->plen = plen;
nci_mt_set((__u8 *)hdr, NCI_MT_CMD_PKT);
nci_pbf_set((__u8 *)hdr, NCI_PBF_LAST);
if (plen)
memcpy(skb_put(skb, plen), payload, plen);
skb->dev = (void *) ndev;
skb_queue_tail(&ndev->cmd_q, skb);
queue_work(ndev->cmd_wq, &ndev->cmd_work);
return 0;
}
/* ---- NCI TX Data worker thread ---- */
static void nci_tx_work(struct work_struct *work)
{
struct nci_dev *ndev = container_of(work, struct nci_dev, tx_work);
struct sk_buff *skb;
pr_debug("credits_cnt %d\n", atomic_read(&ndev->credits_cnt));
/* Send queued tx data */
while (atomic_read(&ndev->credits_cnt)) {
skb = skb_dequeue(&ndev->tx_q);
if (!skb)
return;
/* Check if data flow control is used */
if (atomic_read(&ndev->credits_cnt) !=
NCI_DATA_FLOW_CONTROL_NOT_USED)
atomic_dec(&ndev->credits_cnt);
pr_debug("NCI TX: MT=data, PBF=%d, conn_id=%d, plen=%d\n",
nci_pbf(skb->data),
nci_conn_id(skb->data),
nci_plen(skb->data));
nci_send_frame(skb);
mod_timer(&ndev->data_timer,
jiffies + msecs_to_jiffies(NCI_DATA_TIMEOUT));
}
}
/* ----- NCI RX worker thread (data & control) ----- */
static void nci_rx_work(struct work_struct *work)
{
struct nci_dev *ndev = container_of(work, struct nci_dev, rx_work);
struct sk_buff *skb;
while ((skb = skb_dequeue(&ndev->rx_q))) {
/* Process frame */
switch (nci_mt(skb->data)) {
case NCI_MT_RSP_PKT:
nci_rsp_packet(ndev, skb);
break;
case NCI_MT_NTF_PKT:
nci_ntf_packet(ndev, skb);
break;
case NCI_MT_DATA_PKT:
nci_rx_data_packet(ndev, skb);
break;
default:
pr_err("unknown MT 0x%x\n", nci_mt(skb->data));
kfree_skb(skb);
break;
}
}
/* check if a data exchange timout has occurred */
if (test_bit(NCI_DATA_EXCHANGE_TO, &ndev->flags)) {
/* complete the data exchange transaction, if exists */
if (test_bit(NCI_DATA_EXCHANGE, &ndev->flags))
nci_data_exchange_complete(ndev, NULL, -ETIMEDOUT);
clear_bit(NCI_DATA_EXCHANGE_TO, &ndev->flags);
}
}
/* ----- NCI TX CMD worker thread ----- */
static void nci_cmd_work(struct work_struct *work)
{
struct nci_dev *ndev = container_of(work, struct nci_dev, cmd_work);
struct sk_buff *skb;
pr_debug("cmd_cnt %d\n", atomic_read(&ndev->cmd_cnt));
/* Send queued command */
if (atomic_read(&ndev->cmd_cnt)) {
skb = skb_dequeue(&ndev->cmd_q);
if (!skb)
return;
atomic_dec(&ndev->cmd_cnt);
pr_debug("NCI TX: MT=cmd, PBF=%d, GID=0x%x, OID=0x%x, plen=%d\n",
nci_pbf(skb->data),
nci_opcode_gid(nci_opcode(skb->data)),
nci_opcode_oid(nci_opcode(skb->data)),
nci_plen(skb->data));
nci_send_frame(skb);
mod_timer(&ndev->cmd_timer,
jiffies + msecs_to_jiffies(NCI_CMD_TIMEOUT));
}
}
| gpl-2.0 |
arunthomas/linux | arch/arm/mach-omap2/clockdomains44xx_data.c | 4786 | 13872 | /*
* OMAP4 Clock domains framework
*
* Copyright (C) 2009-2011 Texas Instruments, Inc.
* Copyright (C) 2009-2011 Nokia Corporation
*
* Abhijit Pagare (abhijitpagare@ti.com)
* Benoit Cousson (b-cousson@ti.com)
* Paul Walmsley (paul@pwsan.com)
*
* This file is automatically generated from the OMAP hardware databases.
* We respectfully ask that any modifications to this file be coordinated
* with the public linux-omap@vger.kernel.org mailing list and the
* authors above to ensure that the autogeneration scripts are kept
* up-to-date with the file contents.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/io.h>
#include "clockdomain.h"
#include "cm1_44xx.h"
#include "cm2_44xx.h"
#include "cm-regbits-44xx.h"
#include "prm44xx.h"
#include "prcm44xx.h"
#include "prcm_mpu44xx.h"
/* Static Dependencies for OMAP4 Clock Domains */
static struct clkdm_dep d2d_wkup_sleep_deps[] = {
{ .clkdm_name = "abe_clkdm" },
{ .clkdm_name = "ivahd_clkdm" },
{ .clkdm_name = "l3_1_clkdm" },
{ .clkdm_name = "l3_2_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ .clkdm_name = "l3_init_clkdm" },
{ .clkdm_name = "l4_cfg_clkdm" },
{ .clkdm_name = "l4_per_clkdm" },
{ NULL },
};
static struct clkdm_dep ducati_wkup_sleep_deps[] = {
{ .clkdm_name = "abe_clkdm" },
{ .clkdm_name = "ivahd_clkdm" },
{ .clkdm_name = "l3_1_clkdm" },
{ .clkdm_name = "l3_2_clkdm" },
{ .clkdm_name = "l3_dss_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ .clkdm_name = "l3_gfx_clkdm" },
{ .clkdm_name = "l3_init_clkdm" },
{ .clkdm_name = "l4_cfg_clkdm" },
{ .clkdm_name = "l4_per_clkdm" },
{ .clkdm_name = "l4_secure_clkdm" },
{ .clkdm_name = "l4_wkup_clkdm" },
{ .clkdm_name = "tesla_clkdm" },
{ NULL },
};
static struct clkdm_dep iss_wkup_sleep_deps[] = {
{ .clkdm_name = "ivahd_clkdm" },
{ .clkdm_name = "l3_1_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ NULL },
};
static struct clkdm_dep ivahd_wkup_sleep_deps[] = {
{ .clkdm_name = "l3_1_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ NULL },
};
static struct clkdm_dep l3_dma_wkup_sleep_deps[] = {
{ .clkdm_name = "abe_clkdm" },
{ .clkdm_name = "ducati_clkdm" },
{ .clkdm_name = "ivahd_clkdm" },
{ .clkdm_name = "l3_1_clkdm" },
{ .clkdm_name = "l3_dss_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ .clkdm_name = "l3_init_clkdm" },
{ .clkdm_name = "l4_cfg_clkdm" },
{ .clkdm_name = "l4_per_clkdm" },
{ .clkdm_name = "l4_secure_clkdm" },
{ .clkdm_name = "l4_wkup_clkdm" },
{ NULL },
};
static struct clkdm_dep l3_dss_wkup_sleep_deps[] = {
{ .clkdm_name = "ivahd_clkdm" },
{ .clkdm_name = "l3_2_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ NULL },
};
static struct clkdm_dep l3_gfx_wkup_sleep_deps[] = {
{ .clkdm_name = "ivahd_clkdm" },
{ .clkdm_name = "l3_1_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ NULL },
};
static struct clkdm_dep l3_init_wkup_sleep_deps[] = {
{ .clkdm_name = "abe_clkdm" },
{ .clkdm_name = "ivahd_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ .clkdm_name = "l4_cfg_clkdm" },
{ .clkdm_name = "l4_per_clkdm" },
{ .clkdm_name = "l4_secure_clkdm" },
{ .clkdm_name = "l4_wkup_clkdm" },
{ NULL },
};
static struct clkdm_dep l4_secure_wkup_sleep_deps[] = {
{ .clkdm_name = "l3_1_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ .clkdm_name = "l4_per_clkdm" },
{ NULL },
};
static struct clkdm_dep mpu_wkup_sleep_deps[] = {
{ .clkdm_name = "abe_clkdm" },
{ .clkdm_name = "ducati_clkdm" },
{ .clkdm_name = "ivahd_clkdm" },
{ .clkdm_name = "l3_1_clkdm" },
{ .clkdm_name = "l3_2_clkdm" },
{ .clkdm_name = "l3_dss_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ .clkdm_name = "l3_gfx_clkdm" },
{ .clkdm_name = "l3_init_clkdm" },
{ .clkdm_name = "l4_cfg_clkdm" },
{ .clkdm_name = "l4_per_clkdm" },
{ .clkdm_name = "l4_secure_clkdm" },
{ .clkdm_name = "l4_wkup_clkdm" },
{ .clkdm_name = "tesla_clkdm" },
{ NULL },
};
static struct clkdm_dep tesla_wkup_sleep_deps[] = {
{ .clkdm_name = "abe_clkdm" },
{ .clkdm_name = "ivahd_clkdm" },
{ .clkdm_name = "l3_1_clkdm" },
{ .clkdm_name = "l3_2_clkdm" },
{ .clkdm_name = "l3_emif_clkdm" },
{ .clkdm_name = "l3_init_clkdm" },
{ .clkdm_name = "l4_cfg_clkdm" },
{ .clkdm_name = "l4_per_clkdm" },
{ .clkdm_name = "l4_wkup_clkdm" },
{ NULL },
};
static struct clockdomain l4_cefuse_44xx_clkdm = {
.name = "l4_cefuse_clkdm",
.pwrdm = { .name = "cefuse_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CEFUSE_INST,
.clkdm_offs = OMAP4430_CM2_CEFUSE_CEFUSE_CDOFFS,
.flags = CLKDM_CAN_FORCE_WAKEUP | CLKDM_CAN_HWSUP,
};
static struct clockdomain l4_cfg_44xx_clkdm = {
.name = "l4_cfg_clkdm",
.pwrdm = { .name = "core_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CORE_INST,
.clkdm_offs = OMAP4430_CM2_CORE_L4CFG_CDOFFS,
.dep_bit = OMAP4430_L4CFG_STATDEP_SHIFT,
.flags = CLKDM_CAN_HWSUP,
};
static struct clockdomain tesla_44xx_clkdm = {
.name = "tesla_clkdm",
.pwrdm = { .name = "tesla_pwrdm" },
.prcm_partition = OMAP4430_CM1_PARTITION,
.cm_inst = OMAP4430_CM1_TESLA_INST,
.clkdm_offs = OMAP4430_CM1_TESLA_TESLA_CDOFFS,
.dep_bit = OMAP4430_TESLA_STATDEP_SHIFT,
.wkdep_srcs = tesla_wkup_sleep_deps,
.sleepdep_srcs = tesla_wkup_sleep_deps,
.flags = CLKDM_CAN_HWSUP_SWSUP,
};
static struct clockdomain l3_gfx_44xx_clkdm = {
.name = "l3_gfx_clkdm",
.pwrdm = { .name = "gfx_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_GFX_INST,
.clkdm_offs = OMAP4430_CM2_GFX_GFX_CDOFFS,
.dep_bit = OMAP4430_GFX_STATDEP_SHIFT,
.wkdep_srcs = l3_gfx_wkup_sleep_deps,
.sleepdep_srcs = l3_gfx_wkup_sleep_deps,
.flags = CLKDM_CAN_HWSUP_SWSUP,
};
static struct clockdomain ivahd_44xx_clkdm = {
.name = "ivahd_clkdm",
.pwrdm = { .name = "ivahd_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_IVAHD_INST,
.clkdm_offs = OMAP4430_CM2_IVAHD_IVAHD_CDOFFS,
.dep_bit = OMAP4430_IVAHD_STATDEP_SHIFT,
.wkdep_srcs = ivahd_wkup_sleep_deps,
.sleepdep_srcs = ivahd_wkup_sleep_deps,
.flags = CLKDM_CAN_HWSUP_SWSUP,
};
static struct clockdomain l4_secure_44xx_clkdm = {
.name = "l4_secure_clkdm",
.pwrdm = { .name = "l4per_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_L4PER_INST,
.clkdm_offs = OMAP4430_CM2_L4PER_L4SEC_CDOFFS,
.dep_bit = OMAP4430_L4SEC_STATDEP_SHIFT,
.wkdep_srcs = l4_secure_wkup_sleep_deps,
.sleepdep_srcs = l4_secure_wkup_sleep_deps,
.flags = CLKDM_CAN_HWSUP_SWSUP,
};
static struct clockdomain l4_per_44xx_clkdm = {
.name = "l4_per_clkdm",
.pwrdm = { .name = "l4per_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_L4PER_INST,
.clkdm_offs = OMAP4430_CM2_L4PER_L4PER_CDOFFS,
.dep_bit = OMAP4430_L4PER_STATDEP_SHIFT,
.flags = CLKDM_CAN_HWSUP_SWSUP,
};
static struct clockdomain abe_44xx_clkdm = {
.name = "abe_clkdm",
.pwrdm = { .name = "abe_pwrdm" },
.prcm_partition = OMAP4430_CM1_PARTITION,
.cm_inst = OMAP4430_CM1_ABE_INST,
.clkdm_offs = OMAP4430_CM1_ABE_ABE_CDOFFS,
.dep_bit = OMAP4430_ABE_STATDEP_SHIFT,
.flags = CLKDM_CAN_HWSUP_SWSUP,
};
static struct clockdomain l3_instr_44xx_clkdm = {
.name = "l3_instr_clkdm",
.pwrdm = { .name = "core_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CORE_INST,
.clkdm_offs = OMAP4430_CM2_CORE_L3INSTR_CDOFFS,
};
static struct clockdomain l3_init_44xx_clkdm = {
.name = "l3_init_clkdm",
.pwrdm = { .name = "l3init_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_L3INIT_INST,
.clkdm_offs = OMAP4430_CM2_L3INIT_L3INIT_CDOFFS,
.dep_bit = OMAP4430_L3INIT_STATDEP_SHIFT,
.wkdep_srcs = l3_init_wkup_sleep_deps,
.sleepdep_srcs = l3_init_wkup_sleep_deps,
.flags = CLKDM_CAN_HWSUP_SWSUP,
};
static struct clockdomain d2d_44xx_clkdm = {
.name = "d2d_clkdm",
.pwrdm = { .name = "core_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CORE_INST,
.clkdm_offs = OMAP4430_CM2_CORE_D2D_CDOFFS,
.wkdep_srcs = d2d_wkup_sleep_deps,
.sleepdep_srcs = d2d_wkup_sleep_deps,
.flags = CLKDM_CAN_FORCE_WAKEUP | CLKDM_CAN_HWSUP,
};
static struct clockdomain mpu0_44xx_clkdm = {
.name = "mpu0_clkdm",
.pwrdm = { .name = "cpu0_pwrdm" },
.prcm_partition = OMAP4430_PRCM_MPU_PARTITION,
.cm_inst = OMAP4430_PRCM_MPU_CPU0_INST,
.clkdm_offs = OMAP4430_PRCM_MPU_CPU0_CPU0_CDOFFS,
.flags = CLKDM_CAN_FORCE_WAKEUP | CLKDM_CAN_HWSUP,
};
static struct clockdomain mpu1_44xx_clkdm = {
.name = "mpu1_clkdm",
.pwrdm = { .name = "cpu1_pwrdm" },
.prcm_partition = OMAP4430_PRCM_MPU_PARTITION,
.cm_inst = OMAP4430_PRCM_MPU_CPU1_INST,
.clkdm_offs = OMAP4430_PRCM_MPU_CPU1_CPU1_CDOFFS,
.flags = CLKDM_CAN_FORCE_WAKEUP | CLKDM_CAN_HWSUP,
};
static struct clockdomain l3_emif_44xx_clkdm = {
.name = "l3_emif_clkdm",
.pwrdm = { .name = "core_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CORE_INST,
.clkdm_offs = OMAP4430_CM2_CORE_MEMIF_CDOFFS,
.dep_bit = OMAP4430_MEMIF_STATDEP_SHIFT,
.flags = CLKDM_CAN_FORCE_WAKEUP | CLKDM_CAN_HWSUP,
};
static struct clockdomain l4_ao_44xx_clkdm = {
.name = "l4_ao_clkdm",
.pwrdm = { .name = "always_on_core_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_ALWAYS_ON_INST,
.clkdm_offs = OMAP4430_CM2_ALWAYS_ON_ALWON_CDOFFS,
.flags = CLKDM_CAN_FORCE_WAKEUP | CLKDM_CAN_HWSUP,
};
static struct clockdomain ducati_44xx_clkdm = {
.name = "ducati_clkdm",
.pwrdm = { .name = "core_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CORE_INST,
.clkdm_offs = OMAP4430_CM2_CORE_DUCATI_CDOFFS,
.dep_bit = OMAP4430_DUCATI_STATDEP_SHIFT,
.wkdep_srcs = ducati_wkup_sleep_deps,
.sleepdep_srcs = ducati_wkup_sleep_deps,
.flags = CLKDM_CAN_HWSUP_SWSUP,
};
static struct clockdomain mpu_44xx_clkdm = {
.name = "mpuss_clkdm",
.pwrdm = { .name = "mpu_pwrdm" },
.prcm_partition = OMAP4430_CM1_PARTITION,
.cm_inst = OMAP4430_CM1_MPU_INST,
.clkdm_offs = OMAP4430_CM1_MPU_MPU_CDOFFS,
.wkdep_srcs = mpu_wkup_sleep_deps,
.sleepdep_srcs = mpu_wkup_sleep_deps,
.flags = CLKDM_CAN_FORCE_WAKEUP | CLKDM_CAN_HWSUP,
};
static struct clockdomain l3_2_44xx_clkdm = {
.name = "l3_2_clkdm",
.pwrdm = { .name = "core_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CORE_INST,
.clkdm_offs = OMAP4430_CM2_CORE_L3_2_CDOFFS,
.dep_bit = OMAP4430_L3_2_STATDEP_SHIFT,
.flags = CLKDM_CAN_HWSUP,
};
static struct clockdomain l3_1_44xx_clkdm = {
.name = "l3_1_clkdm",
.pwrdm = { .name = "core_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CORE_INST,
.clkdm_offs = OMAP4430_CM2_CORE_L3_1_CDOFFS,
.dep_bit = OMAP4430_L3_1_STATDEP_SHIFT,
.flags = CLKDM_CAN_HWSUP,
};
static struct clockdomain iss_44xx_clkdm = {
.name = "iss_clkdm",
.pwrdm = { .name = "cam_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CAM_INST,
.clkdm_offs = OMAP4430_CM2_CAM_CAM_CDOFFS,
.wkdep_srcs = iss_wkup_sleep_deps,
.sleepdep_srcs = iss_wkup_sleep_deps,
.flags = CLKDM_CAN_SWSUP,
};
static struct clockdomain l3_dss_44xx_clkdm = {
.name = "l3_dss_clkdm",
.pwrdm = { .name = "dss_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_DSS_INST,
.clkdm_offs = OMAP4430_CM2_DSS_DSS_CDOFFS,
.dep_bit = OMAP4430_DSS_STATDEP_SHIFT,
.wkdep_srcs = l3_dss_wkup_sleep_deps,
.sleepdep_srcs = l3_dss_wkup_sleep_deps,
.flags = CLKDM_CAN_HWSUP_SWSUP,
};
static struct clockdomain l4_wkup_44xx_clkdm = {
.name = "l4_wkup_clkdm",
.pwrdm = { .name = "wkup_pwrdm" },
.prcm_partition = OMAP4430_PRM_PARTITION,
.cm_inst = OMAP4430_PRM_WKUP_CM_INST,
.clkdm_offs = OMAP4430_PRM_WKUP_CM_WKUP_CDOFFS,
.dep_bit = OMAP4430_L4WKUP_STATDEP_SHIFT,
.flags = CLKDM_CAN_HWSUP | CLKDM_ACTIVE_WITH_MPU,
};
static struct clockdomain emu_sys_44xx_clkdm = {
.name = "emu_sys_clkdm",
.pwrdm = { .name = "emu_pwrdm" },
.prcm_partition = OMAP4430_PRM_PARTITION,
.cm_inst = OMAP4430_PRM_EMU_CM_INST,
.clkdm_offs = OMAP4430_PRM_EMU_CM_EMU_CDOFFS,
.flags = (CLKDM_CAN_ENABLE_AUTO | CLKDM_CAN_FORCE_WAKEUP |
CLKDM_MISSING_IDLE_REPORTING),
};
static struct clockdomain l3_dma_44xx_clkdm = {
.name = "l3_dma_clkdm",
.pwrdm = { .name = "core_pwrdm" },
.prcm_partition = OMAP4430_CM2_PARTITION,
.cm_inst = OMAP4430_CM2_CORE_INST,
.clkdm_offs = OMAP4430_CM2_CORE_SDMA_CDOFFS,
.wkdep_srcs = l3_dma_wkup_sleep_deps,
.sleepdep_srcs = l3_dma_wkup_sleep_deps,
.flags = CLKDM_CAN_FORCE_WAKEUP | CLKDM_CAN_HWSUP,
};
/* As clockdomains are added or removed above, this list must also be changed */
static struct clockdomain *clockdomains_omap44xx[] __initdata = {
&l4_cefuse_44xx_clkdm,
&l4_cfg_44xx_clkdm,
&tesla_44xx_clkdm,
&l3_gfx_44xx_clkdm,
&ivahd_44xx_clkdm,
&l4_secure_44xx_clkdm,
&l4_per_44xx_clkdm,
&abe_44xx_clkdm,
&l3_instr_44xx_clkdm,
&l3_init_44xx_clkdm,
&d2d_44xx_clkdm,
&mpu0_44xx_clkdm,
&mpu1_44xx_clkdm,
&l3_emif_44xx_clkdm,
&l4_ao_44xx_clkdm,
&ducati_44xx_clkdm,
&mpu_44xx_clkdm,
&l3_2_44xx_clkdm,
&l3_1_44xx_clkdm,
&iss_44xx_clkdm,
&l3_dss_44xx_clkdm,
&l4_wkup_44xx_clkdm,
&emu_sys_44xx_clkdm,
&l3_dma_44xx_clkdm,
NULL
};
void __init omap44xx_clockdomains_init(void)
{
clkdm_register_platform_funcs(&omap4_clkdm_operations);
clkdm_register_clkdms(clockdomains_omap44xx);
clkdm_complete_init();
}
| gpl-2.0 |
D380/android_kernel_lge_msm8226 | arch/arm/mach-zynq/timer.c | 5554 | 9036 | /*
* This file contains driver for the Xilinx PS Timer Counter IP.
*
* Copyright (C) 2011 Xilinx
*
* based on arch/mips/kernel/time.c timer driver
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/types.h>
#include <linux/clocksource.h>
#include <linux/clockchips.h>
#include <linux/io.h>
#include <asm/mach/time.h>
#include <mach/zynq_soc.h>
#include "common.h"
#define IRQ_TIMERCOUNTER0 42
/*
* This driver configures the 2 16-bit count-up timers as follows:
*
* T1: Timer 1, clocksource for generic timekeeping
* T2: Timer 2, clockevent source for hrtimers
* T3: Timer 3, <unused>
*
* The input frequency to the timer module for emulation is 2.5MHz which is
* common to all the timer channels (T1, T2, and T3). With a pre-scaler of 32,
* the timers are clocked at 78.125KHz (12.8 us resolution).
*
* The input frequency to the timer module in silicon will be 200MHz. With the
* pre-scaler of 32, the timers are clocked at 6.25MHz (160ns resolution).
*/
#define XTTCPSS_CLOCKSOURCE 0 /* Timer 1 as a generic timekeeping */
#define XTTCPSS_CLOCKEVENT 1 /* Timer 2 as a clock event */
#define XTTCPSS_TIMER_BASE TTC0_BASE
#define XTTCPCC_EVENT_TIMER_IRQ (IRQ_TIMERCOUNTER0 + 1)
/*
* Timer Register Offset Definitions of Timer 1, Increment base address by 4
* and use same offsets for Timer 2
*/
#define XTTCPSS_CLK_CNTRL_OFFSET 0x00 /* Clock Control Reg, RW */
#define XTTCPSS_CNT_CNTRL_OFFSET 0x0C /* Counter Control Reg, RW */
#define XTTCPSS_COUNT_VAL_OFFSET 0x18 /* Counter Value Reg, RO */
#define XTTCPSS_INTR_VAL_OFFSET 0x24 /* Interval Count Reg, RW */
#define XTTCPSS_MATCH_1_OFFSET 0x30 /* Match 1 Value Reg, RW */
#define XTTCPSS_MATCH_2_OFFSET 0x3C /* Match 2 Value Reg, RW */
#define XTTCPSS_MATCH_3_OFFSET 0x48 /* Match 3 Value Reg, RW */
#define XTTCPSS_ISR_OFFSET 0x54 /* Interrupt Status Reg, RO */
#define XTTCPSS_IER_OFFSET 0x60 /* Interrupt Enable Reg, RW */
#define XTTCPSS_CNT_CNTRL_DISABLE_MASK 0x1
/* Setup the timers to use pre-scaling */
#define TIMER_RATE (PERIPHERAL_CLOCK_RATE / 32)
/**
* struct xttcpss_timer - This definition defines local timer structure
*
* @base_addr: Base address of timer
**/
struct xttcpss_timer {
void __iomem *base_addr;
};
static struct xttcpss_timer timers[2];
static struct clock_event_device xttcpss_clockevent;
/**
* xttcpss_set_interval - Set the timer interval value
*
* @timer: Pointer to the timer instance
* @cycles: Timer interval ticks
**/
static void xttcpss_set_interval(struct xttcpss_timer *timer,
unsigned long cycles)
{
u32 ctrl_reg;
/* Disable the counter, set the counter value and re-enable counter */
ctrl_reg = __raw_readl(timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET);
ctrl_reg |= XTTCPSS_CNT_CNTRL_DISABLE_MASK;
__raw_writel(ctrl_reg, timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET);
__raw_writel(cycles, timer->base_addr + XTTCPSS_INTR_VAL_OFFSET);
/* Reset the counter (0x10) so that it starts from 0, one-shot
mode makes this needed for timing to be right. */
ctrl_reg |= 0x10;
ctrl_reg &= ~XTTCPSS_CNT_CNTRL_DISABLE_MASK;
__raw_writel(ctrl_reg, timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET);
}
/**
* xttcpss_clock_event_interrupt - Clock event timer interrupt handler
*
* @irq: IRQ number of the Timer
* @dev_id: void pointer to the xttcpss_timer instance
*
* returns: Always IRQ_HANDLED - success
**/
static irqreturn_t xttcpss_clock_event_interrupt(int irq, void *dev_id)
{
struct clock_event_device *evt = &xttcpss_clockevent;
struct xttcpss_timer *timer = dev_id;
/* Acknowledge the interrupt and call event handler */
__raw_writel(__raw_readl(timer->base_addr + XTTCPSS_ISR_OFFSET),
timer->base_addr + XTTCPSS_ISR_OFFSET);
evt->event_handler(evt);
return IRQ_HANDLED;
}
static struct irqaction event_timer_irq = {
.name = "xttcpss clockevent",
.flags = IRQF_DISABLED | IRQF_TIMER,
.handler = xttcpss_clock_event_interrupt,
};
/**
* xttcpss_timer_hardware_init - Initialize the timer hardware
*
* Initialize the hardware to start the clock source, get the clock
* event timer ready to use, and hook up the interrupt.
**/
static void __init xttcpss_timer_hardware_init(void)
{
/* Setup the clock source counter to be an incrementing counter
* with no interrupt and it rolls over at 0xFFFF. Pre-scale
it by 32 also. Let it start running now.
*/
timers[XTTCPSS_CLOCKSOURCE].base_addr = XTTCPSS_TIMER_BASE;
__raw_writel(0x0, timers[XTTCPSS_CLOCKSOURCE].base_addr +
XTTCPSS_IER_OFFSET);
__raw_writel(0x9, timers[XTTCPSS_CLOCKSOURCE].base_addr +
XTTCPSS_CLK_CNTRL_OFFSET);
__raw_writel(0x10, timers[XTTCPSS_CLOCKSOURCE].base_addr +
XTTCPSS_CNT_CNTRL_OFFSET);
/* Setup the clock event timer to be an interval timer which
* is prescaled by 32 using the interval interrupt. Leave it
* disabled for now.
*/
timers[XTTCPSS_CLOCKEVENT].base_addr = XTTCPSS_TIMER_BASE + 4;
__raw_writel(0x23, timers[XTTCPSS_CLOCKEVENT].base_addr +
XTTCPSS_CNT_CNTRL_OFFSET);
__raw_writel(0x9, timers[XTTCPSS_CLOCKEVENT].base_addr +
XTTCPSS_CLK_CNTRL_OFFSET);
__raw_writel(0x1, timers[XTTCPSS_CLOCKEVENT].base_addr +
XTTCPSS_IER_OFFSET);
/* Setup IRQ the clock event timer */
event_timer_irq.dev_id = &timers[XTTCPSS_CLOCKEVENT];
setup_irq(XTTCPCC_EVENT_TIMER_IRQ, &event_timer_irq);
}
/**
* __raw_readl_cycles - Reads the timer counter register
*
* returns: Current timer counter register value
**/
static cycle_t __raw_readl_cycles(struct clocksource *cs)
{
struct xttcpss_timer *timer = &timers[XTTCPSS_CLOCKSOURCE];
return (cycle_t)__raw_readl(timer->base_addr +
XTTCPSS_COUNT_VAL_OFFSET);
}
/*
* Instantiate and initialize the clock source structure
*/
static struct clocksource clocksource_xttcpss = {
.name = "xttcpss_timer1",
.rating = 200, /* Reasonable clock source */
.read = __raw_readl_cycles,
.mask = CLOCKSOURCE_MASK(16),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
/**
* xttcpss_set_next_event - Sets the time interval for next event
*
* @cycles: Timer interval ticks
* @evt: Address of clock event instance
*
* returns: Always 0 - success
**/
static int xttcpss_set_next_event(unsigned long cycles,
struct clock_event_device *evt)
{
struct xttcpss_timer *timer = &timers[XTTCPSS_CLOCKEVENT];
xttcpss_set_interval(timer, cycles);
return 0;
}
/**
* xttcpss_set_mode - Sets the mode of timer
*
* @mode: Mode to be set
* @evt: Address of clock event instance
**/
static void xttcpss_set_mode(enum clock_event_mode mode,
struct clock_event_device *evt)
{
struct xttcpss_timer *timer = &timers[XTTCPSS_CLOCKEVENT];
u32 ctrl_reg;
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
xttcpss_set_interval(timer, TIMER_RATE / HZ);
break;
case CLOCK_EVT_MODE_ONESHOT:
case CLOCK_EVT_MODE_UNUSED:
case CLOCK_EVT_MODE_SHUTDOWN:
ctrl_reg = __raw_readl(timer->base_addr +
XTTCPSS_CNT_CNTRL_OFFSET);
ctrl_reg |= XTTCPSS_CNT_CNTRL_DISABLE_MASK;
__raw_writel(ctrl_reg,
timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET);
break;
case CLOCK_EVT_MODE_RESUME:
ctrl_reg = __raw_readl(timer->base_addr +
XTTCPSS_CNT_CNTRL_OFFSET);
ctrl_reg &= ~XTTCPSS_CNT_CNTRL_DISABLE_MASK;
__raw_writel(ctrl_reg,
timer->base_addr + XTTCPSS_CNT_CNTRL_OFFSET);
break;
}
}
/*
* Instantiate and initialize the clock event structure
*/
static struct clock_event_device xttcpss_clockevent = {
.name = "xttcpss_timer2",
.features = CLOCK_EVT_FEAT_PERIODIC | CLOCK_EVT_FEAT_ONESHOT,
.set_next_event = xttcpss_set_next_event,
.set_mode = xttcpss_set_mode,
.rating = 200,
};
/**
* xttcpss_timer_init - Initialize the timer
*
* Initializes the timer hardware and register the clock source and clock event
* timers with Linux kernal timer framework
**/
static void __init xttcpss_timer_init(void)
{
xttcpss_timer_hardware_init();
clocksource_register_hz(&clocksource_xttcpss, TIMER_RATE);
/* Calculate the parameters to allow the clockevent to operate using
integer math
*/
clockevents_calc_mult_shift(&xttcpss_clockevent, TIMER_RATE, 4);
xttcpss_clockevent.max_delta_ns =
clockevent_delta2ns(0xfffe, &xttcpss_clockevent);
xttcpss_clockevent.min_delta_ns =
clockevent_delta2ns(1, &xttcpss_clockevent);
/* Indicate that clock event is on 1st CPU as SMP boot needs it */
xttcpss_clockevent.cpumask = cpumask_of(0);
clockevents_register_device(&xttcpss_clockevent);
}
/*
* Instantiate and initialize the system timer structure
*/
struct sys_timer xttcpss_sys_timer = {
.init = xttcpss_timer_init,
};
| gpl-2.0 |
Ca1ne/Enoch213 | drivers/staging/vt6655/tether.c | 8370 | 2852 | /*
* Copyright (c) 2003 VIA Networking, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*
* File: tether.c
*
* Purpose:
*
* Author: Tevin Chen
*
* Date: May 21, 1996
*
* Functions:
* ETHbyGetHashIndexByCrc32 - Caculate multicast hash value by CRC32
* ETHbIsBufferCrc32Ok - Check CRC value of the buffer if Ok or not
*
* Revision History:
*
*/
#include "device.h"
#include "tmacro.h"
#include "tcrc.h"
#include "tether.h"
/*--------------------- Static Definitions -------------------------*/
/*--------------------- Static Classes ----------------------------*/
/*--------------------- Static Variables --------------------------*/
/*--------------------- Static Functions --------------------------*/
/*--------------------- Export Variables --------------------------*/
/*
* Description: Caculate multicast hash value by CRC32
*
* Parameters:
* In:
* pbyMultiAddr - Multicast Address
* Out:
* none
*
* Return Value: Hash value
*
*/
unsigned char ETHbyGetHashIndexByCrc32 (unsigned char *pbyMultiAddr)
{
int ii;
unsigned char byTmpHash;
unsigned char byHash = 0;
// get the least 6-bits from CRC generator
byTmpHash = (unsigned char)(CRCdwCrc32(pbyMultiAddr, ETH_ALEN,
0xFFFFFFFFL) & 0x3F);
// reverse most bit to least bit
for (ii = 0; ii < (sizeof(byTmpHash) * 8); ii++) {
byHash <<= 1;
if (byTmpHash & 0x01)
byHash |= 1;
byTmpHash >>= 1;
}
// adjust 6-bits to the right most
return (byHash >> 2);
}
/*
* Description: Check CRC value of the buffer if Ok or not
*
* Parameters:
* In:
* pbyBuffer - pointer of buffer (normally is rx buffer)
* cbFrameLength - length of buffer, including CRC portion
* Out:
* none
*
* Return Value: true if ok; false if error.
*
*/
bool ETHbIsBufferCrc32Ok (unsigned char *pbyBuffer, unsigned int cbFrameLength)
{
unsigned long dwCRC;
dwCRC = CRCdwGetCrc32(pbyBuffer, cbFrameLength - 4);
if (cpu_to_le32(*((unsigned long *)(pbyBuffer + cbFrameLength - 4))) != dwCRC) {
return false;
}
return true;
}
| gpl-2.0 |
HomuHomu/GT-N7000-ICS-kernel | arch/alpha/kernel/core_marvel.c | 13234 | 25107 | /*
* linux/arch/alpha/kernel/core_marvel.c
*
* Code common to all Marvel based systems.
*/
#define __EXTERN_INLINE inline
#include <asm/io.h>
#include <asm/core_marvel.h>
#undef __EXTERN_INLINE
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/vmalloc.h>
#include <linux/mc146818rtc.h>
#include <linux/rtc.h>
#include <linux/module.h>
#include <linux/bootmem.h>
#include <asm/ptrace.h>
#include <asm/smp.h>
#include <asm/gct.h>
#include <asm/pgalloc.h>
#include <asm/tlbflush.h>
#include <asm/rtc.h>
#include <asm/vga.h>
#include "proto.h"
#include "pci_impl.h"
/*
* Debug helpers
*/
#define DEBUG_CONFIG 0
#if DEBUG_CONFIG
# define DBG_CFG(args) printk args
#else
# define DBG_CFG(args)
#endif
/*
* Private data
*/
static struct io7 *io7_head = NULL;
/*
* Helper functions
*/
static unsigned long __attribute__ ((unused))
read_ev7_csr(int pe, unsigned long offset)
{
ev7_csr *ev7csr = EV7_CSR_KERN(pe, offset);
unsigned long q;
mb();
q = ev7csr->csr;
mb();
return q;
}
static void __attribute__ ((unused))
write_ev7_csr(int pe, unsigned long offset, unsigned long q)
{
ev7_csr *ev7csr = EV7_CSR_KERN(pe, offset);
mb();
ev7csr->csr = q;
mb();
}
static char * __init
mk_resource_name(int pe, int port, char *str)
{
char tmp[80];
char *name;
sprintf(tmp, "PCI %s PE %d PORT %d", str, pe, port);
name = alloc_bootmem(strlen(tmp) + 1);
strcpy(name, tmp);
return name;
}
inline struct io7 *
marvel_next_io7(struct io7 *prev)
{
return (prev ? prev->next : io7_head);
}
struct io7 *
marvel_find_io7(int pe)
{
struct io7 *io7;
for (io7 = io7_head; io7 && io7->pe != pe; io7 = io7->next)
continue;
return io7;
}
static struct io7 * __init
alloc_io7(unsigned int pe)
{
struct io7 *io7;
struct io7 *insp;
int h;
if (marvel_find_io7(pe)) {
printk(KERN_WARNING "IO7 at PE %d already allocated!\n", pe);
return NULL;
}
io7 = alloc_bootmem(sizeof(*io7));
io7->pe = pe;
spin_lock_init(&io7->irq_lock);
for (h = 0; h < 4; h++) {
io7->ports[h].io7 = io7;
io7->ports[h].port = h;
io7->ports[h].enabled = 0; /* default to disabled */
}
/*
* Insert in pe sorted order.
*/
if (NULL == io7_head) /* empty list */
io7_head = io7;
else if (io7_head->pe > io7->pe) { /* insert at head */
io7->next = io7_head;
io7_head = io7;
} else { /* insert at position */
for (insp = io7_head; insp; insp = insp->next) {
if (insp->pe == io7->pe) {
printk(KERN_ERR "Too many IO7s at PE %d\n",
io7->pe);
return NULL;
}
if (NULL == insp->next ||
insp->next->pe > io7->pe) { /* insert here */
io7->next = insp->next;
insp->next = io7;
break;
}
}
if (NULL == insp) { /* couldn't insert ?!? */
printk(KERN_WARNING "Failed to insert IO7 at PE %d "
" - adding at head of list\n", io7->pe);
io7->next = io7_head;
io7_head = io7;
}
}
return io7;
}
void
io7_clear_errors(struct io7 *io7)
{
io7_port7_csrs *p7csrs;
io7_ioport_csrs *csrs;
int port;
/*
* First the IO ports.
*/
for (port = 0; port < 4; port++) {
csrs = IO7_CSRS_KERN(io7->pe, port);
csrs->POx_ERR_SUM.csr = -1UL;
csrs->POx_TLB_ERR.csr = -1UL;
csrs->POx_SPL_COMPLT.csr = -1UL;
csrs->POx_TRANS_SUM.csr = -1UL;
}
/*
* Then the common ones.
*/
p7csrs = IO7_PORT7_CSRS_KERN(io7->pe);
p7csrs->PO7_ERROR_SUM.csr = -1UL;
p7csrs->PO7_UNCRR_SYM.csr = -1UL;
p7csrs->PO7_CRRCT_SYM.csr = -1UL;
}
/*
* IO7 PCI, PCI/X, AGP configuration.
*/
static void __init
io7_init_hose(struct io7 *io7, int port)
{
static int hose_index = 0;
struct pci_controller *hose = alloc_pci_controller();
struct io7_port *io7_port = &io7->ports[port];
io7_ioport_csrs *csrs = IO7_CSRS_KERN(io7->pe, port);
int i;
hose->index = hose_index++; /* arbitrary */
/*
* We don't have an isa or legacy hose, but glibc expects to be
* able to use the bus == 0 / dev == 0 form of the iobase syscall
* to determine information about the i/o system. Since XFree86
* relies on glibc's determination to tell whether or not to use
* sparse access, we need to point the pci_isa_hose at a real hose
* so at least that determination is correct.
*/
if (hose->index == 0)
pci_isa_hose = hose;
io7_port->csrs = csrs;
io7_port->hose = hose;
hose->sysdata = io7_port;
hose->io_space = alloc_resource();
hose->mem_space = alloc_resource();
/*
* Base addresses for userland consumption. Since these are going
* to be mapped, they are pure physical addresses.
*/
hose->sparse_mem_base = hose->sparse_io_base = 0;
hose->dense_mem_base = IO7_MEM_PHYS(io7->pe, port);
hose->dense_io_base = IO7_IO_PHYS(io7->pe, port);
/*
* Base addresses and resource ranges for kernel consumption.
*/
hose->config_space_base = (unsigned long)IO7_CONF_KERN(io7->pe, port);
hose->io_space->start = (unsigned long)IO7_IO_KERN(io7->pe, port);
hose->io_space->end = hose->io_space->start + IO7_IO_SPACE - 1;
hose->io_space->name = mk_resource_name(io7->pe, port, "IO");
hose->io_space->flags = IORESOURCE_IO;
hose->mem_space->start = (unsigned long)IO7_MEM_KERN(io7->pe, port);
hose->mem_space->end = hose->mem_space->start + IO7_MEM_SPACE - 1;
hose->mem_space->name = mk_resource_name(io7->pe, port, "MEM");
hose->mem_space->flags = IORESOURCE_MEM;
if (request_resource(&ioport_resource, hose->io_space) < 0)
printk(KERN_ERR "Failed to request IO on hose %d\n",
hose->index);
if (request_resource(&iomem_resource, hose->mem_space) < 0)
printk(KERN_ERR "Failed to request MEM on hose %d\n",
hose->index);
/*
* Save the existing DMA window settings for later restoration.
*/
for (i = 0; i < 4; i++) {
io7_port->saved_wbase[i] = csrs->POx_WBASE[i].csr;
io7_port->saved_wmask[i] = csrs->POx_WMASK[i].csr;
io7_port->saved_tbase[i] = csrs->POx_TBASE[i].csr;
}
/*
* Set up the PCI to main memory translation windows.
*
* Window 0 is scatter-gather 8MB at 8MB
* Window 1 is direct access 1GB at 2GB
* Window 2 is scatter-gather (up-to) 1GB at 3GB
* Window 3 is disabled
*/
/*
* TBIA before modifying windows.
*/
marvel_pci_tbi(hose, 0, -1);
/*
* Set up window 0 for scatter-gather 8MB at 8MB.
*/
hose->sg_isa = iommu_arena_new_node(marvel_cpuid_to_nid(io7->pe),
hose, 0x00800000, 0x00800000, 0);
hose->sg_isa->align_entry = 8; /* cache line boundary */
csrs->POx_WBASE[0].csr =
hose->sg_isa->dma_base | wbase_m_ena | wbase_m_sg;
csrs->POx_WMASK[0].csr = (hose->sg_isa->size - 1) & wbase_m_addr;
csrs->POx_TBASE[0].csr = virt_to_phys(hose->sg_isa->ptes);
/*
* Set up window 1 for direct-mapped 1GB at 2GB.
*/
csrs->POx_WBASE[1].csr = __direct_map_base | wbase_m_ena;
csrs->POx_WMASK[1].csr = (__direct_map_size - 1) & wbase_m_addr;
csrs->POx_TBASE[1].csr = 0;
/*
* Set up window 2 for scatter-gather (up-to) 1GB at 3GB.
*/
hose->sg_pci = iommu_arena_new_node(marvel_cpuid_to_nid(io7->pe),
hose, 0xc0000000, 0x40000000, 0);
hose->sg_pci->align_entry = 8; /* cache line boundary */
csrs->POx_WBASE[2].csr =
hose->sg_pci->dma_base | wbase_m_ena | wbase_m_sg;
csrs->POx_WMASK[2].csr = (hose->sg_pci->size - 1) & wbase_m_addr;
csrs->POx_TBASE[2].csr = virt_to_phys(hose->sg_pci->ptes);
/*
* Disable window 3.
*/
csrs->POx_WBASE[3].csr = 0;
/*
* Make sure that the AGP Monster Window is disabled.
*/
csrs->POx_CTRL.csr &= ~(1UL << 61);
#if 1
printk("FIXME: disabling master aborts\n");
csrs->POx_MSK_HEI.csr &= ~(3UL << 14);
#endif
/*
* TBIA after modifying windows.
*/
marvel_pci_tbi(hose, 0, -1);
}
static void __init
marvel_init_io7(struct io7 *io7)
{
int i;
printk("Initializing IO7 at PID %d\n", io7->pe);
/*
* Get the Port 7 CSR pointer.
*/
io7->csrs = IO7_PORT7_CSRS_KERN(io7->pe);
/*
* Init this IO7's hoses.
*/
for (i = 0; i < IO7_NUM_PORTS; i++) {
io7_ioport_csrs *csrs = IO7_CSRS_KERN(io7->pe, i);
if (csrs->POx_CACHE_CTL.csr == 8) {
io7->ports[i].enabled = 1;
io7_init_hose(io7, i);
}
}
}
void
marvel_io7_present(gct6_node *node)
{
int pe;
if (node->type != GCT_TYPE_HOSE ||
node->subtype != GCT_SUBTYPE_IO_PORT_MODULE)
return;
pe = (node->id >> 8) & 0xff;
printk("Found an IO7 at PID %d\n", pe);
alloc_io7(pe);
}
static void __init
marvel_find_console_vga_hose(void)
{
u64 *pu64 = (u64 *)((u64)hwrpb + hwrpb->ctbt_offset);
if (pu64[7] == 3) { /* TERM_TYPE == graphics */
struct pci_controller *hose = NULL;
int h = (pu64[30] >> 24) & 0xff; /* TERM_OUT_LOC, hose # */
struct io7 *io7;
int pid, port;
/* FIXME - encoding is going to have to change for Marvel
* since hose will be able to overflow a byte...
* need to fix this decode when the console
* changes its encoding
*/
printk("console graphics is on hose %d (console)\n", h);
/*
* The console's hose numbering is:
*
* hose<n:2>: PID
* hose<1:0>: PORT
*
* We need to find the hose at that pid and port
*/
pid = h >> 2;
port = h & 3;
if ((io7 = marvel_find_io7(pid)))
hose = io7->ports[port].hose;
if (hose) {
printk("Console graphics on hose %d\n", hose->index);
pci_vga_hose = hose;
}
}
}
gct6_search_struct gct_wanted_node_list[] = {
{ GCT_TYPE_HOSE, GCT_SUBTYPE_IO_PORT_MODULE, marvel_io7_present },
{ 0, 0, NULL }
};
/*
* In case the GCT is not complete, let the user specify PIDs with IO7s
* at boot time. Syntax is 'io7=a,b,c,...,n' where a-n are the PIDs (decimal)
* where IO7s are connected
*/
static int __init
marvel_specify_io7(char *str)
{
unsigned long pid;
struct io7 *io7;
char *pchar;
do {
pid = simple_strtoul(str, &pchar, 0);
if (pchar != str) {
printk("User-specified IO7 at PID %lu\n", pid);
io7 = alloc_io7(pid);
if (io7) marvel_init_io7(io7);
}
if (pchar == str) pchar++;
str = pchar;
} while(*str);
return 1;
}
__setup("io7=", marvel_specify_io7);
void __init
marvel_init_arch(void)
{
struct io7 *io7;
/* With multiple PCI busses, we play with I/O as physical addrs. */
ioport_resource.end = ~0UL;
/* PCI DMA Direct Mapping is 1GB at 2GB. */
__direct_map_base = 0x80000000;
__direct_map_size = 0x40000000;
/* Parse the config tree. */
gct6_find_nodes(GCT_NODE_PTR(0), gct_wanted_node_list);
/* Init the io7s. */
for (io7 = NULL; NULL != (io7 = marvel_next_io7(io7)); )
marvel_init_io7(io7);
/* Check for graphic console location (if any). */
marvel_find_console_vga_hose();
}
void
marvel_kill_arch(int mode)
{
}
/*
* PCI Configuration Space access functions
*
* Configuration space addresses have the following format:
*
* |2 2 2 2|1 1 1 1|1 1 1 1|1 1
* |3 2 1 0|9 8 7 6|5 4 3 2|1 0 9 8|7 6 5 4|3 2 1 0
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |B|B|B|B|B|B|B|B|D|D|D|D|D|F|F|F|R|R|R|R|R|R|R|R|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* n:24 reserved for hose base
* 23:16 bus number (8 bits = 128 possible buses)
* 15:11 Device number (5 bits)
* 10:8 function number
* 7:2 register number
*
* Notes:
* IO7 determines whether to use a type 0 or type 1 config cycle
* based on the bus number. Therefore the bus number must be set
* to 0 for the root bus on any hose.
*
* The function number selects which function of a multi-function device
* (e.g., SCSI and Ethernet).
*
*/
static inline unsigned long
build_conf_addr(struct pci_controller *hose, u8 bus,
unsigned int devfn, int where)
{
return (hose->config_space_base | (bus << 16) | (devfn << 8) | where);
}
static unsigned long
mk_conf_addr(struct pci_bus *pbus, unsigned int devfn, int where)
{
struct pci_controller *hose = pbus->sysdata;
struct io7_port *io7_port;
unsigned long addr = 0;
u8 bus = pbus->number;
if (!hose)
return addr;
/* Check for enabled. */
io7_port = hose->sysdata;
if (!io7_port->enabled)
return addr;
if (!pbus->parent) { /* No parent means peer PCI bus. */
/* Don't support idsel > 20 on primary bus. */
if (devfn >= PCI_DEVFN(21, 0))
return addr;
bus = 0;
}
addr = build_conf_addr(hose, bus, devfn, where);
DBG_CFG(("mk_conf_addr: returning pci_addr 0x%lx\n", addr));
return addr;
}
static int
marvel_read_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 *value)
{
unsigned long addr;
if (0 == (addr = mk_conf_addr(bus, devfn, where)))
return PCIBIOS_DEVICE_NOT_FOUND;
switch(size) {
case 1:
*value = __kernel_ldbu(*(vucp)addr);
break;
case 2:
*value = __kernel_ldwu(*(vusp)addr);
break;
case 4:
*value = *(vuip)addr;
break;
default:
return PCIBIOS_FUNC_NOT_SUPPORTED;
}
return PCIBIOS_SUCCESSFUL;
}
static int
marvel_write_config(struct pci_bus *bus, unsigned int devfn, int where,
int size, u32 value)
{
unsigned long addr;
if (0 == (addr = mk_conf_addr(bus, devfn, where)))
return PCIBIOS_DEVICE_NOT_FOUND;
switch (size) {
case 1:
__kernel_stb(value, *(vucp)addr);
mb();
__kernel_ldbu(*(vucp)addr);
break;
case 2:
__kernel_stw(value, *(vusp)addr);
mb();
__kernel_ldwu(*(vusp)addr);
break;
case 4:
*(vuip)addr = value;
mb();
*(vuip)addr;
break;
default:
return PCIBIOS_FUNC_NOT_SUPPORTED;
}
return PCIBIOS_SUCCESSFUL;
}
struct pci_ops marvel_pci_ops =
{
.read = marvel_read_config,
.write = marvel_write_config,
};
/*
* Other PCI helper functions.
*/
void
marvel_pci_tbi(struct pci_controller *hose, dma_addr_t start, dma_addr_t end)
{
io7_ioport_csrs *csrs = ((struct io7_port *)hose->sysdata)->csrs;
wmb();
csrs->POx_SG_TBIA.csr = 0;
mb();
csrs->POx_SG_TBIA.csr;
}
/*
* RTC Support
*/
struct marvel_rtc_access_info {
unsigned long function;
unsigned long index;
unsigned long data;
};
static void
__marvel_access_rtc(void *info)
{
struct marvel_rtc_access_info *rtc_access = info;
register unsigned long __r0 __asm__("$0");
register unsigned long __r16 __asm__("$16") = rtc_access->function;
register unsigned long __r17 __asm__("$17") = rtc_access->index;
register unsigned long __r18 __asm__("$18") = rtc_access->data;
__asm__ __volatile__(
"call_pal %4 # cserve rtc"
: "=r"(__r16), "=r"(__r17), "=r"(__r18), "=r"(__r0)
: "i"(PAL_cserve), "0"(__r16), "1"(__r17), "2"(__r18)
: "$1", "$22", "$23", "$24", "$25");
rtc_access->data = __r0;
}
static u8
__marvel_rtc_io(u8 b, unsigned long addr, int write)
{
static u8 index = 0;
struct marvel_rtc_access_info rtc_access;
u8 ret = 0;
switch(addr) {
case 0x70: /* RTC_PORT(0) */
if (write) index = b;
ret = index;
break;
case 0x71: /* RTC_PORT(1) */
rtc_access.index = index;
rtc_access.data = bcd2bin(b);
rtc_access.function = 0x48 + !write; /* GET/PUT_TOY */
__marvel_access_rtc(&rtc_access);
ret = bin2bcd(rtc_access.data);
break;
default:
printk(KERN_WARNING "Illegal RTC port %lx\n", addr);
break;
}
return ret;
}
/*
* IO map support.
*/
void __iomem *
marvel_ioremap(unsigned long addr, unsigned long size)
{
struct pci_controller *hose;
unsigned long baddr, last;
struct vm_struct *area;
unsigned long vaddr;
unsigned long *ptes;
unsigned long pfn;
/*
* Adjust the address.
*/
FIXUP_MEMADDR_VGA(addr);
/*
* Find the hose.
*/
for (hose = hose_head; hose; hose = hose->next) {
if ((addr >> 32) == (hose->mem_space->start >> 32))
break;
}
if (!hose)
return NULL;
/*
* We have the hose - calculate the bus limits.
*/
baddr = addr - hose->mem_space->start;
last = baddr + size - 1;
/*
* Is it direct-mapped?
*/
if ((baddr >= __direct_map_base) &&
((baddr + size - 1) < __direct_map_base + __direct_map_size)) {
addr = IDENT_ADDR | (baddr - __direct_map_base);
return (void __iomem *) addr;
}
/*
* Check the scatter-gather arena.
*/
if (hose->sg_pci &&
baddr >= (unsigned long)hose->sg_pci->dma_base &&
last < (unsigned long)hose->sg_pci->dma_base + hose->sg_pci->size) {
/*
* Adjust the limits (mappings must be page aligned)
*/
baddr -= hose->sg_pci->dma_base;
last -= hose->sg_pci->dma_base;
baddr &= PAGE_MASK;
size = PAGE_ALIGN(last) - baddr;
/*
* Map it.
*/
area = get_vm_area(size, VM_IOREMAP);
if (!area)
return NULL;
ptes = hose->sg_pci->ptes;
for (vaddr = (unsigned long)area->addr;
baddr <= last;
baddr += PAGE_SIZE, vaddr += PAGE_SIZE) {
pfn = ptes[baddr >> PAGE_SHIFT];
if (!(pfn & 1)) {
printk("ioremap failed... pte not valid...\n");
vfree(area->addr);
return NULL;
}
pfn >>= 1; /* make it a true pfn */
if (__alpha_remap_area_pages(vaddr,
pfn << PAGE_SHIFT,
PAGE_SIZE, 0)) {
printk("FAILED to map...\n");
vfree(area->addr);
return NULL;
}
}
flush_tlb_all();
vaddr = (unsigned long)area->addr + (addr & ~PAGE_MASK);
return (void __iomem *) vaddr;
}
/* Assume it was already a reasonable address */
vaddr = baddr + hose->mem_space->start;
return (void __iomem *) vaddr;
}
void
marvel_iounmap(volatile void __iomem *xaddr)
{
unsigned long addr = (unsigned long) xaddr;
if (addr >= VMALLOC_START)
vfree((void *)(PAGE_MASK & addr));
}
int
marvel_is_mmio(const volatile void __iomem *xaddr)
{
unsigned long addr = (unsigned long) xaddr;
if (addr >= VMALLOC_START)
return 1;
else
return (addr & 0xFF000000UL) == 0;
}
#define __marvel_is_port_kbd(a) (((a) == 0x60) || ((a) == 0x64))
#define __marvel_is_port_rtc(a) (((a) == 0x70) || ((a) == 0x71))
void __iomem *marvel_ioportmap (unsigned long addr)
{
FIXUP_IOADDR_VGA(addr);
return (void __iomem *)addr;
}
unsigned int
marvel_ioread8(void __iomem *xaddr)
{
unsigned long addr = (unsigned long) xaddr;
if (__marvel_is_port_kbd(addr))
return 0;
else if (__marvel_is_port_rtc(addr))
return __marvel_rtc_io(0, addr, 0);
else if (marvel_is_ioaddr(addr))
return __kernel_ldbu(*(vucp)addr);
else
/* this should catch other legacy addresses
that would normally fail on MARVEL,
because there really is nothing there...
*/
return ~0;
}
void
marvel_iowrite8(u8 b, void __iomem *xaddr)
{
unsigned long addr = (unsigned long) xaddr;
if (__marvel_is_port_kbd(addr))
return;
else if (__marvel_is_port_rtc(addr))
__marvel_rtc_io(b, addr, 1);
else if (marvel_is_ioaddr(addr))
__kernel_stb(b, *(vucp)addr);
}
#ifndef CONFIG_ALPHA_GENERIC
EXPORT_SYMBOL(marvel_ioremap);
EXPORT_SYMBOL(marvel_iounmap);
EXPORT_SYMBOL(marvel_is_mmio);
EXPORT_SYMBOL(marvel_ioportmap);
EXPORT_SYMBOL(marvel_ioread8);
EXPORT_SYMBOL(marvel_iowrite8);
#endif
/*
* NUMA Support
*/
/**********
* FIXME - for now each cpu is a node by itself
* -- no real support for striped mode
**********
*/
int
marvel_pa_to_nid(unsigned long pa)
{
int cpuid;
if ((pa >> 43) & 1) /* I/O */
cpuid = (~(pa >> 35) & 0xff);
else /* mem */
cpuid = ((pa >> 34) & 0x3) | ((pa >> (37 - 2)) & (0x1f << 2));
return marvel_cpuid_to_nid(cpuid);
}
int
marvel_cpuid_to_nid(int cpuid)
{
return cpuid;
}
unsigned long
marvel_node_mem_start(int nid)
{
unsigned long pa;
pa = (nid & 0x3) | ((nid & (0x1f << 2)) << 1);
pa <<= 34;
return pa;
}
unsigned long
marvel_node_mem_size(int nid)
{
return 16UL * 1024 * 1024 * 1024; /* 16GB */
}
/*
* AGP GART Support.
*/
#include <linux/agp_backend.h>
#include <asm/agp_backend.h>
#include <linux/slab.h>
#include <linux/delay.h>
struct marvel_agp_aperture {
struct pci_iommu_arena *arena;
long pg_start;
long pg_count;
};
static int
marvel_agp_setup(alpha_agp_info *agp)
{
struct marvel_agp_aperture *aper;
if (!alpha_agpgart_size)
return -ENOMEM;
aper = kmalloc(sizeof(*aper), GFP_KERNEL);
if (aper == NULL) return -ENOMEM;
aper->arena = agp->hose->sg_pci;
aper->pg_count = alpha_agpgart_size / PAGE_SIZE;
aper->pg_start = iommu_reserve(aper->arena, aper->pg_count,
aper->pg_count - 1);
if (aper->pg_start < 0) {
printk(KERN_ERR "Failed to reserve AGP memory\n");
kfree(aper);
return -ENOMEM;
}
agp->aperture.bus_base =
aper->arena->dma_base + aper->pg_start * PAGE_SIZE;
agp->aperture.size = aper->pg_count * PAGE_SIZE;
agp->aperture.sysdata = aper;
return 0;
}
static void
marvel_agp_cleanup(alpha_agp_info *agp)
{
struct marvel_agp_aperture *aper = agp->aperture.sysdata;
int status;
status = iommu_release(aper->arena, aper->pg_start, aper->pg_count);
if (status == -EBUSY) {
printk(KERN_WARNING
"Attempted to release bound AGP memory - unbinding\n");
iommu_unbind(aper->arena, aper->pg_start, aper->pg_count);
status = iommu_release(aper->arena, aper->pg_start,
aper->pg_count);
}
if (status < 0)
printk(KERN_ERR "Failed to release AGP memory\n");
kfree(aper);
kfree(agp);
}
static int
marvel_agp_configure(alpha_agp_info *agp)
{
io7_ioport_csrs *csrs = ((struct io7_port *)agp->hose->sysdata)->csrs;
struct io7 *io7 = ((struct io7_port *)agp->hose->sysdata)->io7;
unsigned int new_rate = 0;
unsigned long agp_pll;
/*
* Check the requested mode against the PLL setting.
* The agpgart_be code has not programmed the card yet,
* so we can still tweak mode here.
*/
agp_pll = io7->csrs->POx_RST[IO7_AGP_PORT].csr;
switch(IO7_PLL_RNGB(agp_pll)) {
case 0x4: /* 2x only */
/*
* The PLL is only programmed for 2x, so adjust the
* rate to 2x, if necessary.
*/
if (agp->mode.bits.rate != 2)
new_rate = 2;
break;
case 0x6: /* 1x / 4x */
/*
* The PLL is programmed for 1x or 4x. Don't go faster
* than requested, so if the requested rate is 2x, use 1x.
*/
if (agp->mode.bits.rate == 2)
new_rate = 1;
break;
default: /* ??????? */
/*
* Don't know what this PLL setting is, take the requested
* rate, but warn the user.
*/
printk("%s: unknown PLL setting RNGB=%lx (PLL6_CTL=%016lx)\n",
__func__, IO7_PLL_RNGB(agp_pll), agp_pll);
break;
}
/*
* Set the new rate, if necessary.
*/
if (new_rate) {
printk("Requested AGP Rate %dX not compatible "
"with PLL setting - using %dX\n",
agp->mode.bits.rate,
new_rate);
agp->mode.bits.rate = new_rate;
}
printk("Enabling AGP on hose %d: %dX%s RQ %d\n",
agp->hose->index, agp->mode.bits.rate,
agp->mode.bits.sba ? " - SBA" : "", agp->mode.bits.rq);
csrs->AGP_CMD.csr = agp->mode.lw;
return 0;
}
static int
marvel_agp_bind_memory(alpha_agp_info *agp, off_t pg_start, struct agp_memory *mem)
{
struct marvel_agp_aperture *aper = agp->aperture.sysdata;
return iommu_bind(aper->arena, aper->pg_start + pg_start,
mem->page_count, mem->pages);
}
static int
marvel_agp_unbind_memory(alpha_agp_info *agp, off_t pg_start, struct agp_memory *mem)
{
struct marvel_agp_aperture *aper = agp->aperture.sysdata;
return iommu_unbind(aper->arena, aper->pg_start + pg_start,
mem->page_count);
}
static unsigned long
marvel_agp_translate(alpha_agp_info *agp, dma_addr_t addr)
{
struct marvel_agp_aperture *aper = agp->aperture.sysdata;
unsigned long baddr = addr - aper->arena->dma_base;
unsigned long pte;
if (addr < agp->aperture.bus_base ||
addr >= agp->aperture.bus_base + agp->aperture.size) {
printk("%s: addr out of range\n", __func__);
return -EINVAL;
}
pte = aper->arena->ptes[baddr >> PAGE_SHIFT];
if (!(pte & 1)) {
printk("%s: pte not valid\n", __func__);
return -EINVAL;
}
return (pte >> 1) << PAGE_SHIFT;
}
struct alpha_agp_ops marvel_agp_ops =
{
.setup = marvel_agp_setup,
.cleanup = marvel_agp_cleanup,
.configure = marvel_agp_configure,
.bind = marvel_agp_bind_memory,
.unbind = marvel_agp_unbind_memory,
.translate = marvel_agp_translate
};
alpha_agp_info *
marvel_agp_info(void)
{
struct pci_controller *hose;
io7_ioport_csrs *csrs;
alpha_agp_info *agp;
struct io7 *io7;
/*
* Find the first IO7 with an AGP card.
*
* FIXME -- there should be a better way (we want to be able to
* specify and what if the agp card is not video???)
*/
hose = NULL;
for (io7 = NULL; (io7 = marvel_next_io7(io7)) != NULL; ) {
struct pci_controller *h;
vuip addr;
if (!io7->ports[IO7_AGP_PORT].enabled)
continue;
h = io7->ports[IO7_AGP_PORT].hose;
addr = (vuip)build_conf_addr(h, 0, PCI_DEVFN(5, 0), 0);
if (*addr != 0xffffffffu) {
hose = h;
break;
}
}
if (!hose || !hose->sg_pci)
return NULL;
printk("MARVEL - using hose %d as AGP\n", hose->index);
/*
* Get the csrs from the hose.
*/
csrs = ((struct io7_port *)hose->sysdata)->csrs;
/*
* Allocate the info structure.
*/
agp = kmalloc(sizeof(*agp), GFP_KERNEL);
if (!agp)
return NULL;
/*
* Fill it in.
*/
agp->hose = hose;
agp->private = NULL;
agp->ops = &marvel_agp_ops;
/*
* Aperture - not configured until ops.setup().
*/
agp->aperture.bus_base = 0;
agp->aperture.size = 0;
agp->aperture.sysdata = NULL;
/*
* Capabilities.
*
* NOTE: IO7 reports through AGP_STAT that it can support a read queue
* depth of 17 (rq = 0x10). It actually only supports a depth of
* 16 (rq = 0xf).
*/
agp->capability.lw = csrs->AGP_STAT.csr;
agp->capability.bits.rq = 0xf;
/*
* Mode.
*/
agp->mode.lw = csrs->AGP_CMD.csr;
return agp;
}
| gpl-2.0 |
Naoya-Horiguchi/linux | drivers/gpu/drm/omapdrm/dss/hdmi4.c | 179 | 18893 | // SPDX-License-Identifier: GPL-2.0-only
/*
* HDMI interface DSS driver for TI's OMAP4 family of SoCs.
*
* Copyright (C) 2010-2011 Texas Instruments Incorporated - https://www.ti.com/
* Authors: Yong Zhi
* Mythri pk <mythripk@ti.com>
*/
#define DSS_SUBSYS_NAME "HDMI"
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/clk.h>
#include <linux/regulator/consumer.h>
#include <linux/component.h>
#include <linux/of.h>
#include <linux/of_graph.h>
#include <sound/omap-hdmi-audio.h>
#include <media/cec.h>
#include <drm/drm_atomic.h>
#include <drm/drm_atomic_state_helper.h>
#include "omapdss.h"
#include "hdmi4_core.h"
#include "hdmi4_cec.h"
#include "dss.h"
#include "hdmi.h"
static int hdmi_runtime_get(struct omap_hdmi *hdmi)
{
int r;
DSSDBG("hdmi_runtime_get\n");
r = pm_runtime_get_sync(&hdmi->pdev->dev);
if (WARN_ON(r < 0)) {
pm_runtime_put_noidle(&hdmi->pdev->dev);
return r;
}
return 0;
}
static void hdmi_runtime_put(struct omap_hdmi *hdmi)
{
int r;
DSSDBG("hdmi_runtime_put\n");
r = pm_runtime_put_sync(&hdmi->pdev->dev);
WARN_ON(r < 0 && r != -ENOSYS);
}
static irqreturn_t hdmi_irq_handler(int irq, void *data)
{
struct omap_hdmi *hdmi = data;
struct hdmi_wp_data *wp = &hdmi->wp;
u32 irqstatus;
irqstatus = hdmi_wp_get_irqstatus(wp);
hdmi_wp_set_irqstatus(wp, irqstatus);
if ((irqstatus & HDMI_IRQ_LINK_CONNECT) &&
irqstatus & HDMI_IRQ_LINK_DISCONNECT) {
/*
* If we get both connect and disconnect interrupts at the same
* time, turn off the PHY, clear interrupts, and restart, which
* raises connect interrupt if a cable is connected, or nothing
* if cable is not connected.
*/
hdmi_wp_set_phy_pwr(wp, HDMI_PHYPWRCMD_OFF);
hdmi_wp_set_irqstatus(wp, HDMI_IRQ_LINK_CONNECT |
HDMI_IRQ_LINK_DISCONNECT);
hdmi_wp_set_phy_pwr(wp, HDMI_PHYPWRCMD_LDOON);
} else if (irqstatus & HDMI_IRQ_LINK_CONNECT) {
hdmi_wp_set_phy_pwr(wp, HDMI_PHYPWRCMD_TXON);
} else if (irqstatus & HDMI_IRQ_LINK_DISCONNECT) {
hdmi_wp_set_phy_pwr(wp, HDMI_PHYPWRCMD_LDOON);
}
if (irqstatus & HDMI_IRQ_CORE) {
u32 intr4 = hdmi_read_reg(hdmi->core.base, HDMI_CORE_SYS_INTR4);
hdmi_write_reg(hdmi->core.base, HDMI_CORE_SYS_INTR4, intr4);
if (intr4 & 8)
hdmi4_cec_irq(&hdmi->core);
}
return IRQ_HANDLED;
}
static int hdmi_power_on_core(struct omap_hdmi *hdmi)
{
int r;
if (hdmi->core.core_pwr_cnt++)
return 0;
r = regulator_enable(hdmi->vdda_reg);
if (r)
goto err_reg_enable;
r = hdmi_runtime_get(hdmi);
if (r)
goto err_runtime_get;
hdmi4_core_powerdown_disable(&hdmi->core);
/* Make selection of HDMI in DSS */
dss_select_hdmi_venc_clk_source(hdmi->dss, DSS_HDMI_M_PCLK);
hdmi->core_enabled = true;
return 0;
err_runtime_get:
regulator_disable(hdmi->vdda_reg);
err_reg_enable:
hdmi->core.core_pwr_cnt--;
return r;
}
static void hdmi_power_off_core(struct omap_hdmi *hdmi)
{
if (--hdmi->core.core_pwr_cnt)
return;
hdmi->core_enabled = false;
hdmi_runtime_put(hdmi);
regulator_disable(hdmi->vdda_reg);
}
static int hdmi_power_on_full(struct omap_hdmi *hdmi)
{
int r;
const struct videomode *vm;
struct hdmi_wp_data *wp = &hdmi->wp;
struct dss_pll_clock_info hdmi_cinfo = { 0 };
unsigned int pc;
r = hdmi_power_on_core(hdmi);
if (r)
return r;
/* disable and clear irqs */
hdmi_wp_clear_irqenable(wp, ~HDMI_IRQ_CORE);
hdmi_wp_set_irqstatus(wp, ~HDMI_IRQ_CORE);
vm = &hdmi->cfg.vm;
DSSDBG("hdmi_power_on hactive= %d vactive = %d\n", vm->hactive,
vm->vactive);
pc = vm->pixelclock;
if (vm->flags & DISPLAY_FLAGS_DOUBLECLK)
pc *= 2;
/* DSS_HDMI_TCLK is bitclk / 10 */
pc *= 10;
dss_pll_calc_b(&hdmi->pll.pll, clk_get_rate(hdmi->pll.pll.clkin),
pc, &hdmi_cinfo);
r = dss_pll_enable(&hdmi->pll.pll);
if (r) {
DSSERR("Failed to enable PLL\n");
goto err_pll_enable;
}
r = dss_pll_set_config(&hdmi->pll.pll, &hdmi_cinfo);
if (r) {
DSSERR("Failed to configure PLL\n");
goto err_pll_cfg;
}
r = hdmi_phy_configure(&hdmi->phy, hdmi_cinfo.clkdco,
hdmi_cinfo.clkout[0]);
if (r) {
DSSDBG("Failed to configure PHY\n");
goto err_phy_cfg;
}
r = hdmi_wp_set_phy_pwr(wp, HDMI_PHYPWRCMD_LDOON);
if (r)
goto err_phy_pwr;
hdmi4_configure(&hdmi->core, &hdmi->wp, &hdmi->cfg);
r = dss_mgr_enable(&hdmi->output);
if (r)
goto err_mgr_enable;
r = hdmi_wp_video_start(&hdmi->wp);
if (r)
goto err_vid_enable;
hdmi_wp_set_irqenable(wp,
HDMI_IRQ_LINK_CONNECT | HDMI_IRQ_LINK_DISCONNECT);
return 0;
err_vid_enable:
dss_mgr_disable(&hdmi->output);
err_mgr_enable:
hdmi_wp_set_phy_pwr(&hdmi->wp, HDMI_PHYPWRCMD_OFF);
err_phy_pwr:
err_phy_cfg:
err_pll_cfg:
dss_pll_disable(&hdmi->pll.pll);
err_pll_enable:
hdmi_power_off_core(hdmi);
return -EIO;
}
static void hdmi_power_off_full(struct omap_hdmi *hdmi)
{
hdmi_wp_clear_irqenable(&hdmi->wp, ~HDMI_IRQ_CORE);
hdmi_wp_video_stop(&hdmi->wp);
dss_mgr_disable(&hdmi->output);
hdmi_wp_set_phy_pwr(&hdmi->wp, HDMI_PHYPWRCMD_OFF);
dss_pll_disable(&hdmi->pll.pll);
hdmi_power_off_core(hdmi);
}
static int hdmi_dump_regs(struct seq_file *s, void *p)
{
struct omap_hdmi *hdmi = s->private;
mutex_lock(&hdmi->lock);
if (hdmi_runtime_get(hdmi)) {
mutex_unlock(&hdmi->lock);
return 0;
}
hdmi_wp_dump(&hdmi->wp, s);
hdmi_pll_dump(&hdmi->pll, s);
hdmi_phy_dump(&hdmi->phy, s);
hdmi4_core_dump(&hdmi->core, s);
hdmi_runtime_put(hdmi);
mutex_unlock(&hdmi->lock);
return 0;
}
static void hdmi_start_audio_stream(struct omap_hdmi *hd)
{
hdmi_wp_audio_enable(&hd->wp, true);
hdmi4_audio_start(&hd->core, &hd->wp);
}
static void hdmi_stop_audio_stream(struct omap_hdmi *hd)
{
hdmi4_audio_stop(&hd->core, &hd->wp);
hdmi_wp_audio_enable(&hd->wp, false);
}
int hdmi4_core_enable(struct hdmi_core_data *core)
{
struct omap_hdmi *hdmi = container_of(core, struct omap_hdmi, core);
int r = 0;
DSSDBG("ENTER omapdss_hdmi4_core_enable\n");
mutex_lock(&hdmi->lock);
r = hdmi_power_on_core(hdmi);
if (r) {
DSSERR("failed to power on device\n");
goto err0;
}
mutex_unlock(&hdmi->lock);
return 0;
err0:
mutex_unlock(&hdmi->lock);
return r;
}
void hdmi4_core_disable(struct hdmi_core_data *core)
{
struct omap_hdmi *hdmi = container_of(core, struct omap_hdmi, core);
DSSDBG("Enter omapdss_hdmi4_core_disable\n");
mutex_lock(&hdmi->lock);
hdmi_power_off_core(hdmi);
mutex_unlock(&hdmi->lock);
}
/* -----------------------------------------------------------------------------
* DRM Bridge Operations
*/
static int hdmi4_bridge_attach(struct drm_bridge *bridge,
enum drm_bridge_attach_flags flags)
{
struct omap_hdmi *hdmi = drm_bridge_to_hdmi(bridge);
if (!(flags & DRM_BRIDGE_ATTACH_NO_CONNECTOR))
return -EINVAL;
return drm_bridge_attach(bridge->encoder, hdmi->output.next_bridge,
bridge, flags);
}
static void hdmi4_bridge_mode_set(struct drm_bridge *bridge,
const struct drm_display_mode *mode,
const struct drm_display_mode *adjusted_mode)
{
struct omap_hdmi *hdmi = drm_bridge_to_hdmi(bridge);
mutex_lock(&hdmi->lock);
drm_display_mode_to_videomode(adjusted_mode, &hdmi->cfg.vm);
dispc_set_tv_pclk(hdmi->dss->dispc, adjusted_mode->clock * 1000);
mutex_unlock(&hdmi->lock);
}
static void hdmi4_bridge_enable(struct drm_bridge *bridge,
struct drm_bridge_state *bridge_state)
{
struct omap_hdmi *hdmi = drm_bridge_to_hdmi(bridge);
struct drm_atomic_state *state = bridge_state->base.state;
struct drm_connector_state *conn_state;
struct drm_connector *connector;
struct drm_crtc_state *crtc_state;
unsigned long flags;
int ret;
/*
* None of these should fail, as the bridge can't be enabled without a
* valid CRTC to connector path with fully populated new states.
*/
connector = drm_atomic_get_new_connector_for_encoder(state,
bridge->encoder);
if (WARN_ON(!connector))
return;
conn_state = drm_atomic_get_new_connector_state(state, connector);
if (WARN_ON(!conn_state))
return;
crtc_state = drm_atomic_get_new_crtc_state(state, conn_state->crtc);
if (WARN_ON(!crtc_state))
return;
hdmi->cfg.hdmi_dvi_mode = connector->display_info.is_hdmi
? HDMI_HDMI : HDMI_DVI;
if (connector->display_info.is_hdmi) {
const struct drm_display_mode *mode;
struct hdmi_avi_infoframe avi;
mode = &crtc_state->adjusted_mode;
ret = drm_hdmi_avi_infoframe_from_display_mode(&avi, connector,
mode);
if (ret == 0)
hdmi->cfg.infoframe = avi;
}
mutex_lock(&hdmi->lock);
ret = hdmi_power_on_full(hdmi);
if (ret) {
DSSERR("failed to power on device\n");
goto done;
}
if (hdmi->audio_configured) {
ret = hdmi4_audio_config(&hdmi->core, &hdmi->wp,
&hdmi->audio_config,
hdmi->cfg.vm.pixelclock);
if (ret) {
DSSERR("Error restoring audio configuration: %d", ret);
hdmi->audio_abort_cb(&hdmi->pdev->dev);
hdmi->audio_configured = false;
}
}
spin_lock_irqsave(&hdmi->audio_playing_lock, flags);
if (hdmi->audio_configured && hdmi->audio_playing)
hdmi_start_audio_stream(hdmi);
hdmi->display_enabled = true;
spin_unlock_irqrestore(&hdmi->audio_playing_lock, flags);
done:
mutex_unlock(&hdmi->lock);
}
static void hdmi4_bridge_disable(struct drm_bridge *bridge,
struct drm_bridge_state *bridge_state)
{
struct omap_hdmi *hdmi = drm_bridge_to_hdmi(bridge);
unsigned long flags;
mutex_lock(&hdmi->lock);
spin_lock_irqsave(&hdmi->audio_playing_lock, flags);
hdmi_stop_audio_stream(hdmi);
hdmi->display_enabled = false;
spin_unlock_irqrestore(&hdmi->audio_playing_lock, flags);
hdmi_power_off_full(hdmi);
mutex_unlock(&hdmi->lock);
}
static void hdmi4_bridge_hpd_notify(struct drm_bridge *bridge,
enum drm_connector_status status)
{
struct omap_hdmi *hdmi = drm_bridge_to_hdmi(bridge);
if (status == connector_status_disconnected)
hdmi4_cec_set_phys_addr(&hdmi->core, CEC_PHYS_ADDR_INVALID);
}
static struct edid *hdmi4_bridge_get_edid(struct drm_bridge *bridge,
struct drm_connector *connector)
{
struct omap_hdmi *hdmi = drm_bridge_to_hdmi(bridge);
struct edid *edid = NULL;
unsigned int cec_addr;
bool need_enable;
int r;
need_enable = hdmi->core_enabled == false;
if (need_enable) {
r = hdmi4_core_enable(&hdmi->core);
if (r)
return NULL;
}
mutex_lock(&hdmi->lock);
r = hdmi_runtime_get(hdmi);
BUG_ON(r);
r = hdmi4_core_ddc_init(&hdmi->core);
if (r)
goto done;
edid = drm_do_get_edid(connector, hdmi4_core_ddc_read, &hdmi->core);
done:
hdmi_runtime_put(hdmi);
mutex_unlock(&hdmi->lock);
if (edid && edid->extensions) {
unsigned int len = (edid->extensions + 1) * EDID_LENGTH;
cec_addr = cec_get_edid_phys_addr((u8 *)edid, len, NULL);
} else {
cec_addr = CEC_PHYS_ADDR_INVALID;
}
hdmi4_cec_set_phys_addr(&hdmi->core, cec_addr);
if (need_enable)
hdmi4_core_disable(&hdmi->core);
return edid;
}
static const struct drm_bridge_funcs hdmi4_bridge_funcs = {
.attach = hdmi4_bridge_attach,
.mode_set = hdmi4_bridge_mode_set,
.atomic_duplicate_state = drm_atomic_helper_bridge_duplicate_state,
.atomic_destroy_state = drm_atomic_helper_bridge_destroy_state,
.atomic_reset = drm_atomic_helper_bridge_reset,
.atomic_enable = hdmi4_bridge_enable,
.atomic_disable = hdmi4_bridge_disable,
.hpd_notify = hdmi4_bridge_hpd_notify,
.get_edid = hdmi4_bridge_get_edid,
};
static void hdmi4_bridge_init(struct omap_hdmi *hdmi)
{
hdmi->bridge.funcs = &hdmi4_bridge_funcs;
hdmi->bridge.of_node = hdmi->pdev->dev.of_node;
hdmi->bridge.ops = DRM_BRIDGE_OP_EDID;
hdmi->bridge.type = DRM_MODE_CONNECTOR_HDMIA;
drm_bridge_add(&hdmi->bridge);
}
static void hdmi4_bridge_cleanup(struct omap_hdmi *hdmi)
{
drm_bridge_remove(&hdmi->bridge);
}
/* -----------------------------------------------------------------------------
* Audio Callbacks
*/
static int hdmi_audio_startup(struct device *dev,
void (*abort_cb)(struct device *dev))
{
struct omap_hdmi *hd = dev_get_drvdata(dev);
mutex_lock(&hd->lock);
WARN_ON(hd->audio_abort_cb != NULL);
hd->audio_abort_cb = abort_cb;
mutex_unlock(&hd->lock);
return 0;
}
static int hdmi_audio_shutdown(struct device *dev)
{
struct omap_hdmi *hd = dev_get_drvdata(dev);
mutex_lock(&hd->lock);
hd->audio_abort_cb = NULL;
hd->audio_configured = false;
hd->audio_playing = false;
mutex_unlock(&hd->lock);
return 0;
}
static int hdmi_audio_start(struct device *dev)
{
struct omap_hdmi *hd = dev_get_drvdata(dev);
unsigned long flags;
spin_lock_irqsave(&hd->audio_playing_lock, flags);
if (hd->display_enabled) {
if (!hdmi_mode_has_audio(&hd->cfg))
DSSERR("%s: Video mode does not support audio\n",
__func__);
hdmi_start_audio_stream(hd);
}
hd->audio_playing = true;
spin_unlock_irqrestore(&hd->audio_playing_lock, flags);
return 0;
}
static void hdmi_audio_stop(struct device *dev)
{
struct omap_hdmi *hd = dev_get_drvdata(dev);
unsigned long flags;
WARN_ON(!hdmi_mode_has_audio(&hd->cfg));
spin_lock_irqsave(&hd->audio_playing_lock, flags);
if (hd->display_enabled)
hdmi_stop_audio_stream(hd);
hd->audio_playing = false;
spin_unlock_irqrestore(&hd->audio_playing_lock, flags);
}
static int hdmi_audio_config(struct device *dev,
struct omap_dss_audio *dss_audio)
{
struct omap_hdmi *hd = dev_get_drvdata(dev);
int ret = 0;
mutex_lock(&hd->lock);
if (hd->display_enabled) {
ret = hdmi4_audio_config(&hd->core, &hd->wp, dss_audio,
hd->cfg.vm.pixelclock);
if (ret)
goto out;
}
hd->audio_configured = true;
hd->audio_config = *dss_audio;
out:
mutex_unlock(&hd->lock);
return ret;
}
static const struct omap_hdmi_audio_ops hdmi_audio_ops = {
.audio_startup = hdmi_audio_startup,
.audio_shutdown = hdmi_audio_shutdown,
.audio_start = hdmi_audio_start,
.audio_stop = hdmi_audio_stop,
.audio_config = hdmi_audio_config,
};
static int hdmi_audio_register(struct omap_hdmi *hdmi)
{
struct omap_hdmi_audio_pdata pdata = {
.dev = &hdmi->pdev->dev,
.version = 4,
.audio_dma_addr = hdmi_wp_get_audio_dma_addr(&hdmi->wp),
.ops = &hdmi_audio_ops,
};
hdmi->audio_pdev = platform_device_register_data(
&hdmi->pdev->dev, "omap-hdmi-audio", PLATFORM_DEVID_AUTO,
&pdata, sizeof(pdata));
if (IS_ERR(hdmi->audio_pdev))
return PTR_ERR(hdmi->audio_pdev);
return 0;
}
/* -----------------------------------------------------------------------------
* Component Bind & Unbind
*/
static int hdmi4_bind(struct device *dev, struct device *master, void *data)
{
struct dss_device *dss = dss_get_device(master);
struct omap_hdmi *hdmi = dev_get_drvdata(dev);
int r;
hdmi->dss = dss;
r = hdmi_runtime_get(hdmi);
if (r)
return r;
r = hdmi_pll_init(dss, hdmi->pdev, &hdmi->pll, &hdmi->wp);
if (r)
goto err_runtime_put;
r = hdmi4_cec_init(hdmi->pdev, &hdmi->core, &hdmi->wp);
if (r)
goto err_pll_uninit;
r = hdmi_audio_register(hdmi);
if (r) {
DSSERR("Registering HDMI audio failed\n");
goto err_cec_uninit;
}
hdmi->debugfs = dss_debugfs_create_file(dss, "hdmi", hdmi_dump_regs,
hdmi);
hdmi_runtime_put(hdmi);
return 0;
err_cec_uninit:
hdmi4_cec_uninit(&hdmi->core);
err_pll_uninit:
hdmi_pll_uninit(&hdmi->pll);
err_runtime_put:
hdmi_runtime_put(hdmi);
return r;
}
static void hdmi4_unbind(struct device *dev, struct device *master, void *data)
{
struct omap_hdmi *hdmi = dev_get_drvdata(dev);
dss_debugfs_remove_file(hdmi->debugfs);
if (hdmi->audio_pdev)
platform_device_unregister(hdmi->audio_pdev);
hdmi4_cec_uninit(&hdmi->core);
hdmi_pll_uninit(&hdmi->pll);
}
static const struct component_ops hdmi4_component_ops = {
.bind = hdmi4_bind,
.unbind = hdmi4_unbind,
};
/* -----------------------------------------------------------------------------
* Probe & Remove, Suspend & Resume
*/
static int hdmi4_init_output(struct omap_hdmi *hdmi)
{
struct omap_dss_device *out = &hdmi->output;
int r;
hdmi4_bridge_init(hdmi);
out->dev = &hdmi->pdev->dev;
out->id = OMAP_DSS_OUTPUT_HDMI;
out->type = OMAP_DISPLAY_TYPE_HDMI;
out->name = "hdmi.0";
out->dispc_channel = OMAP_DSS_CHANNEL_DIGIT;
out->of_port = 0;
r = omapdss_device_init_output(out, &hdmi->bridge);
if (r < 0) {
hdmi4_bridge_cleanup(hdmi);
return r;
}
omapdss_device_register(out);
return 0;
}
static void hdmi4_uninit_output(struct omap_hdmi *hdmi)
{
struct omap_dss_device *out = &hdmi->output;
omapdss_device_unregister(out);
omapdss_device_cleanup_output(out);
hdmi4_bridge_cleanup(hdmi);
}
static int hdmi4_probe_of(struct omap_hdmi *hdmi)
{
struct platform_device *pdev = hdmi->pdev;
struct device_node *node = pdev->dev.of_node;
struct device_node *ep;
int r;
ep = of_graph_get_endpoint_by_regs(node, 0, 0);
if (!ep)
return 0;
r = hdmi_parse_lanes_of(pdev, ep, &hdmi->phy);
of_node_put(ep);
return r;
}
static int hdmi4_probe(struct platform_device *pdev)
{
struct omap_hdmi *hdmi;
int irq;
int r;
hdmi = kzalloc(sizeof(*hdmi), GFP_KERNEL);
if (!hdmi)
return -ENOMEM;
hdmi->pdev = pdev;
dev_set_drvdata(&pdev->dev, hdmi);
mutex_init(&hdmi->lock);
spin_lock_init(&hdmi->audio_playing_lock);
r = hdmi4_probe_of(hdmi);
if (r)
goto err_free;
r = hdmi_wp_init(pdev, &hdmi->wp, 4);
if (r)
goto err_free;
r = hdmi_phy_init(pdev, &hdmi->phy, 4);
if (r)
goto err_free;
r = hdmi4_core_init(pdev, &hdmi->core);
if (r)
goto err_free;
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
DSSERR("platform_get_irq failed\n");
r = -ENODEV;
goto err_free;
}
r = devm_request_threaded_irq(&pdev->dev, irq,
NULL, hdmi_irq_handler,
IRQF_ONESHOT, "OMAP HDMI", hdmi);
if (r) {
DSSERR("HDMI IRQ request failed\n");
goto err_free;
}
hdmi->vdda_reg = devm_regulator_get(&pdev->dev, "vdda");
if (IS_ERR(hdmi->vdda_reg)) {
r = PTR_ERR(hdmi->vdda_reg);
if (r != -EPROBE_DEFER)
DSSERR("can't get VDDA regulator\n");
goto err_free;
}
pm_runtime_enable(&pdev->dev);
r = hdmi4_init_output(hdmi);
if (r)
goto err_pm_disable;
r = component_add(&pdev->dev, &hdmi4_component_ops);
if (r)
goto err_uninit_output;
return 0;
err_uninit_output:
hdmi4_uninit_output(hdmi);
err_pm_disable:
pm_runtime_disable(&pdev->dev);
err_free:
kfree(hdmi);
return r;
}
static int hdmi4_remove(struct platform_device *pdev)
{
struct omap_hdmi *hdmi = platform_get_drvdata(pdev);
component_del(&pdev->dev, &hdmi4_component_ops);
hdmi4_uninit_output(hdmi);
pm_runtime_disable(&pdev->dev);
kfree(hdmi);
return 0;
}
static const struct of_device_id hdmi_of_match[] = {
{ .compatible = "ti,omap4-hdmi", },
{},
};
struct platform_driver omapdss_hdmi4hw_driver = {
.probe = hdmi4_probe,
.remove = hdmi4_remove,
.driver = {
.name = "omapdss_hdmi",
.of_match_table = hdmi_of_match,
.suppress_bind_attrs = true,
},
};
| gpl-2.0 |
elephone-dev/P8000-Kernel | drivers/misc/mediatek/mach/mt6735/nb6735m_65c_l1/lcm/hx8392a_dsi_cmd.c | 435 | 10280 | #ifndef BUILD_LK
#include <linux/string.h>
#endif
#include "lcm_drv.h"
// ---------------------------------------------------------------------------
// Local Constants
// ---------------------------------------------------------------------------
#define FRAME_WIDTH (720)
#define FRAME_HEIGHT (1280)
#define REGFLAG_DELAY 0xFE
#define REGFLAG_END_OF_TABLE 0xFF // END OF REGISTERS MARKER
#define LCM_DSI_CMD_MODE 1
// ---------------------------------------------------------------------------
// Local Variables
// ---------------------------------------------------------------------------
static LCM_UTIL_FUNCS lcm_util = {0};
#define SET_RESET_PIN(v) (lcm_util.set_reset_pin((v)))
#define UDELAY(n) (lcm_util.udelay(n))
#define MDELAY(n) (lcm_util.mdelay(n))
// ---------------------------------------------------------------------------
// Local Functions
// ---------------------------------------------------------------------------
#define dsi_set_cmdq_V2(cmd, count, ppara, force_update) lcm_util.dsi_set_cmdq_V2(cmd, count, ppara, force_update)
#define dsi_set_cmdq(pdata, queue_size, force_update) lcm_util.dsi_set_cmdq(pdata, queue_size, force_update)
#define wrtie_cmd(cmd) lcm_util.dsi_write_cmd(cmd)
#define write_regs(addr, pdata, byte_nums) lcm_util.dsi_write_regs(addr, pdata, byte_nums)
#define read_reg lcm_util.dsi_read_reg()
static struct LCM_setting_table {
unsigned cmd;
unsigned char count;
unsigned char para_list[64];
};
static struct LCM_setting_table lcm_initialization_setting[] = {
/*
Note :
Data ID will depends on the following rule.
count of parameters > 1 => Data ID = 0x39
count of parameters = 1 => Data ID = 0x15
count of parameters = 0 => Data ID = 0x05
Structure Format :
{DCS command, count of parameters, {parameter list}}
{REGFLAG_DELAY, milliseconds of time, {}},
...
Setting ending by predefined flag
{REGFLAG_END_OF_TABLE, 0x00, {}}
*/
//sleep out
{0x11, 0, {}},
{REGFLAG_DELAY, 120, {}},
//SET PASSWORD
{0xB9, 3, {0xFF,0x83,0x92}},
{REGFLAG_DELAY, 10, {}},
//set mipi 4 lane
{0xBA, 17, {0x13, 0x83, 0x00, 0xD6,
0xC5, 0x00, 0x09, 0xFF,
0x0F, 0x27, 0x03, 0x21,
0x27, 0x25, 0x20, 0x00,
0x10}},
//SET POWER
{0xB1, 13, {0x7C, 0x00, 0x43, 0xBB,
0x00, 0x1A, 0x1A, 0x2F,
0x36, 0x3F, 0x3F, 0x42,
0x7A}},
//SET DISPLAY RELATED REGISTER
{0xB2, 12, {0x08,0xC8,0x06,0x06,
0x04,0x84,0x00,0xFF,
0x06,0x06,0x04,0x20}},
//SET CYC
{0xB4, 23, {0x00, 0x00, 0x05, 0x0A,
0x8F, 0x06, 0x0A, 0x95,
0x01, 0x07, 0x06, 0x0C,
0x02, 0x08, 0x08, 0x21,
0x04, 0x02, 0x08, 0x01,
0x04, 0x1A, 0x95}},
// set TE on
{0x35, 1, {0x00}},
{0xBF, 4, {0x05, 0x60, 0x02, 0x00}},
// VCOM//64
{0xB6, 1, {0x6A}},
//SET RGB OR BGR
{0x36, 1, {0x08}},
//SET RGB OR BGR
{0xC0, 2, {0x03, 0x94}},
//SET DSI COMMAND MODE
{0xC2, 1, {0x08}},
//SET DSI COMMAND MODE
{0xC6, 4, {0x35, 0x00, 0x20, 0x04}},
//SET PANEL
{0xCC, 1, {0x09}},
{0xD4, 1, {0x00}},
{0xD5, 23, {0x00, 0x01, 0x04, 0x00,
0x01, 0x67, 0x89, 0xAB,
0x45, 0xCC, 0xCC, 0xCC,
0x00, 0x10, 0x54, 0xBA,
0x98, 0x76, 0xCC, 0xCC,
0xCC, 0x00, 0x00}},
{0xD8, 23, {0x00, 0x00, 0x05, 0x00,
0x9A, 0x00, 0x02, 0x95,
0x01, 0x07, 0x06, 0x00,
0x08, 0x08, 0x00, 0x1D,
0x08, 0x08, 0x08, 0x00,
0x00, 0x00, 0x77}},
{0xE0, 34, {0x00, 0x12, 0x19, 0x33,
0x36, 0x3F, 0x28, 0x47,
0x06, 0x0C, 0x0E, 0x12,
0x14, 0x12, 0x14, 0x12,
0x1A, 0x00, 0x12, 0x19,
0x33, 0x36, 0x3F, 0x28,
0x47, 0x06, 0x0C, 0x0E,
0x12, 0x14, 0x12, 0x14,
0x12, 0x1A}},
{0xE1, 34, {0x00, 0x12, 0x19, 0x33,
0x36, 0x3F, 0x28, 0x47,
0x06, 0x0C, 0x0E, 0x12,
0x14, 0x12, 0x14, 0x12,
0x1A, 0x00, 0x12, 0x19,
0x33, 0x36, 0x3F, 0x28,
0x47, 0x06, 0x0C, 0x0E,
0x12, 0x14, 0x12, 0x14,
0x12, 0x1A}},
{0xE2, 34, {0x00, 0x12, 0x19, 0x33,
0x36, 0x3F, 0x28, 0x47,
0x06, 0x0C, 0x0E, 0x12,
0x14, 0x12, 0x14, 0x12,
0x1A, 0x00, 0x12, 0x19,
0x33, 0x36, 0x3F, 0x28,
0x47, 0x06, 0x0C, 0x0E,
0x12, 0x14, 0x12, 0x14,
0x12, 0x1A}},
//SET PIXEL FORMAT
{0x3A, 1, {0x77}},
//sleep out
{0x29, 0, {}},
};
static struct LCM_setting_table lcm_set_window[] = {
{0x2A, 4, {0x00, 0x00, (FRAME_WIDTH>>8), (FRAME_WIDTH&0xFF)}},
{0x2B, 4, {0x00, 0x00, (FRAME_HEIGHT>>8), (FRAME_HEIGHT&0xFF)}},
{REGFLAG_END_OF_TABLE, 0x00, {}}
};
static struct LCM_setting_table lcm_sleep_out_setting[] = {
// Sleep Out
{0x11, 1, {0x00}},
{REGFLAG_DELAY, 120, {}},
// Display ON
{0x29, 1, {0x00}},
{REGFLAG_END_OF_TABLE, 0x00, {}}
};
static struct LCM_setting_table lcm_deep_sleep_mode_in_setting[] = {
// Display off sequence
{0x28, 1, {0x00}},
// Sleep Mode On
{0x10, 1, {0x00}},
{REGFLAG_END_OF_TABLE, 0x00, {}}
};
static struct LCM_setting_table lcm_backlight_level_setting[] = {
{0x51, 1, {0xFF}},
{REGFLAG_END_OF_TABLE, 0x00, {}}
};
static void push_table(struct LCM_setting_table *table, unsigned int count, unsigned char force_update)
{
unsigned int i;
for(i = 0; i < count; i++) {
unsigned cmd;
cmd = table[i].cmd;
switch (cmd) {
case REGFLAG_DELAY :
MDELAY(table[i].count);
break;
case REGFLAG_END_OF_TABLE :
break;
default:
dsi_set_cmdq_V2(cmd, table[i].count, table[i].para_list, force_update);
}
}
}
// ---------------------------------------------------------------------------
// LCM Driver Implementations
// ---------------------------------------------------------------------------
static void lcm_set_util_funcs(const LCM_UTIL_FUNCS *util)
{
memcpy(&lcm_util, util, sizeof(LCM_UTIL_FUNCS));
}
static void lcm_get_params(LCM_PARAMS *params)
{
memset(params, 0, sizeof(LCM_PARAMS));
params->type = LCM_TYPE_DSI;
params->width = FRAME_WIDTH;
params->height = FRAME_HEIGHT;
// enable tearing-free
params->dbi.te_mode = LCM_DBI_TE_MODE_VSYNC_ONLY;
params->dbi.te_edge_polarity = LCM_POLARITY_RISING;
#if (LCM_DSI_CMD_MODE)
params->dsi.mode = CMD_MODE;
params->dsi.switch_mode = SYNC_PULSE_VDO_MODE;
#else
params->dsi.mode = SYNC_PULSE_VDO_MODE;
#endif
// DSI
/* Command mode setting */
params->dsi.LANE_NUM = LCM_FOUR_LANE;
//The following defined the fomat for data coming from LCD engine.
params->dsi.data_format.color_order = LCM_COLOR_ORDER_RGB;
params->dsi.data_format.trans_seq = LCM_DSI_TRANS_SEQ_MSB_FIRST;
params->dsi.data_format.padding = LCM_DSI_PADDING_ON_LSB;
params->dsi.data_format.format = LCM_DSI_FORMAT_RGB888;
// Highly depends on LCD driver capability.
// Not support in MT6573
params->dsi.packet_size=256;
params->dsi.PS=LCM_PACKED_PS_24BIT_RGB888;
params->dsi.PLL_CLOCK = 200;
}
static void lcm_init(void)
{
SET_RESET_PIN(1);
SET_RESET_PIN(0);
MDELAY(10);
SET_RESET_PIN(1);
MDELAY(20);
push_table(lcm_initialization_setting, sizeof(lcm_initialization_setting) / sizeof(struct LCM_setting_table), 1);
}
static void lcm_suspend(void)
{
push_table(lcm_deep_sleep_mode_in_setting, sizeof(lcm_deep_sleep_mode_in_setting) / sizeof(struct LCM_setting_table), 1);
}
static void lcm_resume(void)
{
push_table(lcm_sleep_out_setting, sizeof(lcm_sleep_out_setting) / sizeof(struct LCM_setting_table), 1);
}
static void lcm_update(unsigned int x, unsigned int y,
unsigned int width, unsigned int height)
{
unsigned int x0 = x;
unsigned int y0 = y;
unsigned int x1 = x0 + width - 1;
unsigned int y1 = y0 + height - 1;
unsigned char x0_MSB = ((x0>>8)&0xFF);
unsigned char x0_LSB = (x0&0xFF);
unsigned char x1_MSB = ((x1>>8)&0xFF);
unsigned char x1_LSB = (x1&0xFF);
unsigned char y0_MSB = ((y0>>8)&0xFF);
unsigned char y0_LSB = (y0&0xFF);
unsigned char y1_MSB = ((y1>>8)&0xFF);
unsigned char y1_LSB = (y1&0xFF);
unsigned int data_array[16];
data_array[0]= 0x00053902;
data_array[1]= (x1_MSB<<24)|(x0_LSB<<16)|(x0_MSB<<8)|0x2a;
data_array[2]= (x1_LSB);
data_array[3]= 0x00053902;
data_array[4]= (y1_MSB<<24)|(y0_LSB<<16)|(y0_MSB<<8)|0x2b;
data_array[5]= (y1_LSB);
data_array[6]= 0x002c3909;
dsi_set_cmdq(&data_array, 7, 0);
}
static void lcm_setbacklight(unsigned int level)
{
unsigned int default_level = 145;
unsigned int mapped_level = 0;
//for LGE backlight IC mapping table
if(level > 255)
level = 255;
if(level >0)
mapped_level = default_level+(level)*(255-default_level)/(255);
else
mapped_level=0;
// Refresh value of backlight level.
lcm_backlight_level_setting[0].para_list[0] = mapped_level;
push_table(lcm_backlight_level_setting, sizeof(lcm_backlight_level_setting) / sizeof(struct LCM_setting_table), 1);
}
static void lcm_setpwm(unsigned int divider)
{
// TBD
}
static unsigned int lcm_getpwm(unsigned int divider)
{
// ref freq = 15MHz, B0h setting 0x80, so 80.6% * freq is pwm_clk;
// pwm_clk / 255 / 2(lcm_setpwm() 6th params) = pwm_duration = 23706
unsigned int pwm_clk = 23706 / (1<<divider);
return pwm_clk;
}
LCM_DRIVER hx8392a_dsi_cmd_lcm_drv =
{
.name = "hx8392a_dsi_cmd",
.set_util_funcs = lcm_set_util_funcs,
.get_params = lcm_get_params,
.init = lcm_init,
.suspend = lcm_suspend,
.resume = lcm_resume,
#if (LCM_DSI_CMD_MODE)
.set_backlight = lcm_setbacklight,
//.set_pwm = lcm_setpwm,
//.get_pwm = lcm_getpwm,
.update = lcm_update
#endif
};
| gpl-2.0 |
mm120/gcc-vc4 | libiberty/dyn-string.c | 435 | 11299 | /* An abstract string datatype.
Copyright (C) 1998, 1999, 2000, 2002, 2004 Free Software Foundation, Inc.
Contributed by Mark Mitchell (mark@markmitchell.com).
This file is part of GNU CC.
GNU CC 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.
In addition to the permissions in the GNU General Public License, the
Free Software Foundation gives you unlimited permission to link the
compiled version of this file into combinations with other programs,
and to distribute those combinations without any restriction coming
from the use of this file. (The General Public License restrictions
do apply in other respects; for example, they cover modification of
the file, and distribution when not linked into a combined
executable.)
GNU CC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU CC; see the file COPYING. If not, write to
the Free Software Foundation, 51 Franklin Street - Fifth Floor,
Boston, MA 02110-1301, USA. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include "libiberty.h"
#include "dyn-string.h"
/* Performs in-place initialization of a dyn_string struct. This
function can be used with a dyn_string struct on the stack or
embedded in another object. The contents of of the string itself
are still dynamically allocated. The string initially is capable
of holding at least SPACE characeters, including the terminating
NUL. If SPACE is 0, it will silently be increated to 1.
If RETURN_ON_ALLOCATION_FAILURE is defined and memory allocation
fails, returns 0. Otherwise returns 1. */
int
dyn_string_init (struct dyn_string *ds_struct_ptr, int space)
{
/* We need at least one byte in which to store the terminating NUL. */
if (space == 0)
space = 1;
#ifdef RETURN_ON_ALLOCATION_FAILURE
ds_struct_ptr->s = (char *) malloc (space);
if (ds_struct_ptr->s == NULL)
return 0;
#else
ds_struct_ptr->s = XNEWVEC (char, space);
#endif
ds_struct_ptr->allocated = space;
ds_struct_ptr->length = 0;
ds_struct_ptr->s[0] = '\0';
return 1;
}
/* Create a new dynamic string capable of holding at least SPACE
characters, including the terminating NUL. If SPACE is 0, it will
be silently increased to 1. If RETURN_ON_ALLOCATION_FAILURE is
defined and memory allocation fails, returns NULL. Otherwise
returns the newly allocated string. */
dyn_string_t
dyn_string_new (int space)
{
dyn_string_t result;
#ifdef RETURN_ON_ALLOCATION_FAILURE
result = (dyn_string_t) malloc (sizeof (struct dyn_string));
if (result == NULL)
return NULL;
if (!dyn_string_init (result, space))
{
free (result);
return NULL;
}
#else
result = XNEW (struct dyn_string);
dyn_string_init (result, space);
#endif
return result;
}
/* Free the memory used by DS. */
void
dyn_string_delete (dyn_string_t ds)
{
free (ds->s);
free (ds);
}
/* Returns the contents of DS in a buffer allocated with malloc. It
is the caller's responsibility to deallocate the buffer using free.
DS is then set to the empty string. Deletes DS itself. */
char*
dyn_string_release (dyn_string_t ds)
{
/* Store the old buffer. */
char* result = ds->s;
/* The buffer is no longer owned by DS. */
ds->s = NULL;
/* Delete DS. */
free (ds);
/* Return the old buffer. */
return result;
}
/* Increase the capacity of DS so it can hold at least SPACE
characters, plus the terminating NUL. This function will not (at
present) reduce the capacity of DS. Returns DS on success.
If RETURN_ON_ALLOCATION_FAILURE is defined and a memory allocation
operation fails, deletes DS and returns NULL. */
dyn_string_t
dyn_string_resize (dyn_string_t ds, int space)
{
int new_allocated = ds->allocated;
/* Increase SPACE to hold the NUL termination. */
++space;
/* Increase allocation by factors of two. */
while (space > new_allocated)
new_allocated *= 2;
if (new_allocated != ds->allocated)
{
ds->allocated = new_allocated;
/* We actually need more space. */
#ifdef RETURN_ON_ALLOCATION_FAILURE
ds->s = (char *) realloc (ds->s, ds->allocated);
if (ds->s == NULL)
{
free (ds);
return NULL;
}
#else
ds->s = XRESIZEVEC (char, ds->s, ds->allocated);
#endif
}
return ds;
}
/* Sets the contents of DS to the empty string. */
void
dyn_string_clear (dyn_string_t ds)
{
/* A dyn_string always has room for at least the NUL terminator. */
ds->s[0] = '\0';
ds->length = 0;
}
/* Makes the contents of DEST the same as the contents of SRC. DEST
and SRC must be distinct. Returns 1 on success. On failure, if
RETURN_ON_ALLOCATION_FAILURE, deletes DEST and returns 0. */
int
dyn_string_copy (dyn_string_t dest, dyn_string_t src)
{
if (dest == src)
abort ();
/* Make room in DEST. */
if (dyn_string_resize (dest, src->length) == NULL)
return 0;
/* Copy DEST into SRC. */
strcpy (dest->s, src->s);
/* Update the size of DEST. */
dest->length = src->length;
return 1;
}
/* Copies SRC, a NUL-terminated string, into DEST. Returns 1 on
success. On failure, if RETURN_ON_ALLOCATION_FAILURE, deletes DEST
and returns 0. */
int
dyn_string_copy_cstr (dyn_string_t dest, const char *src)
{
int length = strlen (src);
/* Make room in DEST. */
if (dyn_string_resize (dest, length) == NULL)
return 0;
/* Copy DEST into SRC. */
strcpy (dest->s, src);
/* Update the size of DEST. */
dest->length = length;
return 1;
}
/* Inserts SRC at the beginning of DEST. DEST is expanded as
necessary. SRC and DEST must be distinct. Returns 1 on success.
On failure, if RETURN_ON_ALLOCATION_FAILURE, deletes DEST and
returns 0. */
int
dyn_string_prepend (dyn_string_t dest, dyn_string_t src)
{
return dyn_string_insert (dest, 0, src);
}
/* Inserts SRC, a NUL-terminated string, at the beginning of DEST.
DEST is expanded as necessary. Returns 1 on success. On failure,
if RETURN_ON_ALLOCATION_FAILURE, deletes DEST and returns 0. */
int
dyn_string_prepend_cstr (dyn_string_t dest, const char *src)
{
return dyn_string_insert_cstr (dest, 0, src);
}
/* Inserts SRC into DEST starting at position POS. DEST is expanded
as necessary. SRC and DEST must be distinct. Returns 1 on
success. On failure, if RETURN_ON_ALLOCATION_FAILURE, deletes DEST
and returns 0. */
int
dyn_string_insert (dyn_string_t dest, int pos, dyn_string_t src)
{
int i;
if (src == dest)
abort ();
if (dyn_string_resize (dest, dest->length + src->length) == NULL)
return 0;
/* Make room for the insertion. Be sure to copy the NUL. */
for (i = dest->length; i >= pos; --i)
dest->s[i + src->length] = dest->s[i];
/* Splice in the new stuff. */
strncpy (dest->s + pos, src->s, src->length);
/* Compute the new length. */
dest->length += src->length;
return 1;
}
/* Inserts SRC, a NUL-terminated string, into DEST starting at
position POS. DEST is expanded as necessary. Returns 1 on
success. On failure, RETURN_ON_ALLOCATION_FAILURE, deletes DEST
and returns 0. */
int
dyn_string_insert_cstr (dyn_string_t dest, int pos, const char *src)
{
int i;
int length = strlen (src);
if (dyn_string_resize (dest, dest->length + length) == NULL)
return 0;
/* Make room for the insertion. Be sure to copy the NUL. */
for (i = dest->length; i >= pos; --i)
dest->s[i + length] = dest->s[i];
/* Splice in the new stuff. */
strncpy (dest->s + pos, src, length);
/* Compute the new length. */
dest->length += length;
return 1;
}
/* Inserts character C into DEST starting at position POS. DEST is
expanded as necessary. Returns 1 on success. On failure,
RETURN_ON_ALLOCATION_FAILURE, deletes DEST and returns 0. */
int
dyn_string_insert_char (dyn_string_t dest, int pos, int c)
{
int i;
if (dyn_string_resize (dest, dest->length + 1) == NULL)
return 0;
/* Make room for the insertion. Be sure to copy the NUL. */
for (i = dest->length; i >= pos; --i)
dest->s[i + 1] = dest->s[i];
/* Add the new character. */
dest->s[pos] = c;
/* Compute the new length. */
++dest->length;
return 1;
}
/* Append S to DS, resizing DS if necessary. Returns 1 on success.
On failure, if RETURN_ON_ALLOCATION_FAILURE, deletes DEST and
returns 0. */
int
dyn_string_append (dyn_string_t dest, dyn_string_t s)
{
if (dyn_string_resize (dest, dest->length + s->length) == 0)
return 0;
strcpy (dest->s + dest->length, s->s);
dest->length += s->length;
return 1;
}
/* Append the NUL-terminated string S to DS, resizing DS if necessary.
Returns 1 on success. On failure, if RETURN_ON_ALLOCATION_FAILURE,
deletes DEST and returns 0. */
int
dyn_string_append_cstr (dyn_string_t dest, const char *s)
{
int len = strlen (s);
/* The new length is the old length plus the size of our string, plus
one for the null at the end. */
if (dyn_string_resize (dest, dest->length + len) == NULL)
return 0;
strcpy (dest->s + dest->length, s);
dest->length += len;
return 1;
}
/* Appends C to the end of DEST. Returns 1 on success. On failure,
if RETURN_ON_ALLOCATION_FAILURE, deletes DEST and returns 0. */
int
dyn_string_append_char (dyn_string_t dest, int c)
{
/* Make room for the extra character. */
if (dyn_string_resize (dest, dest->length + 1) == NULL)
return 0;
/* Append the character; it will overwrite the old NUL. */
dest->s[dest->length] = c;
/* Add a new NUL at the end. */
dest->s[dest->length + 1] = '\0';
/* Update the length. */
++(dest->length);
return 1;
}
/* Sets the contents of DEST to the substring of SRC starting at START
and ending before END. START must be less than or equal to END,
and both must be between zero and the length of SRC, inclusive.
Returns 1 on success. On failure, if RETURN_ON_ALLOCATION_FAILURE,
deletes DEST and returns 0. */
int
dyn_string_substring (dyn_string_t dest, dyn_string_t src,
int start, int end)
{
int i;
int length = end - start;
if (start > end || start > src->length || end > src->length)
abort ();
/* Make room for the substring. */
if (dyn_string_resize (dest, length) == NULL)
return 0;
/* Copy the characters in the substring, */
for (i = length; --i >= 0; )
dest->s[i] = src->s[start + i];
/* NUL-terimate the result. */
dest->s[length] = '\0';
/* Record the length of the substring. */
dest->length = length;
return 1;
}
/* Returns non-zero if DS1 and DS2 have the same contents. */
int
dyn_string_eq (dyn_string_t ds1, dyn_string_t ds2)
{
/* If DS1 and DS2 have different lengths, they must not be the same. */
if (ds1->length != ds2->length)
return 0;
else
return !strcmp (ds1->s, ds2->s);
}
| gpl-2.0 |
surdupetru/android_kernel_huawei_msm8916-caf | drivers/soc/qcom/qmi_interface.c | 435 | 55955 | /* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/io.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/list.h>
#include <linux/socket.h>
#include <linux/gfp.h>
#include <linux/qmi_encdec.h>
#include <linux/workqueue.h>
#include <linux/mutex.h>
#include <linux/hashtable.h>
#include <linux/ipc_router.h>
#include <soc/qcom/msm_qmi_interface.h>
#include "qmi_interface_priv.h"
#define BUILD_INSTANCE_ID(vers, ins) (((vers) & 0xFF) | (((ins) & 0xFF) << 8))
#define LOOKUP_MASK 0xFFFFFFFF
#define MAX_WQ_NAME_LEN 20
static LIST_HEAD(svc_event_nb_list);
static DEFINE_MUTEX(svc_event_nb_list_lock);
struct qmi_notify_event_work {
unsigned event;
void *oob_data;
size_t oob_data_len;
void *priv;
struct work_struct work;
};
static void qmi_notify_event_worker(struct work_struct *work);
#define HANDLE_HASH_TBL_SZ 1
static DEFINE_HASHTABLE(handle_hash_tbl, HANDLE_HASH_TBL_SZ);
static DEFINE_MUTEX(handle_hash_tbl_lock);
struct elem_info qmi_response_type_v01_ei[] = {
{
.data_type = QMI_SIGNED_2_BYTE_ENUM,
.elem_len = 1,
.elem_size = sizeof(uint16_t),
.is_array = NO_ARRAY,
.tlv_type = QMI_COMMON_TLV_TYPE,
.offset = offsetof(struct qmi_response_type_v01,
result),
.ei_array = NULL,
},
{
.data_type = QMI_SIGNED_2_BYTE_ENUM,
.elem_len = 1,
.elem_size = sizeof(uint16_t),
.is_array = NO_ARRAY,
.tlv_type = QMI_COMMON_TLV_TYPE,
.offset = offsetof(struct qmi_response_type_v01,
error),
.ei_array = NULL,
},
{
.data_type = QMI_EOTI,
.elem_len = 0,
.elem_size = 0,
.is_array = NO_ARRAY,
.tlv_type = QMI_COMMON_TLV_TYPE,
.offset = 0,
.ei_array = NULL,
},
};
struct elem_info qmi_error_resp_type_v01_ei[] = {
{
.data_type = QMI_STRUCT,
.elem_len = 1,
.elem_size = sizeof(struct qmi_response_type_v01),
.is_array = NO_ARRAY,
.tlv_type = 0x02,
.offset = 0,
.ei_array = qmi_response_type_v01_ei,
},
{
.data_type = QMI_EOTI,
.elem_len = 0,
.elem_size = 0,
.is_array = NO_ARRAY,
.tlv_type = 0x00,
.offset = 0,
.ei_array = NULL,
},
};
struct msg_desc err_resp_desc = {
.max_msg_len = 7,
.msg_id = 0,
.ei_array = qmi_error_resp_type_v01_ei,
};
static void svc_resume_tx_worker(struct work_struct *work);
static void clean_txn_info(struct qmi_handle *handle);
/**
* add_req_handle() - Create and Add a request handle to the connection
* @conn_h: Connection handle over which the request has arrived.
* @msg_id: Message ID of the request.
* @txn_id: Transaction ID of the request.
*
* @return: Pointer to request handle on success, NULL on error.
*
* This function creates a request handle to track the request that arrives
* on a connection. This function then adds it to the connection's request
* handle list.
*/
static struct req_handle *add_req_handle(struct qmi_svc_clnt_conn *conn_h,
uint16_t msg_id, uint16_t txn_id)
{
struct req_handle *req_h;
req_h = kmalloc(sizeof(struct req_handle), GFP_KERNEL);
if (!req_h) {
pr_err("%s: Error allocating req_h\n", __func__);
return NULL;
}
req_h->conn_h = conn_h;
req_h->msg_id = msg_id;
req_h->txn_id = txn_id;
list_add_tail(&req_h->list, &conn_h->req_handle_list);
return req_h;
}
/**
* verify_req_handle() - Verify the validity of a request handle
* @conn_h: Connection handle over which the request has arrived.
* @req_h: Request handle to be verified.
*
* @return: true on success, false on failure.
*
* This function is used to check if the request handle is present in
* the connection handle.
*/
static bool verify_req_handle(struct qmi_svc_clnt_conn *conn_h,
struct req_handle *req_h)
{
struct req_handle *temp_req_h;
list_for_each_entry(temp_req_h, &conn_h->req_handle_list, list) {
if (temp_req_h == req_h)
return true;
}
return false;
}
/**
* rmv_req_handle() - Remove and destroy the request handle
* @req_h: Request handle to be removed and destroyed.
*
* @return: 0.
*/
static int rmv_req_handle(struct req_handle *req_h)
{
list_del(&req_h->list);
kfree(req_h);
return 0;
}
/**
* add_svc_clnt_conn() - Create and add a connection handle to a service
* @handle: QMI handle in which the service is hosted.
* @clnt_addr: Address of the client connecting with the service.
* @clnt_addr_len: Length of the client address.
*
* @return: Pointer to connection handle on success, NULL on error.
*
* This function is used to create a connection handle that binds the service
* with a client. This function is called on a service's QMI handle when a
* client sends its first message to the service.
*
* This function must be called with handle->handle_lock locked.
*/
static struct qmi_svc_clnt_conn *add_svc_clnt_conn(
struct qmi_handle *handle, void *clnt_addr, size_t clnt_addr_len)
{
struct qmi_svc_clnt_conn *conn_h;
conn_h = kmalloc(sizeof(struct qmi_svc_clnt_conn), GFP_KERNEL);
if (!conn_h) {
pr_err("%s: Error allocating conn_h\n", __func__);
return NULL;
}
conn_h->clnt_addr = kmalloc(clnt_addr_len, GFP_KERNEL);
if (!conn_h->clnt_addr) {
pr_err("%s: Error allocating clnt_addr\n", __func__);
return NULL;
}
INIT_LIST_HEAD(&conn_h->list);
conn_h->svc_handle = handle;
memcpy(conn_h->clnt_addr, clnt_addr, clnt_addr_len);
conn_h->clnt_addr_len = clnt_addr_len;
INIT_LIST_HEAD(&conn_h->req_handle_list);
INIT_DELAYED_WORK(&conn_h->resume_tx_work, svc_resume_tx_worker);
INIT_LIST_HEAD(&conn_h->pending_txn_list);
mutex_init(&conn_h->pending_txn_lock);
list_add_tail(&conn_h->list, &handle->conn_list);
return conn_h;
}
/**
* find_svc_clnt_conn() - Find the existence of a client<->service connection
* @handle: Service's QMI handle.
* @clnt_addr: Address of the client to be present in the connection.
* @clnt_addr_len: Length of the client address.
*
* @return: Pointer to connection handle if the matching connection is found,
* NULL if the connection is not found.
*
* This function is used to find the existence of a client<->service connection
* handle in a service's QMI handle. This function tries to match the client
* address in the existing connections.
*
* This function must be called with handle->handle_lock locked.
*/
static struct qmi_svc_clnt_conn *find_svc_clnt_conn(
struct qmi_handle *handle, void *clnt_addr, size_t clnt_addr_len)
{
struct qmi_svc_clnt_conn *conn_h;
list_for_each_entry(conn_h, &handle->conn_list, list) {
if (!memcmp(conn_h->clnt_addr, clnt_addr, clnt_addr_len))
return conn_h;
}
return NULL;
}
/**
* verify_svc_clnt_conn() - Verify the existence of a connection handle
* @handle: Service's QMI handle.
* @conn_h: Connection handle to be verified.
*
* @return: true on success, false on failure.
*
* This function is used to verify the existence of a connection in the
* connection list maintained by the service.
*
* This function must be called with handle->handle_lock locked.
*/
static bool verify_svc_clnt_conn(struct qmi_handle *handle,
struct qmi_svc_clnt_conn *conn_h)
{
struct qmi_svc_clnt_conn *temp_conn_h;
list_for_each_entry(temp_conn_h, &handle->conn_list, list) {
if (temp_conn_h == conn_h)
return true;
}
return false;
}
/**
* rmv_svc_clnt_conn() - Remove the connection handle info from the service
* @conn_h: Connection handle to be removed.
*
* This function removes a connection handle from a service's QMI handle.
*
* This function must be called with handle->handle_lock locked.
*/
static void rmv_svc_clnt_conn(struct qmi_svc_clnt_conn *conn_h)
{
struct req_handle *req_h, *temp_req_h;
struct qmi_txn *txn_h, *temp_txn_h;
list_del(&conn_h->list);
list_for_each_entry_safe(req_h, temp_req_h,
&conn_h->req_handle_list, list)
rmv_req_handle(req_h);
mutex_lock(&conn_h->pending_txn_lock);
list_for_each_entry_safe(txn_h, temp_txn_h,
&conn_h->pending_txn_list, list) {
list_del(&txn_h->list);
kfree(txn_h->enc_data);
kfree(txn_h);
}
mutex_unlock(&conn_h->pending_txn_lock);
flush_delayed_work(&conn_h->resume_tx_work);
kfree(conn_h->clnt_addr);
kfree(conn_h);
}
/**
* qmi_event_notify() - Notification function to QMI client/service interface
* @event: Type of event that gets notified.
* @oob_data: Any out-of-band data associated with event.
* @oob_data_len: Length of the out-of-band data, if any.
* @priv: Private data.
*
* This function is called by the underlying transport to notify the QMI
* interface regarding any incoming event. This function is registered by
* QMI interface when it opens a port/handle with the underlying transport.
*/
static void qmi_event_notify(unsigned event, void *oob_data,
size_t oob_data_len, void *priv)
{
struct qmi_notify_event_work *notify_work;
struct qmi_handle *handle;
uint32_t key = 0;
notify_work = kmalloc(sizeof(struct qmi_notify_event_work),
GFP_KERNEL);
if (!notify_work) {
pr_err("%s: Couldn't notify %d event to %p\n",
__func__, event, priv);
return;
}
notify_work->event = event;
if (oob_data) {
notify_work->oob_data = kmalloc(oob_data_len, GFP_KERNEL);
if (!notify_work->oob_data) {
pr_err("%s: Couldn't allocate oob_data @ %d to %p\n",
__func__, event, priv);
kfree(notify_work);
return;
}
memcpy(notify_work->oob_data, oob_data, oob_data_len);
} else {
notify_work->oob_data = NULL;
}
notify_work->oob_data_len = oob_data_len;
notify_work->priv = priv;
INIT_WORK(¬ify_work->work, qmi_notify_event_worker);
mutex_lock(&handle_hash_tbl_lock);
hash_for_each_possible(handle_hash_tbl, handle, handle_hash, key) {
if (handle == (struct qmi_handle *)priv) {
queue_work(handle->handle_wq,
¬ify_work->work);
mutex_unlock(&handle_hash_tbl_lock);
return;
}
}
mutex_unlock(&handle_hash_tbl_lock);
kfree(notify_work->oob_data);
kfree(notify_work);
}
static void qmi_notify_event_worker(struct work_struct *work)
{
struct qmi_notify_event_work *notify_work =
container_of(work, struct qmi_notify_event_work, work);
struct qmi_handle *handle = (struct qmi_handle *)notify_work->priv;
unsigned long flags;
if (!handle)
return;
mutex_lock(&handle->handle_lock);
if (handle->handle_reset) {
mutex_unlock(&handle->handle_lock);
kfree(notify_work->oob_data);
kfree(notify_work);
return;
}
switch (notify_work->event) {
case IPC_ROUTER_CTRL_CMD_DATA:
spin_lock_irqsave(&handle->notify_lock, flags);
handle->notify(handle, QMI_RECV_MSG, handle->notify_priv);
spin_unlock_irqrestore(&handle->notify_lock, flags);
break;
case IPC_ROUTER_CTRL_CMD_RESUME_TX:
if (handle->handle_type == QMI_CLIENT_HANDLE) {
queue_delayed_work(handle->handle_wq,
&handle->resume_tx_work,
msecs_to_jiffies(0));
} else if (handle->handle_type == QMI_SERVICE_HANDLE) {
struct msm_ipc_addr rtx_addr = {0};
struct qmi_svc_clnt_conn *conn_h;
union rr_control_msg *msg;
msg = (union rr_control_msg *)notify_work->oob_data;
rtx_addr.addrtype = MSM_IPC_ADDR_ID;
rtx_addr.addr.port_addr.node_id = msg->cli.node_id;
rtx_addr.addr.port_addr.port_id = msg->cli.port_id;
conn_h = find_svc_clnt_conn(handle, &rtx_addr,
sizeof(rtx_addr));
if (conn_h)
queue_delayed_work(handle->handle_wq,
&conn_h->resume_tx_work,
msecs_to_jiffies(0));
}
break;
case IPC_ROUTER_CTRL_CMD_NEW_SERVER:
case IPC_ROUTER_CTRL_CMD_REMOVE_SERVER:
case IPC_ROUTER_CTRL_CMD_REMOVE_CLIENT:
queue_delayed_work(handle->handle_wq,
&handle->ctl_work, msecs_to_jiffies(0));
break;
default:
break;
}
mutex_unlock(&handle->handle_lock);
kfree(notify_work->oob_data);
kfree(notify_work);
}
/**
* clnt_resume_tx_worker() - Handle the Resume_Tx event
* @work : Pointer to the work strcuture.
*
* This function handles the resume_tx event for any QMI client that
* exists in the kernel space. This function parses the pending_txn_list of
* the handle and attempts a send for each transaction in that list.
*/
static void clnt_resume_tx_worker(struct work_struct *work)
{
struct delayed_work *rtx_work = to_delayed_work(work);
struct qmi_handle *handle =
container_of(rtx_work, struct qmi_handle, resume_tx_work);
struct qmi_txn *pend_txn, *temp_txn;
int ret;
uint16_t msg_id;
mutex_lock(&handle->handle_lock);
if (handle->handle_reset)
goto out_clnt_handle_rtx;
list_for_each_entry_safe(pend_txn, temp_txn,
&handle->pending_txn_list, list) {
ret = msm_ipc_router_send_msg(
(struct msm_ipc_port *)handle->src_port,
(struct msm_ipc_addr *)handle->dest_info,
pend_txn->enc_data, pend_txn->enc_data_len);
if (ret == -EAGAIN)
break;
msg_id = ((struct qmi_header *)pend_txn->enc_data)->msg_id;
kfree(pend_txn->enc_data);
if (ret < 0) {
pr_err("%s: Sending transaction %d from port %d failed",
__func__, pend_txn->txn_id,
((struct msm_ipc_port *)handle->src_port)->
this_port.port_id);
if (pend_txn->type == QMI_ASYNC_TXN) {
pend_txn->resp_cb(pend_txn->handle,
msg_id, pend_txn->resp,
pend_txn->resp_cb_data,
ret);
list_del(&pend_txn->list);
kfree(pend_txn);
} else if (pend_txn->type == QMI_SYNC_TXN) {
pend_txn->send_stat = ret;
wake_up(&pend_txn->wait_q);
}
} else {
list_del(&pend_txn->list);
list_add_tail(&pend_txn->list, &handle->txn_list);
}
}
out_clnt_handle_rtx:
mutex_unlock(&handle->handle_lock);
}
/**
* svc_resume_tx_worker() - Handle the Resume_Tx event
* @work : Pointer to the work strcuture.
*
* This function handles the resume_tx event for any QMI service that
* exists in the kernel space. This function parses the pending_txn_list of
* the connection handle and attempts a send for each transaction in that list.
*/
static void svc_resume_tx_worker(struct work_struct *work)
{
struct delayed_work *rtx_work = to_delayed_work(work);
struct qmi_svc_clnt_conn *conn_h =
container_of(rtx_work, struct qmi_svc_clnt_conn,
resume_tx_work);
struct qmi_handle *handle = (struct qmi_handle *)conn_h->svc_handle;
struct qmi_txn *pend_txn, *temp_txn;
int ret;
mutex_lock(&conn_h->pending_txn_lock);
if (handle->handle_reset)
goto out_svc_handle_rtx;
list_for_each_entry_safe(pend_txn, temp_txn,
&conn_h->pending_txn_list, list) {
ret = msm_ipc_router_send_msg(
(struct msm_ipc_port *)handle->src_port,
(struct msm_ipc_addr *)conn_h->clnt_addr,
pend_txn->enc_data, pend_txn->enc_data_len);
if (ret == -EAGAIN)
break;
if (ret < 0)
pr_err("%s: Sending transaction %d from port %d failed",
__func__, pend_txn->txn_id,
((struct msm_ipc_port *)handle->src_port)->
this_port.port_id);
list_del(&pend_txn->list);
kfree(pend_txn->enc_data);
kfree(pend_txn);
}
out_svc_handle_rtx:
mutex_unlock(&conn_h->pending_txn_lock);
}
/**
* handle_rmv_server() - Handle the server exit event
* @handle: Client handle on which the server exit event is received.
* @ctl_msg: Information about the server that is exiting.
*
* @return: 0 on success, standard Linux error codes on failure.
*
* This function must be called with handle->handle_lock locked.
*/
static int handle_rmv_server(struct qmi_handle *handle,
union rr_control_msg *ctl_msg)
{
struct msm_ipc_addr *svc_addr;
unsigned long flags;
if (unlikely(!handle->dest_info))
return 0;
svc_addr = (struct msm_ipc_addr *)(handle->dest_info);
if (svc_addr->addr.port_addr.node_id == ctl_msg->srv.node_id &&
svc_addr->addr.port_addr.port_id == ctl_msg->srv.port_id) {
/* Wakeup any threads waiting for the response */
handle->handle_reset = 1;
clean_txn_info(handle);
spin_lock_irqsave(&handle->notify_lock, flags);
handle->notify(handle, QMI_SERVER_EXIT, handle->notify_priv);
spin_unlock_irqrestore(&handle->notify_lock, flags);
}
return 0;
}
/**
* handle_rmv_client() - Handle the client exit event
* @handle: Service handle on which the client exit event is received.
* @ctl_msg: Information about the client that is exiting.
*
* @return: 0 on success, standard Linux error codes on failure.
*
* This function must be called with handle->handle_lock locked.
*/
static int handle_rmv_client(struct qmi_handle *handle,
union rr_control_msg *ctl_msg)
{
struct qmi_svc_clnt_conn *conn_h;
struct msm_ipc_addr clnt_addr = {0};
unsigned long flags;
clnt_addr.addrtype = MSM_IPC_ADDR_ID;
clnt_addr.addr.port_addr.node_id = ctl_msg->cli.node_id;
clnt_addr.addr.port_addr.port_id = ctl_msg->cli.port_id;
conn_h = find_svc_clnt_conn(handle, &clnt_addr, sizeof(clnt_addr));
if (conn_h) {
spin_lock_irqsave(&handle->notify_lock, flags);
handle->svc_ops_options->disconnect_cb(handle, conn_h);
spin_unlock_irqrestore(&handle->notify_lock, flags);
rmv_svc_clnt_conn(conn_h);
}
return 0;
}
/**
* handle_ctl_msg: Worker function to handle the control events
* @work: Work item to map the QMI handle.
*
* This function is a worker function to handle the incoming control
* events like REMOVE_SERVER/REMOVE_CLIENT. The work item is unique
* to a handle and the workker function handles the control events on
* a specific handle.
*/
static void handle_ctl_msg(struct work_struct *work)
{
struct delayed_work *ctl_work = to_delayed_work(work);
struct qmi_handle *handle =
container_of(ctl_work, struct qmi_handle, ctl_work);
unsigned int ctl_msg_len;
union rr_control_msg *ctl_msg = NULL;
struct msm_ipc_addr src_addr;
int rc;
mutex_lock(&handle->handle_lock);
while (1) {
if (handle->handle_reset)
break;
/* Read the messages */
rc = msm_ipc_router_read_msg(
(struct msm_ipc_port *)(handle->ctl_port),
&src_addr, (unsigned char **)&ctl_msg, &ctl_msg_len);
if (rc == -ENOMSG)
break;
if (rc < 0) {
pr_err("%s: Read failed %d\n", __func__, rc);
break;
}
if (ctl_msg->cmd == IPC_ROUTER_CTRL_CMD_REMOVE_SERVER &&
handle->handle_type == QMI_CLIENT_HANDLE)
handle_rmv_server(handle, ctl_msg);
else if (ctl_msg->cmd == IPC_ROUTER_CTRL_CMD_REMOVE_CLIENT &&
handle->handle_type == QMI_SERVICE_HANDLE)
handle_rmv_client(handle, ctl_msg);
kfree(ctl_msg);
}
mutex_unlock(&handle->handle_lock);
return;
}
struct qmi_handle *qmi_handle_create(
void (*notify)(struct qmi_handle *handle,
enum qmi_event_type event, void *notify_priv),
void *notify_priv)
{
struct qmi_handle *temp_handle;
struct msm_ipc_port *port_ptr, *ctl_port_ptr;
static uint32_t handle_count;
char wq_name[MAX_WQ_NAME_LEN];
temp_handle = kzalloc(sizeof(struct qmi_handle), GFP_KERNEL);
if (!temp_handle) {
pr_err("%s: Failure allocating client handle\n", __func__);
return NULL;
}
mutex_lock(&handle_hash_tbl_lock);
handle_count++;
scnprintf(wq_name, MAX_WQ_NAME_LEN, "qmi_hndl%08x", handle_count);
hash_add(handle_hash_tbl, &temp_handle->handle_hash, 0);
temp_handle->handle_wq = create_singlethread_workqueue(wq_name);
mutex_unlock(&handle_hash_tbl_lock);
if (!temp_handle->handle_wq) {
pr_err("%s: Couldn't create workqueue for handle\n", __func__);
goto handle_create_err1;
}
/* Initialize common elements */
temp_handle->handle_type = QMI_CLIENT_HANDLE;
temp_handle->next_txn_id = 1;
mutex_init(&temp_handle->handle_lock);
spin_lock_init(&temp_handle->notify_lock);
temp_handle->notify = notify;
temp_handle->notify_priv = notify_priv;
init_waitqueue_head(&temp_handle->reset_waitq);
INIT_DELAYED_WORK(&temp_handle->resume_tx_work, clnt_resume_tx_worker);
INIT_DELAYED_WORK(&temp_handle->ctl_work, handle_ctl_msg);
/* Initialize client specific elements */
INIT_LIST_HEAD(&temp_handle->txn_list);
INIT_LIST_HEAD(&temp_handle->pending_txn_list);
/* Initialize service specific elements */
INIT_LIST_HEAD(&temp_handle->conn_list);
port_ptr = msm_ipc_router_create_port(qmi_event_notify,
(void *)temp_handle);
if (!port_ptr) {
pr_err("%s: IPC router port creation failed\n", __func__);
goto handle_create_err2;
}
ctl_port_ptr = msm_ipc_router_create_port(qmi_event_notify,
(void *)temp_handle);
if (!ctl_port_ptr) {
pr_err("%s: IPC router ctl port creation failed\n", __func__);
goto handle_create_err3;
}
msm_ipc_router_bind_control_port(ctl_port_ptr);
temp_handle->src_port = port_ptr;
temp_handle->ctl_port = ctl_port_ptr;
return temp_handle;
handle_create_err3:
msm_ipc_router_close_port(port_ptr);
handle_create_err2:
destroy_workqueue(temp_handle->handle_wq);
handle_create_err1:
mutex_lock(&handle_hash_tbl_lock);
hash_del(&temp_handle->handle_hash);
mutex_unlock(&handle_hash_tbl_lock);
kfree(temp_handle);
return NULL;
}
EXPORT_SYMBOL(qmi_handle_create);
static void clean_txn_info(struct qmi_handle *handle)
{
struct qmi_txn *txn_handle, *temp_txn_handle, *pend_txn;
list_for_each_entry_safe(pend_txn, temp_txn_handle,
&handle->pending_txn_list, list) {
if (pend_txn->type == QMI_ASYNC_TXN) {
list_del(&pend_txn->list);
pend_txn->resp_cb(pend_txn->handle,
((struct qmi_header *)
pend_txn->enc_data)->msg_id,
pend_txn->resp, pend_txn->resp_cb_data,
-ENETRESET);
kfree(pend_txn->enc_data);
kfree(pend_txn);
} else if (pend_txn->type == QMI_SYNC_TXN) {
kfree(pend_txn->enc_data);
wake_up(&pend_txn->wait_q);
}
}
list_for_each_entry_safe(txn_handle, temp_txn_handle,
&handle->txn_list, list) {
if (txn_handle->type == QMI_ASYNC_TXN) {
list_del(&txn_handle->list);
kfree(txn_handle);
} else if (txn_handle->type == QMI_SYNC_TXN) {
wake_up(&txn_handle->wait_q);
}
}
}
int qmi_handle_destroy(struct qmi_handle *handle)
{
int rc;
if (!handle)
return -EINVAL;
mutex_lock(&handle_hash_tbl_lock);
hash_del(&handle->handle_hash);
mutex_unlock(&handle_hash_tbl_lock);
mutex_lock(&handle->handle_lock);
handle->handle_reset = 1;
clean_txn_info(handle);
msm_ipc_router_close_port((struct msm_ipc_port *)(handle->ctl_port));
msm_ipc_router_close_port((struct msm_ipc_port *)(handle->src_port));
mutex_unlock(&handle->handle_lock);
flush_workqueue(handle->handle_wq);
destroy_workqueue(handle->handle_wq);
rc = wait_event_interruptible(handle->reset_waitq,
list_empty(&handle->txn_list));
kfree(handle->dest_info);
kfree(handle);
return 0;
}
EXPORT_SYMBOL(qmi_handle_destroy);
int qmi_register_ind_cb(struct qmi_handle *handle,
void (*ind_cb)(struct qmi_handle *handle,
unsigned int msg_id, void *msg,
unsigned int msg_len, void *ind_cb_priv),
void *ind_cb_priv)
{
if (!handle)
return -EINVAL;
mutex_lock(&handle->handle_lock);
if (handle->handle_reset) {
mutex_unlock(&handle->handle_lock);
return -ENETRESET;
}
handle->ind_cb = ind_cb;
handle->ind_cb_priv = ind_cb_priv;
mutex_unlock(&handle->handle_lock);
return 0;
}
EXPORT_SYMBOL(qmi_register_ind_cb);
static int qmi_encode_and_send_req(struct qmi_txn **ret_txn_handle,
struct qmi_handle *handle, enum txn_type type,
struct msg_desc *req_desc, void *req, unsigned int req_len,
struct msg_desc *resp_desc, void *resp, unsigned int resp_len,
void (*resp_cb)(struct qmi_handle *handle,
unsigned int msg_id, void *msg,
void *resp_cb_data, int stat),
void *resp_cb_data)
{
struct qmi_txn *txn_handle;
int rc, encoded_req_len;
void *encoded_req;
if (!handle || !handle->dest_info ||
!req_desc || !resp_desc || !resp)
return -EINVAL;
if ((!req && req_len) || (!req_len && req))
return -EINVAL;
mutex_lock(&handle->handle_lock);
if (handle->handle_reset) {
mutex_unlock(&handle->handle_lock);
return -ENETRESET;
}
/* Allocate Transaction Info */
txn_handle = kzalloc(sizeof(struct qmi_txn), GFP_KERNEL);
if (!txn_handle) {
pr_err("%s: Failed to allocate txn handle\n", __func__);
mutex_unlock(&handle->handle_lock);
return -ENOMEM;
}
txn_handle->type = type;
INIT_LIST_HEAD(&txn_handle->list);
init_waitqueue_head(&txn_handle->wait_q);
/* Cache the parameters passed & mark it as sync*/
txn_handle->handle = handle;
txn_handle->resp_desc = resp_desc;
txn_handle->resp = resp;
txn_handle->resp_len = resp_len;
txn_handle->resp_received = 0;
txn_handle->resp_cb = resp_cb;
txn_handle->resp_cb_data = resp_cb_data;
txn_handle->enc_data = NULL;
txn_handle->enc_data_len = 0;
/* Encode the request msg */
encoded_req_len = req_desc->max_msg_len + QMI_HEADER_SIZE;
encoded_req = kmalloc(encoded_req_len, GFP_KERNEL);
if (!encoded_req) {
pr_err("%s: Failed to allocate req_msg_buf\n", __func__);
rc = -ENOMEM;
goto encode_and_send_req_err1;
}
rc = qmi_kernel_encode(req_desc,
(void *)(encoded_req + QMI_HEADER_SIZE),
req_desc->max_msg_len, req);
if (rc < 0) {
pr_err("%s: Encode Failure %d\n", __func__, rc);
goto encode_and_send_req_err2;
}
encoded_req_len = rc;
/* Encode the header & Add to the txn_list */
if (!handle->next_txn_id)
handle->next_txn_id++;
txn_handle->txn_id = handle->next_txn_id++;
encode_qmi_header(encoded_req, QMI_REQUEST_CONTROL_FLAG,
txn_handle->txn_id, req_desc->msg_id,
encoded_req_len);
encoded_req_len += QMI_HEADER_SIZE;
/*
* Check if this port has transactions queued to its pending list
* and if there are any pending transactions then add the current
* transaction to the pending list rather than sending it. This avoids
* out-of-order message transfers.
*/
if (!list_empty(&handle->pending_txn_list)) {
rc = -EAGAIN;
goto append_pend_txn;
}
list_add_tail(&txn_handle->list, &handle->txn_list);
/* Send the request */
rc = msm_ipc_router_send_msg((struct msm_ipc_port *)(handle->src_port),
(struct msm_ipc_addr *)handle->dest_info,
encoded_req, encoded_req_len);
append_pend_txn:
if (rc == -EAGAIN) {
txn_handle->enc_data = encoded_req;
txn_handle->enc_data_len = encoded_req_len;
if (list_empty(&handle->pending_txn_list))
list_del(&txn_handle->list);
list_add_tail(&txn_handle->list, &handle->pending_txn_list);
if (ret_txn_handle)
*ret_txn_handle = txn_handle;
mutex_unlock(&handle->handle_lock);
return 0;
}
if (rc < 0) {
pr_err("%s: send_msg failed %d\n", __func__, rc);
goto encode_and_send_req_err3;
}
mutex_unlock(&handle->handle_lock);
kfree(encoded_req);
if (ret_txn_handle)
*ret_txn_handle = txn_handle;
return 0;
encode_and_send_req_err3:
list_del(&txn_handle->list);
encode_and_send_req_err2:
kfree(encoded_req);
encode_and_send_req_err1:
kfree(txn_handle);
mutex_unlock(&handle->handle_lock);
return rc;
}
int qmi_send_req_wait(struct qmi_handle *handle,
struct msg_desc *req_desc,
void *req, unsigned int req_len,
struct msg_desc *resp_desc,
void *resp, unsigned int resp_len,
unsigned long timeout_ms)
{
struct qmi_txn *txn_handle = NULL;
int rc;
/* Encode and send the request */
rc = qmi_encode_and_send_req(&txn_handle, handle, QMI_SYNC_TXN,
req_desc, req, req_len,
resp_desc, resp, resp_len,
NULL, NULL);
if (rc < 0) {
pr_err("%s: Error encode & send req: %d\n", __func__, rc);
return rc;
}
/* Wait for the response */
if (!timeout_ms) {
wait_event(txn_handle->wait_q,
(txn_handle->resp_received ||
handle->handle_reset ||
(txn_handle->send_stat < 0)));
} else {
rc = wait_event_timeout(txn_handle->wait_q,
(txn_handle->resp_received ||
handle->handle_reset ||
(txn_handle->send_stat < 0)),
msecs_to_jiffies(timeout_ms));
if (rc == 0)
rc = -ETIMEDOUT;
}
mutex_lock(&handle->handle_lock);
if (!txn_handle->resp_received) {
pr_err("%s: Response Wait Error %d\n", __func__, rc);
if (handle->handle_reset)
rc = -ENETRESET;
if (rc >= 0)
rc = -EFAULT;
if (txn_handle->send_stat < 0)
rc = txn_handle->send_stat;
goto send_req_wait_err;
}
rc = 0;
send_req_wait_err:
list_del(&txn_handle->list);
kfree(txn_handle);
mutex_unlock(&handle->handle_lock);
wake_up(&handle->reset_waitq);
return rc;
}
EXPORT_SYMBOL(qmi_send_req_wait);
int qmi_send_req_nowait(struct qmi_handle *handle,
struct msg_desc *req_desc,
void *req, unsigned int req_len,
struct msg_desc *resp_desc,
void *resp, unsigned int resp_len,
void (*resp_cb)(struct qmi_handle *handle,
unsigned int msg_id, void *msg,
void *resp_cb_data, int stat),
void *resp_cb_data)
{
return qmi_encode_and_send_req(NULL, handle, QMI_ASYNC_TXN,
req_desc, req, req_len,
resp_desc, resp, resp_len,
resp_cb, resp_cb_data);
}
EXPORT_SYMBOL(qmi_send_req_nowait);
/**
* qmi_encode_and_send_resp() - Encode and send QMI response
* @handle: QMI service handle sending the response.
* @conn_h: Connection handle to which the response is sent.
* @req_h: Request handle for which the response is sent.
* @resp_desc: Message Descriptor describing the response structure.
* @resp: Response structure.
* @resp_len: Length of the response structure.
*
* @return: 0 on success, standard Linux error codes on failure.
*
* This function encodes and sends a response message from a service to
* a client identified from the connection handle. The request for which
* the response is sent is identified from the connection handle.
*
* This function must be called with handle->handle_lock locked.
*/
static int qmi_encode_and_send_resp(struct qmi_handle *handle,
struct qmi_svc_clnt_conn *conn_h, struct req_handle *req_h,
struct msg_desc *resp_desc, void *resp, unsigned int resp_len)
{
struct qmi_txn *txn_handle;
uint16_t cntl_flag;
int rc;
int encoded_resp_len;
void *encoded_resp;
if (handle->handle_reset) {
rc = -ENETRESET;
goto encode_and_send_resp_err0;
}
if (handle->handle_type != QMI_SERVICE_HANDLE ||
!verify_svc_clnt_conn(handle, conn_h) ||
(req_h && !verify_req_handle(conn_h, req_h))) {
rc = -EINVAL;
goto encode_and_send_resp_err0;
}
/* Allocate Transaction Info */
txn_handle = kzalloc(sizeof(struct qmi_txn), GFP_KERNEL);
if (!txn_handle) {
pr_err("%s: Failed to allocate txn handle\n", __func__);
rc = -ENOMEM;
goto encode_and_send_resp_err0;
}
INIT_LIST_HEAD(&txn_handle->list);
init_waitqueue_head(&txn_handle->wait_q);
txn_handle->handle = handle;
txn_handle->enc_data = NULL;
txn_handle->enc_data_len = 0;
/* Encode the response msg */
encoded_resp_len = resp_desc->max_msg_len + QMI_HEADER_SIZE;
encoded_resp = kmalloc(encoded_resp_len, GFP_KERNEL);
if (!encoded_resp) {
pr_err("%s: Failed to allocate resp_msg_buf\n", __func__);
rc = -ENOMEM;
goto encode_and_send_resp_err1;
}
rc = qmi_kernel_encode(resp_desc,
(void *)(encoded_resp + QMI_HEADER_SIZE),
resp_desc->max_msg_len, resp);
if (rc < 0) {
pr_err("%s: Encode Failure %d\n", __func__, rc);
goto encode_and_send_resp_err2;
}
encoded_resp_len = rc;
/* Encode the header & Add to the txn_list */
if (req_h) {
txn_handle->txn_id = req_h->txn_id;
cntl_flag = QMI_RESPONSE_CONTROL_FLAG;
} else {
if (!handle->next_txn_id)
handle->next_txn_id++;
txn_handle->txn_id = handle->next_txn_id++;
cntl_flag = QMI_INDICATION_CONTROL_FLAG;
}
encode_qmi_header(encoded_resp, cntl_flag,
txn_handle->txn_id, resp_desc->msg_id,
encoded_resp_len);
encoded_resp_len += QMI_HEADER_SIZE;
/*
* Check if this svc_clnt has transactions queued to its pending list
* and if there are any pending transactions then add the current
* transaction to the pending list rather than sending it. This avoids
* out-of-order message transfers.
*/
mutex_lock(&conn_h->pending_txn_lock);
if (list_empty(&conn_h->pending_txn_list))
rc = msm_ipc_router_send_msg(
(struct msm_ipc_port *)(handle->src_port),
(struct msm_ipc_addr *)conn_h->clnt_addr,
encoded_resp, encoded_resp_len);
else
rc = -EAGAIN;
if (req_h)
rmv_req_handle(req_h);
if (rc == -EAGAIN) {
txn_handle->enc_data = encoded_resp;
txn_handle->enc_data_len = encoded_resp_len;
list_add_tail(&txn_handle->list, &conn_h->pending_txn_list);
mutex_unlock(&conn_h->pending_txn_lock);
return 0;
}
mutex_unlock(&conn_h->pending_txn_lock);
if (rc < 0)
pr_err("%s: send_msg failed %d\n", __func__, rc);
encode_and_send_resp_err2:
kfree(encoded_resp);
encode_and_send_resp_err1:
kfree(txn_handle);
encode_and_send_resp_err0:
return rc;
}
/**
* qmi_send_resp() - Send response to a request
* @handle: QMI handle from which the response is sent.
* @clnt: Client to which the response is sent.
* @req_handle: Request for which the response is sent.
* @resp_desc: Descriptor explaining the response structure.
* @resp: Pointer to the response structure.
* @resp_len: Length of the response structure.
*
* @return: 0 on success, < 0 on error.
*/
int qmi_send_resp(struct qmi_handle *handle, void *conn_handle,
void *req_handle, struct msg_desc *resp_desc,
void *resp, unsigned int resp_len)
{
int rc;
struct qmi_svc_clnt_conn *conn_h;
struct req_handle *req_h;
if (!handle || !conn_handle || !req_handle ||
!resp_desc || !resp || !resp_len)
return -EINVAL;
conn_h = (struct qmi_svc_clnt_conn *)conn_handle;
req_h = (struct req_handle *)req_handle;
mutex_lock(&handle->handle_lock);
rc = qmi_encode_and_send_resp(handle, conn_h, req_h,
resp_desc, resp, resp_len);
if (rc < 0)
pr_err("%s: Error encoding and sending response\n", __func__);
mutex_unlock(&handle->handle_lock);
return rc;
}
EXPORT_SYMBOL(qmi_send_resp);
/**
* qmi_send_resp_from_cb() - Send response to a request from request_cb
* @handle: QMI handle from which the response is sent.
* @clnt: Client to which the response is sent.
* @req_handle: Request for which the response is sent.
* @resp_desc: Descriptor explaining the response structure.
* @resp: Pointer to the response structure.
* @resp_len: Length of the response structure.
*
* @return: 0 on success, < 0 on error.
*/
int qmi_send_resp_from_cb(struct qmi_handle *handle, void *conn_handle,
void *req_handle, struct msg_desc *resp_desc,
void *resp, unsigned int resp_len)
{
int rc;
struct qmi_svc_clnt_conn *conn_h;
struct req_handle *req_h;
if (!handle || !conn_handle || !req_handle ||
!resp_desc || !resp || !resp_len)
return -EINVAL;
conn_h = (struct qmi_svc_clnt_conn *)conn_handle;
req_h = (struct req_handle *)req_handle;
rc = qmi_encode_and_send_resp(handle, conn_h, req_h,
resp_desc, resp, resp_len);
if (rc < 0)
pr_err("%s: Error encoding and sending response\n", __func__);
return rc;
}
EXPORT_SYMBOL(qmi_send_resp_from_cb);
/**
* qmi_send_ind() - Send unsolicited event/indication to a client
* @handle: QMI handle from which the indication is sent.
* @clnt: Client to which the indication is sent.
* @ind_desc: Descriptor explaining the indication structure.
* @ind: Pointer to the indication structure.
* @ind_len: Length of the indication structure.
*
* @return: 0 on success, < 0 on error.
*/
int qmi_send_ind(struct qmi_handle *handle, void *conn_handle,
struct msg_desc *ind_desc, void *ind, unsigned int ind_len)
{
int rc = 0;
struct qmi_svc_clnt_conn *conn_h;
if (!handle || !conn_handle || !ind_desc)
return -EINVAL;
if ((!ind && ind_len) || (ind && !ind_len))
return -EINVAL;
conn_h = (struct qmi_svc_clnt_conn *)conn_handle;
mutex_lock(&handle->handle_lock);
rc = qmi_encode_and_send_resp(handle, conn_h, NULL,
ind_desc, ind, ind_len);
if (rc < 0)
pr_err("%s: Error encoding and sending ind.\n", __func__);
mutex_unlock(&handle->handle_lock);
return rc;
}
EXPORT_SYMBOL(qmi_send_ind);
/**
* qmi_send_ind_from_cb() - Send indication to a client from registration_cb
* @handle: QMI handle from which the indication is sent.
* @clnt: Client to which the indication is sent.
* @ind_desc: Descriptor explaining the indication structure.
* @ind: Pointer to the indication structure.
* @ind_len: Length of the indication structure.
*
* @return: 0 on success, < 0 on error.
*/
int qmi_send_ind_from_cb(struct qmi_handle *handle, void *conn_handle,
struct msg_desc *ind_desc, void *ind, unsigned int ind_len)
{
int rc = 0;
struct qmi_svc_clnt_conn *conn_h;
if (!handle || !conn_handle || !ind_desc)
return -EINVAL;
if ((!ind && ind_len) || (ind && !ind_len))
return -EINVAL;
conn_h = (struct qmi_svc_clnt_conn *)conn_handle;
rc = qmi_encode_and_send_resp(handle, conn_h, NULL,
ind_desc, ind, ind_len);
if (rc < 0)
pr_err("%s: Error encoding and sending ind.\n", __func__);
return rc;
}
EXPORT_SYMBOL(qmi_send_ind_from_cb);
/**
* translate_err_code() - Translate Linux error codes into QMI error codes
* @err: Standard Linux error codes to be translated.
*
* @return: Return QMI error code.
*/
static int translate_err_code(int err)
{
int rc;
switch (err) {
case -ECONNREFUSED:
rc = QMI_ERR_CLIENT_IDS_EXHAUSTED_V01;
break;
case -EBADMSG:
rc = QMI_ERR_ENCODING_V01;
break;
case -ENOMEM:
rc = QMI_ERR_NO_MEMORY_V01;
break;
case -EOPNOTSUPP:
rc = QMI_ERR_MALFORMED_MSG_V01;
break;
case -ENOTSUPP:
rc = QMI_ERR_NOT_SUPPORTED_V01;
break;
default:
rc = QMI_ERR_INTERNAL_V01;
break;
}
return rc;
}
/**
* send_err_resp() - Send the error response
* @handle: Service handle from which the response is sent.
* @conn_h: Client<->Service connection on which the response is sent.
* @addr: Client address to which the error response is sent.
* @msg_id: Request message id for which the error response is sent.
* @txn_id: Request Transaction ID for which the error response is sent.
* @err: Error code to be sent.
*
* @return: 0 on success, standard Linux error codes on failure.
*
* This function is used to send an error response from within the QMI
* service interface. This function is called when the service returns
* an error to the QMI interface while handling a request.
*/
static int send_err_resp(struct qmi_handle *handle,
struct qmi_svc_clnt_conn *conn_h, void *addr,
uint16_t msg_id, uint16_t txn_id, int err)
{
struct qmi_response_type_v01 err_resp;
struct qmi_txn *txn_handle;
struct msm_ipc_addr *dest_addr;
int rc;
int encoded_resp_len;
void *encoded_resp;
if (handle->handle_reset)
return -ENETRESET;
err_resp.result = QMI_RESULT_FAILURE_V01;
err_resp.error = translate_err_code(err);
/* Allocate Transaction Info */
txn_handle = kzalloc(sizeof(struct qmi_txn), GFP_KERNEL);
if (!txn_handle) {
pr_err("%s: Failed to allocate txn handle\n", __func__);
return -ENOMEM;
}
INIT_LIST_HEAD(&txn_handle->list);
init_waitqueue_head(&txn_handle->wait_q);
txn_handle->handle = handle;
txn_handle->enc_data = NULL;
txn_handle->enc_data_len = 0;
/* Encode the response msg */
encoded_resp_len = err_resp_desc.max_msg_len + QMI_HEADER_SIZE;
encoded_resp = kmalloc(encoded_resp_len, GFP_KERNEL);
if (!encoded_resp) {
pr_err("%s: Failed to allocate resp_msg_buf\n", __func__);
rc = -ENOMEM;
goto encode_and_send_err_resp_err0;
}
rc = qmi_kernel_encode(&err_resp_desc,
(void *)(encoded_resp + QMI_HEADER_SIZE),
err_resp_desc.max_msg_len, &err_resp);
if (rc < 0) {
pr_err("%s: Encode Failure %d\n", __func__, rc);
goto encode_and_send_err_resp_err1;
}
encoded_resp_len = rc;
/* Encode the header & Add to the txn_list */
txn_handle->txn_id = txn_id;
encode_qmi_header(encoded_resp, QMI_RESPONSE_CONTROL_FLAG,
txn_handle->txn_id, msg_id,
encoded_resp_len);
encoded_resp_len += QMI_HEADER_SIZE;
/*
* Check if this svc_clnt has transactions queued to its pending list
* and if there are any pending transactions then add the current
* transaction to the pending list rather than sending it. This avoids
* out-of-order message transfers.
*/
if (!conn_h) {
dest_addr = (struct msm_ipc_addr *)addr;
goto tx_err_resp;
}
mutex_lock(&conn_h->pending_txn_lock);
dest_addr = (struct msm_ipc_addr *)conn_h->clnt_addr;
if (!list_empty(&conn_h->pending_txn_list)) {
rc = -EAGAIN;
goto queue_err_resp;
}
tx_err_resp:
rc = msm_ipc_router_send_msg(
(struct msm_ipc_port *)(handle->src_port),
dest_addr, encoded_resp, encoded_resp_len);
queue_err_resp:
if (rc == -EAGAIN && conn_h) {
txn_handle->enc_data = encoded_resp;
txn_handle->enc_data_len = encoded_resp_len;
list_add_tail(&txn_handle->list, &conn_h->pending_txn_list);
mutex_unlock(&conn_h->pending_txn_lock);
return 0;
}
if (conn_h)
mutex_unlock(&conn_h->pending_txn_lock);
if (rc < 0)
pr_err("%s: send_msg failed %d\n", __func__, rc);
encode_and_send_err_resp_err1:
kfree(encoded_resp);
encode_and_send_err_resp_err0:
kfree(txn_handle);
return rc;
}
/**
* handle_qmi_request() - Handle the QMI request
* @handle: QMI service handle on which the request has arrived.
* @req_msg: Request message to be handled.
* @txn_id: Transaction ID of the request message.
* @msg_id: Message ID of the request message.
* @msg_len: Message Length of the request message.
* @src_addr: Address of the source which sent the request.
* @src_addr_len: Length of the source address.
*
* @return: 0 on success, standard Linux error codes on failure.
*/
static int handle_qmi_request(struct qmi_handle *handle,
unsigned char *req_msg, uint16_t txn_id,
uint16_t msg_id, uint16_t msg_len,
void *src_addr, size_t src_addr_len)
{
struct qmi_svc_clnt_conn *conn_h;
struct msg_desc *req_desc = NULL;
void *req_struct = NULL;
unsigned int req_struct_len = 0;
struct req_handle *req_h = NULL;
int rc = 0;
if (handle->handle_type != QMI_SERVICE_HANDLE)
return -EOPNOTSUPP;
conn_h = find_svc_clnt_conn(handle, src_addr, src_addr_len);
if (conn_h)
goto decode_req;
/* New client, establish a connection */
conn_h = add_svc_clnt_conn(handle, src_addr, src_addr_len);
if (!conn_h) {
pr_err("%s: Error adding a new conn_h\n", __func__);
rc = -ENOMEM;
goto out_handle_req;
}
rc = handle->svc_ops_options->connect_cb(handle, conn_h);
if (rc < 0) {
pr_err("%s: Error accepting new client\n", __func__);
rmv_svc_clnt_conn(conn_h);
conn_h = NULL;
goto out_handle_req;
}
decode_req:
if (!msg_len)
goto process_req;
req_struct_len = handle->svc_ops_options->req_desc_cb(msg_id,
&req_desc);
if (!req_desc || req_struct_len <= 0) {
pr_err("%s: Error getting req_desc for msg_id %d\n",
__func__, msg_id);
rc = -ENOTSUPP;
goto out_handle_req;
}
req_struct = kzalloc(req_struct_len, GFP_KERNEL);
if (!req_struct) {
pr_err("%s: Error allocating request struct\n", __func__);
rc = -ENOMEM;
goto out_handle_req;
}
rc = qmi_kernel_decode(req_desc, req_struct,
(void *)(req_msg + QMI_HEADER_SIZE), msg_len);
if (rc < 0) {
pr_err("%s: Error decoding msg_id %d\n", __func__, msg_id);
rc = -EBADMSG;
goto out_handle_req;
}
process_req:
req_h = add_req_handle(conn_h, msg_id, txn_id);
if (!req_h) {
pr_err("%s: Error adding new request handle\n", __func__);
rc = -ENOMEM;
goto out_handle_req;
}
rc = handle->svc_ops_options->req_cb(handle, conn_h, req_h,
msg_id, req_struct);
if (rc < 0) {
pr_err("%s: Error while req_cb\n", __func__);
/* Check if the error is before or after sending a response */
if (verify_req_handle(conn_h, req_h))
rmv_req_handle(req_h);
else
rc = 0;
}
out_handle_req:
kfree(req_struct);
if (rc < 0)
send_err_resp(handle, conn_h, src_addr, msg_id, txn_id, rc);
return rc;
}
static struct qmi_txn *find_txn_handle(struct qmi_handle *handle,
uint16_t txn_id)
{
struct qmi_txn *txn_handle;
list_for_each_entry(txn_handle, &handle->txn_list, list) {
if (txn_handle->txn_id == txn_id)
return txn_handle;
}
return NULL;
}
static int handle_qmi_response(struct qmi_handle *handle,
unsigned char *resp_msg, uint16_t txn_id,
uint16_t msg_id, uint16_t msg_len)
{
struct qmi_txn *txn_handle;
int rc;
/* Find the transaction handle */
txn_handle = find_txn_handle(handle, txn_id);
if (!txn_handle) {
pr_err("%s Response received for non-existent txn_id %d\n",
__func__, txn_id);
return 0;
}
/* Decode the message */
rc = qmi_kernel_decode(txn_handle->resp_desc, txn_handle->resp,
(void *)(resp_msg + QMI_HEADER_SIZE), msg_len);
if (rc < 0) {
pr_err("%s: Response Decode Failure <%d: %d: %d> rc: %d\n",
__func__, txn_id, msg_id, msg_len, rc);
wake_up(&txn_handle->wait_q);
if (txn_handle->type == QMI_ASYNC_TXN) {
list_del(&txn_handle->list);
kfree(txn_handle);
}
return rc;
}
/* Handle async or sync resp */
switch (txn_handle->type) {
case QMI_SYNC_TXN:
txn_handle->resp_received = 1;
wake_up(&txn_handle->wait_q);
rc = 0;
break;
case QMI_ASYNC_TXN:
if (txn_handle->resp_cb)
txn_handle->resp_cb(txn_handle->handle, msg_id,
txn_handle->resp,
txn_handle->resp_cb_data, 0);
list_del(&txn_handle->list);
kfree(txn_handle);
rc = 0;
break;
default:
pr_err("%s: Unrecognized transaction type\n", __func__);
return -EFAULT;
}
return rc;
}
static int handle_qmi_indication(struct qmi_handle *handle, void *msg,
unsigned int msg_id, unsigned int msg_len)
{
if (handle->ind_cb)
handle->ind_cb(handle, msg_id, msg,
msg_len, handle->ind_cb_priv);
return 0;
}
int qmi_recv_msg(struct qmi_handle *handle)
{
unsigned int recv_msg_len;
unsigned char *recv_msg = NULL;
struct msm_ipc_addr src_addr = {0};
unsigned char cntl_flag;
uint16_t txn_id, msg_id, msg_len;
int rc;
if (!handle)
return -EINVAL;
mutex_lock(&handle->handle_lock);
if (handle->handle_reset) {
mutex_unlock(&handle->handle_lock);
return -ENETRESET;
}
/* Read the messages */
rc = msm_ipc_router_read_msg((struct msm_ipc_port *)(handle->src_port),
&src_addr, &recv_msg, &recv_msg_len);
if (rc == -ENOMSG) {
mutex_unlock(&handle->handle_lock);
return rc;
}
if (rc < 0) {
pr_err("%s: Read failed %d\n", __func__, rc);
mutex_unlock(&handle->handle_lock);
return rc;
}
/* Decode the header & Handle the req, resp, indication message */
decode_qmi_header(recv_msg, &cntl_flag, &txn_id, &msg_id, &msg_len);
switch (cntl_flag) {
case QMI_REQUEST_CONTROL_FLAG:
rc = handle_qmi_request(handle, recv_msg, txn_id, msg_id,
msg_len, &src_addr, sizeof(src_addr));
break;
case QMI_RESPONSE_CONTROL_FLAG:
rc = handle_qmi_response(handle, recv_msg,
txn_id, msg_id, msg_len);
break;
case QMI_INDICATION_CONTROL_FLAG:
rc = handle_qmi_indication(handle, recv_msg, msg_id, msg_len);
break;
default:
rc = -EFAULT;
pr_err("%s: Unsupported message type %d\n",
__func__, cntl_flag);
break;
}
kfree(recv_msg);
mutex_unlock(&handle->handle_lock);
return rc;
}
EXPORT_SYMBOL(qmi_recv_msg);
int qmi_connect_to_service(struct qmi_handle *handle,
uint32_t service_id,
uint32_t service_vers,
uint32_t service_ins)
{
struct msm_ipc_port_name svc_name;
struct msm_ipc_server_info svc_info;
struct msm_ipc_addr *svc_dest_addr;
int rc;
uint32_t instance_id;
if (!handle)
return -EINVAL;
svc_dest_addr = kzalloc(sizeof(struct msm_ipc_addr),
GFP_KERNEL);
if (!svc_dest_addr) {
pr_err("%s: Failure allocating memory\n", __func__);
return -ENOMEM;
}
instance_id = BUILD_INSTANCE_ID(service_vers, service_ins);
svc_name.service = service_id;
svc_name.instance = instance_id;
rc = msm_ipc_router_lookup_server_name(&svc_name, &svc_info,
1, LOOKUP_MASK);
if (rc <= 0) {
pr_err("%s: Server %08x:%08x not found\n",
__func__, service_id, instance_id);
return -ENODEV;
}
svc_dest_addr->addrtype = MSM_IPC_ADDR_ID;
svc_dest_addr->addr.port_addr.node_id = svc_info.node_id;
svc_dest_addr->addr.port_addr.port_id = svc_info.port_id;
mutex_lock(&handle->handle_lock);
if (handle->handle_reset) {
mutex_unlock(&handle->handle_lock);
return -ENETRESET;
}
handle->dest_info = svc_dest_addr;
mutex_unlock(&handle->handle_lock);
return 0;
}
EXPORT_SYMBOL(qmi_connect_to_service);
static struct svc_event_nb *find_svc_event_nb_by_name(const char *name)
{
struct svc_event_nb *temp;
list_for_each_entry(temp, &svc_event_nb_list, list) {
if (!strncmp(name, temp->pdriver_name,
sizeof(temp->pdriver_name)))
return temp;
}
return NULL;
}
static int qmi_svc_event_probe(struct platform_device *pdev)
{
struct svc_event_nb *temp;
unsigned long flags;
mutex_lock(&svc_event_nb_list_lock);
temp = find_svc_event_nb_by_name(pdev->name);
if (!temp) {
mutex_unlock(&svc_event_nb_list_lock);
return -EINVAL;
}
spin_lock_irqsave(&temp->nb_lock, flags);
temp->svc_avail++;
raw_notifier_call_chain(&temp->svc_event_rcvr_list,
QMI_SERVER_ARRIVE, NULL);
spin_unlock_irqrestore(&temp->nb_lock, flags);
mutex_unlock(&svc_event_nb_list_lock);
return 0;
}
static int qmi_svc_event_remove(struct platform_device *pdev)
{
struct svc_event_nb *temp;
unsigned long flags;
mutex_lock(&svc_event_nb_list_lock);
temp = find_svc_event_nb_by_name(pdev->name);
if (!temp) {
mutex_unlock(&svc_event_nb_list_lock);
return -EINVAL;
}
spin_lock_irqsave(&temp->nb_lock, flags);
temp->svc_avail--;
raw_notifier_call_chain(&temp->svc_event_rcvr_list,
QMI_SERVER_EXIT, NULL);
spin_unlock_irqrestore(&temp->nb_lock, flags);
mutex_unlock(&svc_event_nb_list_lock);
return 0;
}
static struct svc_event_nb *find_svc_event_nb(uint32_t service_id,
uint32_t instance_id)
{
struct svc_event_nb *temp;
list_for_each_entry(temp, &svc_event_nb_list, list) {
if (temp->service_id == service_id &&
temp->instance_id == instance_id)
return temp;
}
return NULL;
}
static struct svc_event_nb *find_and_add_svc_event_nb(uint32_t service_id,
uint32_t instance_id)
{
struct svc_event_nb *temp;
int ret;
mutex_lock(&svc_event_nb_list_lock);
temp = find_svc_event_nb(service_id, instance_id);
if (temp) {
mutex_unlock(&svc_event_nb_list_lock);
return temp;
}
temp = kzalloc(sizeof(struct svc_event_nb), GFP_KERNEL);
if (!temp) {
mutex_unlock(&svc_event_nb_list_lock);
pr_err("%s: Failed to alloc notifier block\n", __func__);
return temp;
}
spin_lock_init(&temp->nb_lock);
temp->service_id = service_id;
temp->instance_id = instance_id;
INIT_LIST_HEAD(&temp->list);
temp->svc_driver.probe = qmi_svc_event_probe;
temp->svc_driver.remove = qmi_svc_event_remove;
scnprintf(temp->pdriver_name, sizeof(temp->pdriver_name),
"SVC%08x:%08x", service_id, instance_id);
temp->svc_driver.driver.name = temp->pdriver_name;
RAW_INIT_NOTIFIER_HEAD(&temp->svc_event_rcvr_list);
list_add_tail(&temp->list, &svc_event_nb_list);
mutex_unlock(&svc_event_nb_list_lock);
ret = platform_driver_register(&temp->svc_driver);
if (ret < 0) {
pr_err("%s: Failed pdriver register\n", __func__);
mutex_lock(&svc_event_nb_list_lock);
list_del(&temp->list);
mutex_unlock(&svc_event_nb_list_lock);
kfree(temp);
temp = NULL;
}
return temp;
}
int qmi_svc_event_notifier_register(uint32_t service_id,
uint32_t service_vers,
uint32_t service_ins,
struct notifier_block *nb)
{
struct svc_event_nb *temp;
unsigned long flags;
int ret;
uint32_t instance_id;
instance_id = BUILD_INSTANCE_ID(service_vers, service_ins);
temp = find_and_add_svc_event_nb(service_id, instance_id);
if (!temp)
return -EFAULT;
mutex_lock(&svc_event_nb_list_lock);
temp = find_svc_event_nb(service_id, instance_id);
if (!temp) {
mutex_unlock(&svc_event_nb_list_lock);
return -EFAULT;
}
spin_lock_irqsave(&temp->nb_lock, flags);
if (temp->svc_avail)
nb->notifier_call(nb, QMI_SERVER_ARRIVE, NULL);
ret = raw_notifier_chain_register(&temp->svc_event_rcvr_list, nb);
spin_unlock_irqrestore(&temp->nb_lock, flags);
mutex_unlock(&svc_event_nb_list_lock);
return ret;
}
EXPORT_SYMBOL(qmi_svc_event_notifier_register);
int qmi_svc_event_notifier_unregister(uint32_t service_id,
uint32_t service_vers,
uint32_t service_ins,
struct notifier_block *nb)
{
int ret;
struct svc_event_nb *temp;
unsigned long flags;
uint32_t instance_id;
instance_id = BUILD_INSTANCE_ID(service_vers, service_ins);
mutex_lock(&svc_event_nb_list_lock);
temp = find_svc_event_nb(service_id, instance_id);
if (!temp) {
mutex_unlock(&svc_event_nb_list_lock);
return -EINVAL;
}
spin_lock_irqsave(&temp->nb_lock, flags);
ret = raw_notifier_chain_unregister(&temp->svc_event_rcvr_list, nb);
spin_unlock_irqrestore(&temp->nb_lock, flags);
mutex_unlock(&svc_event_nb_list_lock);
return ret;
}
EXPORT_SYMBOL(qmi_svc_event_notifier_unregister);
/**
* qmi_svc_register() - Register a QMI service with a QMI handle
* @handle: QMI handle on which the service has to be registered.
* @ops_options: Service specific operations and options.
*
* @return: 0 if successfully registered, < 0 on error.
*/
int qmi_svc_register(struct qmi_handle *handle, void *ops_options)
{
struct qmi_svc_ops_options *svc_ops_options;
struct msm_ipc_addr svc_name;
int rc;
uint32_t instance_id;
svc_ops_options = (struct qmi_svc_ops_options *)ops_options;
if (!handle || !svc_ops_options)
return -EINVAL;
/* Check if the required elements of opts_options are filled */
if (!svc_ops_options->service_id || !svc_ops_options->service_vers ||
!svc_ops_options->connect_cb || !svc_ops_options->disconnect_cb ||
!svc_ops_options->req_desc_cb || !svc_ops_options->req_cb)
return -EINVAL;
mutex_lock(&handle->handle_lock);
/* Check if another service/client is registered in that handle */
if (handle->handle_type == QMI_SERVICE_HANDLE || handle->dest_info) {
mutex_unlock(&handle->handle_lock);
return -EBUSY;
}
INIT_LIST_HEAD(&handle->conn_list);
mutex_unlock(&handle->handle_lock);
/*
* Unlocked the handle_lock, because NEW_SERVER message will end up
* in this handle's control port, which requires holding the same
* mutex. Also it is safe to call register_server unlocked.
*/
/* Register the service */
instance_id = ((svc_ops_options->service_vers & 0xFF) |
((svc_ops_options->service_ins & 0xFF) << 8));
svc_name.addrtype = MSM_IPC_ADDR_NAME;
svc_name.addr.port_name.service = svc_ops_options->service_id;
svc_name.addr.port_name.instance = instance_id;
rc = msm_ipc_router_register_server(
(struct msm_ipc_port *)handle->src_port, &svc_name);
if (rc < 0) {
pr_err("%s: Error %d registering QMI service %08x:%08x\n",
__func__, rc, svc_ops_options->service_id,
instance_id);
return rc;
}
mutex_lock(&handle->handle_lock);
handle->svc_ops_options = svc_ops_options;
handle->handle_type = QMI_SERVICE_HANDLE;
mutex_unlock(&handle->handle_lock);
return rc;
}
EXPORT_SYMBOL(qmi_svc_register);
/**
* qmi_svc_unregister() - Unregister the service from a QMI handle
* @handle: QMI handle from which the service has to be unregistered.
*
* return: 0 on success, < 0 on error.
*/
int qmi_svc_unregister(struct qmi_handle *handle)
{
struct qmi_svc_clnt_conn *conn_h, *temp_conn_h;
if (!handle || handle->handle_type != QMI_SERVICE_HANDLE)
return -EINVAL;
mutex_lock(&handle->handle_lock);
handle->handle_type = QMI_CLIENT_HANDLE;
mutex_unlock(&handle->handle_lock);
/*
* Unlocked the handle_lock, because REMOVE_SERVER message will end up
* in this handle's control port, which requires holding the same
* mutex. Also it is safe to call register_server unlocked.
*/
msm_ipc_router_unregister_server(
(struct msm_ipc_port *)handle->src_port);
mutex_lock(&handle->handle_lock);
list_for_each_entry_safe(conn_h, temp_conn_h,
&handle->conn_list, list)
rmv_svc_clnt_conn(conn_h);
mutex_unlock(&handle->handle_lock);
return 0;
}
EXPORT_SYMBOL(qmi_svc_unregister);
MODULE_DESCRIPTION("MSM QMI Interface");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Californication/lge-kernel-msm7x27-ICS-JB | arch/sparc/kernel/us2e_cpufreq.c | 1203 | 9814 | /* us2e_cpufreq.c: UltraSPARC-IIe cpu frequency support
*
* Copyright (C) 2003 David S. Miller (davem@redhat.com)
*
* Many thanks to Dominik Brodowski for fixing up the cpufreq
* infrastructure in order to make this driver easier to implement.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/cpufreq.h>
#include <linux/threads.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <asm/asi.h>
#include <asm/timer.h>
static struct cpufreq_driver *cpufreq_us2e_driver;
struct us2e_freq_percpu_info {
struct cpufreq_frequency_table table[6];
};
/* Indexed by cpu number. */
static struct us2e_freq_percpu_info *us2e_freq_table;
#define HBIRD_MEM_CNTL0_ADDR 0x1fe0000f010UL
#define HBIRD_ESTAR_MODE_ADDR 0x1fe0000f080UL
/* UltraSPARC-IIe has five dividers: 1, 2, 4, 6, and 8. These are controlled
* in the ESTAR mode control register.
*/
#define ESTAR_MODE_DIV_1 0x0000000000000000UL
#define ESTAR_MODE_DIV_2 0x0000000000000001UL
#define ESTAR_MODE_DIV_4 0x0000000000000003UL
#define ESTAR_MODE_DIV_6 0x0000000000000002UL
#define ESTAR_MODE_DIV_8 0x0000000000000004UL
#define ESTAR_MODE_DIV_MASK 0x0000000000000007UL
#define MCTRL0_SREFRESH_ENAB 0x0000000000010000UL
#define MCTRL0_REFR_COUNT_MASK 0x0000000000007f00UL
#define MCTRL0_REFR_COUNT_SHIFT 8
#define MCTRL0_REFR_INTERVAL 7800
#define MCTRL0_REFR_CLKS_P_CNT 64
static unsigned long read_hbreg(unsigned long addr)
{
unsigned long ret;
__asm__ __volatile__("ldxa [%1] %2, %0"
: "=&r" (ret)
: "r" (addr), "i" (ASI_PHYS_BYPASS_EC_E));
return ret;
}
static void write_hbreg(unsigned long addr, unsigned long val)
{
__asm__ __volatile__("stxa %0, [%1] %2\n\t"
"membar #Sync"
: /* no outputs */
: "r" (val), "r" (addr), "i" (ASI_PHYS_BYPASS_EC_E)
: "memory");
if (addr == HBIRD_ESTAR_MODE_ADDR) {
/* Need to wait 16 clock cycles for the PLL to lock. */
udelay(1);
}
}
static void self_refresh_ctl(int enable)
{
unsigned long mctrl = read_hbreg(HBIRD_MEM_CNTL0_ADDR);
if (enable)
mctrl |= MCTRL0_SREFRESH_ENAB;
else
mctrl &= ~MCTRL0_SREFRESH_ENAB;
write_hbreg(HBIRD_MEM_CNTL0_ADDR, mctrl);
(void) read_hbreg(HBIRD_MEM_CNTL0_ADDR);
}
static void frob_mem_refresh(int cpu_slowing_down,
unsigned long clock_tick,
unsigned long old_divisor, unsigned long divisor)
{
unsigned long old_refr_count, refr_count, mctrl;
refr_count = (clock_tick * MCTRL0_REFR_INTERVAL);
refr_count /= (MCTRL0_REFR_CLKS_P_CNT * divisor * 1000000000UL);
mctrl = read_hbreg(HBIRD_MEM_CNTL0_ADDR);
old_refr_count = (mctrl & MCTRL0_REFR_COUNT_MASK)
>> MCTRL0_REFR_COUNT_SHIFT;
mctrl &= ~MCTRL0_REFR_COUNT_MASK;
mctrl |= refr_count << MCTRL0_REFR_COUNT_SHIFT;
write_hbreg(HBIRD_MEM_CNTL0_ADDR, mctrl);
mctrl = read_hbreg(HBIRD_MEM_CNTL0_ADDR);
if (cpu_slowing_down && !(mctrl & MCTRL0_SREFRESH_ENAB)) {
unsigned long usecs;
/* We have to wait for both refresh counts (old
* and new) to go to zero.
*/
usecs = (MCTRL0_REFR_CLKS_P_CNT *
(refr_count + old_refr_count) *
1000000UL *
old_divisor) / clock_tick;
udelay(usecs + 1UL);
}
}
static void us2e_transition(unsigned long estar, unsigned long new_bits,
unsigned long clock_tick,
unsigned long old_divisor, unsigned long divisor)
{
unsigned long flags;
local_irq_save(flags);
estar &= ~ESTAR_MODE_DIV_MASK;
/* This is based upon the state transition diagram in the IIe manual. */
if (old_divisor == 2 && divisor == 1) {
self_refresh_ctl(0);
write_hbreg(HBIRD_ESTAR_MODE_ADDR, estar | new_bits);
frob_mem_refresh(0, clock_tick, old_divisor, divisor);
} else if (old_divisor == 1 && divisor == 2) {
frob_mem_refresh(1, clock_tick, old_divisor, divisor);
write_hbreg(HBIRD_ESTAR_MODE_ADDR, estar | new_bits);
self_refresh_ctl(1);
} else if (old_divisor == 1 && divisor > 2) {
us2e_transition(estar, ESTAR_MODE_DIV_2, clock_tick,
1, 2);
us2e_transition(estar, new_bits, clock_tick,
2, divisor);
} else if (old_divisor > 2 && divisor == 1) {
us2e_transition(estar, ESTAR_MODE_DIV_2, clock_tick,
old_divisor, 2);
us2e_transition(estar, new_bits, clock_tick,
2, divisor);
} else if (old_divisor < divisor) {
frob_mem_refresh(0, clock_tick, old_divisor, divisor);
write_hbreg(HBIRD_ESTAR_MODE_ADDR, estar | new_bits);
} else if (old_divisor > divisor) {
write_hbreg(HBIRD_ESTAR_MODE_ADDR, estar | new_bits);
frob_mem_refresh(1, clock_tick, old_divisor, divisor);
} else {
BUG();
}
local_irq_restore(flags);
}
static unsigned long index_to_estar_mode(unsigned int index)
{
switch (index) {
case 0:
return ESTAR_MODE_DIV_1;
case 1:
return ESTAR_MODE_DIV_2;
case 2:
return ESTAR_MODE_DIV_4;
case 3:
return ESTAR_MODE_DIV_6;
case 4:
return ESTAR_MODE_DIV_8;
default:
BUG();
};
}
static unsigned long index_to_divisor(unsigned int index)
{
switch (index) {
case 0:
return 1;
case 1:
return 2;
case 2:
return 4;
case 3:
return 6;
case 4:
return 8;
default:
BUG();
};
}
static unsigned long estar_to_divisor(unsigned long estar)
{
unsigned long ret;
switch (estar & ESTAR_MODE_DIV_MASK) {
case ESTAR_MODE_DIV_1:
ret = 1;
break;
case ESTAR_MODE_DIV_2:
ret = 2;
break;
case ESTAR_MODE_DIV_4:
ret = 4;
break;
case ESTAR_MODE_DIV_6:
ret = 6;
break;
case ESTAR_MODE_DIV_8:
ret = 8;
break;
default:
BUG();
};
return ret;
}
static unsigned int us2e_freq_get(unsigned int cpu)
{
cpumask_t cpus_allowed;
unsigned long clock_tick, estar;
if (!cpu_online(cpu))
return 0;
cpus_allowed = current->cpus_allowed;
set_cpus_allowed_ptr(current, cpumask_of(cpu));
clock_tick = sparc64_get_clock_tick(cpu) / 1000;
estar = read_hbreg(HBIRD_ESTAR_MODE_ADDR);
set_cpus_allowed_ptr(current, &cpus_allowed);
return clock_tick / estar_to_divisor(estar);
}
static void us2e_set_cpu_divider_index(unsigned int cpu, unsigned int index)
{
unsigned long new_bits, new_freq;
unsigned long clock_tick, divisor, old_divisor, estar;
cpumask_t cpus_allowed;
struct cpufreq_freqs freqs;
if (!cpu_online(cpu))
return;
cpus_allowed = current->cpus_allowed;
set_cpus_allowed_ptr(current, cpumask_of(cpu));
new_freq = clock_tick = sparc64_get_clock_tick(cpu) / 1000;
new_bits = index_to_estar_mode(index);
divisor = index_to_divisor(index);
new_freq /= divisor;
estar = read_hbreg(HBIRD_ESTAR_MODE_ADDR);
old_divisor = estar_to_divisor(estar);
freqs.old = clock_tick / old_divisor;
freqs.new = new_freq;
freqs.cpu = cpu;
cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE);
if (old_divisor != divisor)
us2e_transition(estar, new_bits, clock_tick * 1000,
old_divisor, divisor);
cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE);
set_cpus_allowed_ptr(current, &cpus_allowed);
}
static int us2e_freq_target(struct cpufreq_policy *policy,
unsigned int target_freq,
unsigned int relation)
{
unsigned int new_index = 0;
if (cpufreq_frequency_table_target(policy,
&us2e_freq_table[policy->cpu].table[0],
target_freq, relation, &new_index))
return -EINVAL;
us2e_set_cpu_divider_index(policy->cpu, new_index);
return 0;
}
static int us2e_freq_verify(struct cpufreq_policy *policy)
{
return cpufreq_frequency_table_verify(policy,
&us2e_freq_table[policy->cpu].table[0]);
}
static int __init us2e_freq_cpu_init(struct cpufreq_policy *policy)
{
unsigned int cpu = policy->cpu;
unsigned long clock_tick = sparc64_get_clock_tick(cpu) / 1000;
struct cpufreq_frequency_table *table =
&us2e_freq_table[cpu].table[0];
table[0].index = 0;
table[0].frequency = clock_tick / 1;
table[1].index = 1;
table[1].frequency = clock_tick / 2;
table[2].index = 2;
table[2].frequency = clock_tick / 4;
table[2].index = 3;
table[2].frequency = clock_tick / 6;
table[2].index = 4;
table[2].frequency = clock_tick / 8;
table[2].index = 5;
table[3].frequency = CPUFREQ_TABLE_END;
policy->cpuinfo.transition_latency = 0;
policy->cur = clock_tick;
return cpufreq_frequency_table_cpuinfo(policy, table);
}
static int us2e_freq_cpu_exit(struct cpufreq_policy *policy)
{
if (cpufreq_us2e_driver)
us2e_set_cpu_divider_index(policy->cpu, 0);
return 0;
}
static int __init us2e_freq_init(void)
{
unsigned long manuf, impl, ver;
int ret;
if (tlb_type != spitfire)
return -ENODEV;
__asm__("rdpr %%ver, %0" : "=r" (ver));
manuf = ((ver >> 48) & 0xffff);
impl = ((ver >> 32) & 0xffff);
if (manuf == 0x17 && impl == 0x13) {
struct cpufreq_driver *driver;
ret = -ENOMEM;
driver = kzalloc(sizeof(struct cpufreq_driver), GFP_KERNEL);
if (!driver)
goto err_out;
us2e_freq_table = kzalloc(
(NR_CPUS * sizeof(struct us2e_freq_percpu_info)),
GFP_KERNEL);
if (!us2e_freq_table)
goto err_out;
driver->init = us2e_freq_cpu_init;
driver->verify = us2e_freq_verify;
driver->target = us2e_freq_target;
driver->get = us2e_freq_get;
driver->exit = us2e_freq_cpu_exit;
driver->owner = THIS_MODULE,
strcpy(driver->name, "UltraSPARC-IIe");
cpufreq_us2e_driver = driver;
ret = cpufreq_register_driver(driver);
if (ret)
goto err_out;
return 0;
err_out:
if (driver) {
kfree(driver);
cpufreq_us2e_driver = NULL;
}
kfree(us2e_freq_table);
us2e_freq_table = NULL;
return ret;
}
return -ENODEV;
}
static void __exit us2e_freq_exit(void)
{
if (cpufreq_us2e_driver) {
cpufreq_unregister_driver(cpufreq_us2e_driver);
kfree(cpufreq_us2e_driver);
cpufreq_us2e_driver = NULL;
kfree(us2e_freq_table);
us2e_freq_table = NULL;
}
}
MODULE_AUTHOR("David S. Miller <davem@redhat.com>");
MODULE_DESCRIPTION("cpufreq driver for UltraSPARC-IIe");
MODULE_LICENSE("GPL");
module_init(us2e_freq_init);
module_exit(us2e_freq_exit);
| gpl-2.0 |
gkoloventzos/hetfs-linux | drivers/ata/pata_cmd640.c | 1971 | 6646 | /*
* pata_cmd640.c - CMD640 PCI PATA for new ATA layer
* (C) 2007 Red Hat Inc
*
* Based upon
* linux/drivers/ide/pci/cmd640.c Version 1.02 Sep 01, 1996
*
* Copyright (C) 1995-1996 Linus Torvalds & authors (see driver)
*
* This drives only the PCI version of the controller. If you have a
* VLB one then we have enough docs to support it but you can write
* your own code.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/gfp.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "pata_cmd640"
#define DRV_VERSION "0.0.5"
struct cmd640_reg {
int last;
u8 reg58[ATA_MAX_DEVICES];
};
enum {
CFR = 0x50,
CNTRL = 0x51,
CMDTIM = 0x52,
ARTIM0 = 0x53,
DRWTIM0 = 0x54,
ARTIM23 = 0x57,
DRWTIM23 = 0x58,
BRST = 0x59
};
/**
* cmd640_set_piomode - set initial PIO mode data
* @ap: ATA port
* @adev: ATA device
*
* Called to do the PIO mode setup.
*/
static void cmd640_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
struct cmd640_reg *timing = ap->private_data;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct ata_timing t;
const unsigned long T = 1000000 / 33;
const u8 setup_data[] = { 0x40, 0x40, 0x40, 0x80, 0x00 };
u8 reg;
int arttim = ARTIM0 + 2 * adev->devno;
struct ata_device *pair = ata_dev_pair(adev);
if (ata_timing_compute(adev, adev->pio_mode, &t, T, 0) < 0) {
printk(KERN_ERR DRV_NAME ": mode computation failed.\n");
return;
}
/* The second channel has shared timings and the setup timing is
messy to switch to merge it for worst case */
if (ap->port_no && pair) {
struct ata_timing p;
ata_timing_compute(pair, pair->pio_mode, &p, T, 1);
ata_timing_merge(&p, &t, &t, ATA_TIMING_SETUP);
}
/* Make the timings fit */
if (t.recover > 16) {
t.active += t.recover - 16;
t.recover = 16;
}
if (t.active > 16)
t.active = 16;
/* Now convert the clocks into values we can actually stuff into
the chip */
if (t.recover > 1)
t.recover--; /* 640B only */
else
t.recover = 15;
if (t.setup > 4)
t.setup = 0xC0;
else
t.setup = setup_data[t.setup];
if (ap->port_no == 0) {
t.active &= 0x0F; /* 0 = 16 */
/* Load setup timing */
pci_read_config_byte(pdev, arttim, ®);
reg &= 0x3F;
reg |= t.setup;
pci_write_config_byte(pdev, arttim, reg);
/* Load active/recovery */
pci_write_config_byte(pdev, arttim + 1, (t.active << 4) | t.recover);
} else {
/* Save the shared timings for channel, they will be loaded
by qc_issue. Reloading the setup time is expensive so we
keep a merged one loaded */
pci_read_config_byte(pdev, ARTIM23, ®);
reg &= 0x3F;
reg |= t.setup;
pci_write_config_byte(pdev, ARTIM23, reg);
timing->reg58[adev->devno] = (t.active << 4) | t.recover;
}
}
/**
* cmd640_qc_issue - command preparation hook
* @qc: Command to be issued
*
* Channel 1 has shared timings. We must reprogram the
* clock each drive 2/3 switch we do.
*/
static unsigned int cmd640_qc_issue(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_device *adev = qc->dev;
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct cmd640_reg *timing = ap->private_data;
if (ap->port_no != 0 && adev->devno != timing->last) {
pci_write_config_byte(pdev, DRWTIM23, timing->reg58[adev->devno]);
timing->last = adev->devno;
}
return ata_sff_qc_issue(qc);
}
/**
* cmd640_port_start - port setup
* @ap: ATA port being set up
*
* The CMD640 needs to maintain private data structures so we
* allocate space here.
*/
static int cmd640_port_start(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
struct cmd640_reg *timing;
timing = devm_kzalloc(&pdev->dev, sizeof(struct cmd640_reg), GFP_KERNEL);
if (timing == NULL)
return -ENOMEM;
timing->last = -1; /* Force a load */
ap->private_data = timing;
return 0;
}
static bool cmd640_sff_irq_check(struct ata_port *ap)
{
struct pci_dev *pdev = to_pci_dev(ap->host->dev);
int irq_reg = ap->port_no ? ARTIM23 : CFR;
u8 irq_stat, irq_mask = ap->port_no ? 0x10 : 0x04;
pci_read_config_byte(pdev, irq_reg, &irq_stat);
return irq_stat & irq_mask;
}
static struct scsi_host_template cmd640_sht = {
ATA_PIO_SHT(DRV_NAME),
};
static struct ata_port_operations cmd640_port_ops = {
.inherits = &ata_sff_port_ops,
/* In theory xfer_noirq is not needed once we kill the prefetcher */
.sff_data_xfer = ata_sff_data_xfer_noirq,
.sff_irq_check = cmd640_sff_irq_check,
.qc_issue = cmd640_qc_issue,
.cable_detect = ata_cable_40wire,
.set_piomode = cmd640_set_piomode,
.port_start = cmd640_port_start,
};
static void cmd640_hardware_init(struct pci_dev *pdev)
{
u8 ctrl;
/* CMD640 detected, commiserations */
pci_write_config_byte(pdev, 0x5B, 0x00);
/* PIO0 command cycles */
pci_write_config_byte(pdev, CMDTIM, 0);
/* 512 byte bursts (sector) */
pci_write_config_byte(pdev, BRST, 0x40);
/*
* A reporter a long time ago
* Had problems with the data fifo
* So don't run the risk
* Of putting crap on the disk
* For its better just to go slow
*/
/* Do channel 0 */
pci_read_config_byte(pdev, CNTRL, &ctrl);
pci_write_config_byte(pdev, CNTRL, ctrl | 0xC0);
/* Ditto for channel 1 */
pci_read_config_byte(pdev, ARTIM23, &ctrl);
ctrl |= 0x0C;
pci_write_config_byte(pdev, ARTIM23, ctrl);
}
static int cmd640_init_one(struct pci_dev *pdev, const struct pci_device_id *id)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.port_ops = &cmd640_port_ops
};
const struct ata_port_info *ppi[] = { &info, NULL };
int rc;
rc = pcim_enable_device(pdev);
if (rc)
return rc;
cmd640_hardware_init(pdev);
return ata_pci_sff_init_one(pdev, ppi, &cmd640_sht, NULL, 0);
}
#ifdef CONFIG_PM_SLEEP
static int cmd640_reinit_one(struct pci_dev *pdev)
{
struct ata_host *host = pci_get_drvdata(pdev);
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
cmd640_hardware_init(pdev);
ata_host_resume(host);
return 0;
}
#endif
static const struct pci_device_id cmd640[] = {
{ PCI_VDEVICE(CMD, 0x640), 0 },
{ },
};
static struct pci_driver cmd640_pci_driver = {
.name = DRV_NAME,
.id_table = cmd640,
.probe = cmd640_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM_SLEEP
.suspend = ata_pci_device_suspend,
.resume = cmd640_reinit_one,
#endif
};
module_pci_driver(cmd640_pci_driver);
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("low-level driver for CMD640 PATA controllers");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, cmd640);
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
papi92/android_kernel_samsung_g906s | sound/pci/ice1712/prodigy_hifi.c | 3251 | 32363 | /*
* ALSA driver for ICEnsemble VT1724 (Envy24HT)
*
* Lowlevel functions for Audiotrak Prodigy 7.1 Hifi
* based on pontis.c
*
* Copyright (c) 2007 Julian Scheel <julian@jusst.de>
* Copyright (c) 2007 allank
* Copyright (c) 2004 Takashi Iwai <tiwai@suse.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/info.h>
#include <sound/tlv.h>
#include "ice1712.h"
#include "envy24ht.h"
#include "prodigy_hifi.h"
struct prodigy_hifi_spec {
unsigned short master[2];
unsigned short vol[8];
};
/* I2C addresses */
#define WM_DEV 0x34
/* WM8776 registers */
#define WM_HP_ATTEN_L 0x00 /* headphone left attenuation */
#define WM_HP_ATTEN_R 0x01 /* headphone left attenuation */
#define WM_HP_MASTER 0x02 /* headphone master (both channels),
override LLR */
#define WM_DAC_ATTEN_L 0x03 /* digital left attenuation */
#define WM_DAC_ATTEN_R 0x04
#define WM_DAC_MASTER 0x05
#define WM_PHASE_SWAP 0x06 /* DAC phase swap */
#define WM_DAC_CTRL1 0x07
#define WM_DAC_MUTE 0x08
#define WM_DAC_CTRL2 0x09
#define WM_DAC_INT 0x0a
#define WM_ADC_INT 0x0b
#define WM_MASTER_CTRL 0x0c
#define WM_POWERDOWN 0x0d
#define WM_ADC_ATTEN_L 0x0e
#define WM_ADC_ATTEN_R 0x0f
#define WM_ALC_CTRL1 0x10
#define WM_ALC_CTRL2 0x11
#define WM_ALC_CTRL3 0x12
#define WM_NOISE_GATE 0x13
#define WM_LIMITER 0x14
#define WM_ADC_MUX 0x15
#define WM_OUT_MUX 0x16
#define WM_RESET 0x17
/* Analog Recording Source :- Mic, LineIn, CD/Video, */
/* implement capture source select control for WM8776 */
#define WM_AIN1 "AIN1"
#define WM_AIN2 "AIN2"
#define WM_AIN3 "AIN3"
#define WM_AIN4 "AIN4"
#define WM_AIN5 "AIN5"
/* GPIO pins of envy24ht connected to wm8766 */
#define WM8766_SPI_CLK (1<<17) /* CLK, Pin97 on ICE1724 */
#define WM8766_SPI_MD (1<<16) /* DATA VT1724 -> WM8766, Pin96 */
#define WM8766_SPI_ML (1<<18) /* Latch, Pin98 */
/* WM8766 registers */
#define WM8766_DAC_CTRL 0x02 /* DAC Control */
#define WM8766_INT_CTRL 0x03 /* Interface Control */
#define WM8766_DAC_CTRL2 0x09
#define WM8766_DAC_CTRL3 0x0a
#define WM8766_RESET 0x1f
#define WM8766_LDA1 0x00
#define WM8766_LDA2 0x04
#define WM8766_LDA3 0x06
#define WM8766_RDA1 0x01
#define WM8766_RDA2 0x05
#define WM8766_RDA3 0x07
#define WM8766_MUTE1 0x0C
#define WM8766_MUTE2 0x0F
/*
* Prodigy HD2
*/
#define AK4396_ADDR 0x00
#define AK4396_CSN (1 << 8) /* CSN->GPIO8, pin 75 */
#define AK4396_CCLK (1 << 9) /* CCLK->GPIO9, pin 76 */
#define AK4396_CDTI (1 << 10) /* CDTI->GPIO10, pin 77 */
/* ak4396 registers */
#define AK4396_CTRL1 0x00
#define AK4396_CTRL2 0x01
#define AK4396_CTRL3 0x02
#define AK4396_LCH_ATT 0x03
#define AK4396_RCH_ATT 0x04
/*
* get the current register value of WM codec
*/
static unsigned short wm_get(struct snd_ice1712 *ice, int reg)
{
reg <<= 1;
return ((unsigned short)ice->akm[0].images[reg] << 8) |
ice->akm[0].images[reg + 1];
}
/*
* set the register value of WM codec and remember it
*/
static void wm_put_nocache(struct snd_ice1712 *ice, int reg, unsigned short val)
{
unsigned short cval;
cval = (reg << 9) | val;
snd_vt1724_write_i2c(ice, WM_DEV, cval >> 8, cval & 0xff);
}
static void wm_put(struct snd_ice1712 *ice, int reg, unsigned short val)
{
wm_put_nocache(ice, reg, val);
reg <<= 1;
ice->akm[0].images[reg] = val >> 8;
ice->akm[0].images[reg + 1] = val;
}
/*
* write data in the SPI mode
*/
static void set_gpio_bit(struct snd_ice1712 *ice, unsigned int bit, int val)
{
unsigned int tmp = snd_ice1712_gpio_read(ice);
if (val)
tmp |= bit;
else
tmp &= ~bit;
snd_ice1712_gpio_write(ice, tmp);
}
/*
* SPI implementation for WM8766 codec - only writing supported, no readback
*/
static void wm8766_spi_send_word(struct snd_ice1712 *ice, unsigned int data)
{
int i;
for (i = 0; i < 16; i++) {
set_gpio_bit(ice, WM8766_SPI_CLK, 0);
udelay(1);
set_gpio_bit(ice, WM8766_SPI_MD, data & 0x8000);
udelay(1);
set_gpio_bit(ice, WM8766_SPI_CLK, 1);
udelay(1);
data <<= 1;
}
}
static void wm8766_spi_write(struct snd_ice1712 *ice, unsigned int reg,
unsigned int data)
{
unsigned int block;
snd_ice1712_gpio_set_dir(ice, WM8766_SPI_MD|
WM8766_SPI_CLK|WM8766_SPI_ML);
snd_ice1712_gpio_set_mask(ice, ~(WM8766_SPI_MD|
WM8766_SPI_CLK|WM8766_SPI_ML));
/* latch must be low when writing */
set_gpio_bit(ice, WM8766_SPI_ML, 0);
block = (reg << 9) | (data & 0x1ff);
wm8766_spi_send_word(ice, block); /* REGISTER ADDRESS */
/* release latch */
set_gpio_bit(ice, WM8766_SPI_ML, 1);
udelay(1);
/* restore */
snd_ice1712_gpio_set_mask(ice, ice->gpio.write_mask);
snd_ice1712_gpio_set_dir(ice, ice->gpio.direction);
}
/*
* serial interface for ak4396 - only writing supported, no readback
*/
static void ak4396_send_word(struct snd_ice1712 *ice, unsigned int data)
{
int i;
for (i = 0; i < 16; i++) {
set_gpio_bit(ice, AK4396_CCLK, 0);
udelay(1);
set_gpio_bit(ice, AK4396_CDTI, data & 0x8000);
udelay(1);
set_gpio_bit(ice, AK4396_CCLK, 1);
udelay(1);
data <<= 1;
}
}
static void ak4396_write(struct snd_ice1712 *ice, unsigned int reg,
unsigned int data)
{
unsigned int block;
snd_ice1712_gpio_set_dir(ice, AK4396_CSN|AK4396_CCLK|AK4396_CDTI);
snd_ice1712_gpio_set_mask(ice, ~(AK4396_CSN|AK4396_CCLK|AK4396_CDTI));
/* latch must be low when writing */
set_gpio_bit(ice, AK4396_CSN, 0);
block = ((AK4396_ADDR & 0x03) << 14) | (1 << 13) |
((reg & 0x1f) << 8) | (data & 0xff);
ak4396_send_word(ice, block); /* REGISTER ADDRESS */
/* release latch */
set_gpio_bit(ice, AK4396_CSN, 1);
udelay(1);
/* restore */
snd_ice1712_gpio_set_mask(ice, ice->gpio.write_mask);
snd_ice1712_gpio_set_dir(ice, ice->gpio.direction);
}
/*
* ak4396 mixers
*/
/*
* DAC volume attenuation mixer control (-64dB to 0dB)
*/
static int ak4396_dac_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0; /* mute */
uinfo->value.integer.max = 0xFF; /* linear */
return 0;
}
static int ak4396_dac_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
struct prodigy_hifi_spec *spec = ice->spec;
int i;
for (i = 0; i < 2; i++)
ucontrol->value.integer.value[i] = spec->vol[i];
return 0;
}
static int ak4396_dac_vol_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
struct prodigy_hifi_spec *spec = ice->spec;
int i;
int change = 0;
mutex_lock(&ice->gpio_mutex);
for (i = 0; i < 2; i++) {
if (ucontrol->value.integer.value[i] != spec->vol[i]) {
spec->vol[i] = ucontrol->value.integer.value[i];
ak4396_write(ice, AK4396_LCH_ATT + i,
spec->vol[i] & 0xff);
change = 1;
}
}
mutex_unlock(&ice->gpio_mutex);
return change;
}
static const DECLARE_TLV_DB_SCALE(db_scale_wm_dac, -12700, 100, 1);
static const DECLARE_TLV_DB_LINEAR(ak4396_db_scale, TLV_DB_GAIN_MUTE, 0);
static struct snd_kcontrol_new prodigy_hd2_controls[] = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Front Playback Volume",
.info = ak4396_dac_vol_info,
.get = ak4396_dac_vol_get,
.put = ak4396_dac_vol_put,
.tlv = { .p = ak4396_db_scale },
},
};
/* --------------- */
/*
* Logarithmic volume values for WM87*6
* Computed as 20 * Log10(255 / x)
*/
static const unsigned char wm_vol[256] = {
127, 48, 42, 39, 36, 34, 33, 31, 30, 29, 28, 27, 27, 26, 25, 25, 24, 24, 23,
23, 22, 22, 21, 21, 21, 20, 20, 20, 19, 19, 19, 18, 18, 18, 18, 17, 17, 17,
17, 16, 16, 16, 16, 15, 15, 15, 15, 15, 15, 14, 14, 14, 14, 14, 13, 13, 13,
13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11,
11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0
};
#define WM_VOL_MAX (sizeof(wm_vol) - 1)
#define WM_VOL_MUTE 0x8000
#define DAC_0dB 0xff
#define DAC_RES 128
#define DAC_MIN (DAC_0dB - DAC_RES)
static void wm_set_vol(struct snd_ice1712 *ice, unsigned int index,
unsigned short vol, unsigned short master)
{
unsigned char nvol;
if ((master & WM_VOL_MUTE) || (vol & WM_VOL_MUTE))
nvol = 0;
else {
nvol = (((vol & ~WM_VOL_MUTE) * (master & ~WM_VOL_MUTE)) / 128)
& WM_VOL_MAX;
nvol = (nvol ? (nvol + DAC_MIN) : 0) & 0xff;
}
wm_put(ice, index, nvol);
wm_put_nocache(ice, index, 0x100 | nvol);
}
static void wm8766_set_vol(struct snd_ice1712 *ice, unsigned int index,
unsigned short vol, unsigned short master)
{
unsigned char nvol;
if ((master & WM_VOL_MUTE) || (vol & WM_VOL_MUTE))
nvol = 0;
else {
nvol = (((vol & ~WM_VOL_MUTE) * (master & ~WM_VOL_MUTE)) / 128)
& WM_VOL_MAX;
nvol = (nvol ? (nvol + DAC_MIN) : 0) & 0xff;
}
wm8766_spi_write(ice, index, (0x0100 | nvol));
}
/*
* DAC volume attenuation mixer control (-64dB to 0dB)
*/
static int wm_dac_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0; /* mute */
uinfo->value.integer.max = DAC_RES; /* 0dB, 0.5dB step */
return 0;
}
static int wm_dac_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
struct prodigy_hifi_spec *spec = ice->spec;
int i;
for (i = 0; i < 2; i++)
ucontrol->value.integer.value[i] =
spec->vol[2 + i] & ~WM_VOL_MUTE;
return 0;
}
static int wm_dac_vol_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
struct prodigy_hifi_spec *spec = ice->spec;
int i, idx, change = 0;
mutex_lock(&ice->gpio_mutex);
for (i = 0; i < 2; i++) {
if (ucontrol->value.integer.value[i] != spec->vol[2 + i]) {
idx = WM_DAC_ATTEN_L + i;
spec->vol[2 + i] &= WM_VOL_MUTE;
spec->vol[2 + i] |= ucontrol->value.integer.value[i];
wm_set_vol(ice, idx, spec->vol[2 + i], spec->master[i]);
change = 1;
}
}
mutex_unlock(&ice->gpio_mutex);
return change;
}
/*
* WM8766 DAC volume attenuation mixer control
*/
static int wm8766_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
int voices = kcontrol->private_value >> 8;
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = voices;
uinfo->value.integer.min = 0; /* mute */
uinfo->value.integer.max = DAC_RES; /* 0dB */
return 0;
}
static int wm8766_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
struct prodigy_hifi_spec *spec = ice->spec;
int i, ofs, voices;
voices = kcontrol->private_value >> 8;
ofs = kcontrol->private_value & 0xff;
for (i = 0; i < voices; i++)
ucontrol->value.integer.value[i] = spec->vol[ofs + i];
return 0;
}
static int wm8766_vol_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
struct prodigy_hifi_spec *spec = ice->spec;
int i, idx, ofs, voices;
int change = 0;
voices = kcontrol->private_value >> 8;
ofs = kcontrol->private_value & 0xff;
mutex_lock(&ice->gpio_mutex);
for (i = 0; i < voices; i++) {
if (ucontrol->value.integer.value[i] != spec->vol[ofs + i]) {
idx = WM8766_LDA1 + ofs + i;
spec->vol[ofs + i] &= WM_VOL_MUTE;
spec->vol[ofs + i] |= ucontrol->value.integer.value[i];
wm8766_set_vol(ice, idx,
spec->vol[ofs + i], spec->master[i]);
change = 1;
}
}
mutex_unlock(&ice->gpio_mutex);
return change;
}
/*
* Master volume attenuation mixer control / applied to WM8776+WM8766
*/
static int wm_master_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = DAC_RES;
return 0;
}
static int wm_master_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
struct prodigy_hifi_spec *spec = ice->spec;
int i;
for (i = 0; i < 2; i++)
ucontrol->value.integer.value[i] = spec->master[i];
return 0;
}
static int wm_master_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
struct prodigy_hifi_spec *spec = ice->spec;
int ch, change = 0;
mutex_lock(&ice->gpio_mutex);
for (ch = 0; ch < 2; ch++) {
if (ucontrol->value.integer.value[ch] != spec->master[ch]) {
spec->master[ch] = ucontrol->value.integer.value[ch];
/* Apply to front DAC */
wm_set_vol(ice, WM_DAC_ATTEN_L + ch,
spec->vol[2 + ch], spec->master[ch]);
wm8766_set_vol(ice, WM8766_LDA1 + ch,
spec->vol[0 + ch], spec->master[ch]);
wm8766_set_vol(ice, WM8766_LDA2 + ch,
spec->vol[4 + ch], spec->master[ch]);
wm8766_set_vol(ice, WM8766_LDA3 + ch,
spec->vol[6 + ch], spec->master[ch]);
change = 1;
}
}
mutex_unlock(&ice->gpio_mutex);
return change;
}
/* KONSTI */
static int wm_adc_mux_enum_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
static char* texts[32] = {
"NULL", WM_AIN1, WM_AIN2, WM_AIN1 "+" WM_AIN2,
WM_AIN3, WM_AIN1 "+" WM_AIN3, WM_AIN2 "+" WM_AIN3,
WM_AIN1 "+" WM_AIN2 "+" WM_AIN3,
WM_AIN4, WM_AIN1 "+" WM_AIN4, WM_AIN2 "+" WM_AIN4,
WM_AIN1 "+" WM_AIN2 "+" WM_AIN4,
WM_AIN3 "+" WM_AIN4, WM_AIN1 "+" WM_AIN3 "+" WM_AIN4,
WM_AIN2 "+" WM_AIN3 "+" WM_AIN4,
WM_AIN1 "+" WM_AIN2 "+" WM_AIN3 "+" WM_AIN4,
WM_AIN5, WM_AIN1 "+" WM_AIN5, WM_AIN2 "+" WM_AIN5,
WM_AIN1 "+" WM_AIN2 "+" WM_AIN5,
WM_AIN3 "+" WM_AIN5, WM_AIN1 "+" WM_AIN3 "+" WM_AIN5,
WM_AIN2 "+" WM_AIN3 "+" WM_AIN5,
WM_AIN1 "+" WM_AIN2 "+" WM_AIN3 "+" WM_AIN5,
WM_AIN4 "+" WM_AIN5, WM_AIN1 "+" WM_AIN4 "+" WM_AIN5,
WM_AIN2 "+" WM_AIN4 "+" WM_AIN5,
WM_AIN1 "+" WM_AIN2 "+" WM_AIN4 "+" WM_AIN5,
WM_AIN3 "+" WM_AIN4 "+" WM_AIN5,
WM_AIN1 "+" WM_AIN3 "+" WM_AIN4 "+" WM_AIN5,
WM_AIN2 "+" WM_AIN3 "+" WM_AIN4 "+" WM_AIN5,
WM_AIN1 "+" WM_AIN2 "+" WM_AIN3 "+" WM_AIN4 "+" WM_AIN5
};
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = 32;
if (uinfo->value.enumerated.item > 31)
uinfo->value.enumerated.item = 31;
strcpy(uinfo->value.enumerated.name,
texts[uinfo->value.enumerated.item]);
return 0;
}
static int wm_adc_mux_enum_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
mutex_lock(&ice->gpio_mutex);
ucontrol->value.integer.value[0] = wm_get(ice, WM_ADC_MUX) & 0x1f;
mutex_unlock(&ice->gpio_mutex);
return 0;
}
static int wm_adc_mux_enum_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
unsigned short oval, nval;
int change = 0;
mutex_lock(&ice->gpio_mutex);
oval = wm_get(ice, WM_ADC_MUX);
nval = (oval & 0xe0) | ucontrol->value.integer.value[0];
if (nval != oval) {
wm_put(ice, WM_ADC_MUX, nval);
change = 1;
}
mutex_unlock(&ice->gpio_mutex);
return change;
}
/* KONSTI */
/*
* ADC gain mixer control (-64dB to 0dB)
*/
#define ADC_0dB 0xcf
#define ADC_RES 128
#define ADC_MIN (ADC_0dB - ADC_RES)
static int wm_adc_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0; /* mute (-64dB) */
uinfo->value.integer.max = ADC_RES; /* 0dB, 0.5dB step */
return 0;
}
static int wm_adc_vol_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
unsigned short val;
int i;
mutex_lock(&ice->gpio_mutex);
for (i = 0; i < 2; i++) {
val = wm_get(ice, WM_ADC_ATTEN_L + i) & 0xff;
val = val > ADC_MIN ? (val - ADC_MIN) : 0;
ucontrol->value.integer.value[i] = val;
}
mutex_unlock(&ice->gpio_mutex);
return 0;
}
static int wm_adc_vol_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
unsigned short ovol, nvol;
int i, idx, change = 0;
mutex_lock(&ice->gpio_mutex);
for (i = 0; i < 2; i++) {
nvol = ucontrol->value.integer.value[i];
nvol = nvol ? (nvol + ADC_MIN) : 0;
idx = WM_ADC_ATTEN_L + i;
ovol = wm_get(ice, idx) & 0xff;
if (ovol != nvol) {
wm_put(ice, idx, nvol);
change = 1;
}
}
mutex_unlock(&ice->gpio_mutex);
return change;
}
/*
* ADC input mux mixer control
*/
#define wm_adc_mux_info snd_ctl_boolean_mono_info
static int wm_adc_mux_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
int bit = kcontrol->private_value;
mutex_lock(&ice->gpio_mutex);
ucontrol->value.integer.value[0] =
(wm_get(ice, WM_ADC_MUX) & (1 << bit)) ? 1 : 0;
mutex_unlock(&ice->gpio_mutex);
return 0;
}
static int wm_adc_mux_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
int bit = kcontrol->private_value;
unsigned short oval, nval;
int change;
mutex_lock(&ice->gpio_mutex);
nval = oval = wm_get(ice, WM_ADC_MUX);
if (ucontrol->value.integer.value[0])
nval |= (1 << bit);
else
nval &= ~(1 << bit);
change = nval != oval;
if (change) {
wm_put(ice, WM_ADC_MUX, nval);
}
mutex_unlock(&ice->gpio_mutex);
return 0;
}
/*
* Analog bypass (In -> Out)
*/
#define wm_bypass_info snd_ctl_boolean_mono_info
static int wm_bypass_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
mutex_lock(&ice->gpio_mutex);
ucontrol->value.integer.value[0] =
(wm_get(ice, WM_OUT_MUX) & 0x04) ? 1 : 0;
mutex_unlock(&ice->gpio_mutex);
return 0;
}
static int wm_bypass_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
unsigned short val, oval;
int change = 0;
mutex_lock(&ice->gpio_mutex);
val = oval = wm_get(ice, WM_OUT_MUX);
if (ucontrol->value.integer.value[0])
val |= 0x04;
else
val &= ~0x04;
if (val != oval) {
wm_put(ice, WM_OUT_MUX, val);
change = 1;
}
mutex_unlock(&ice->gpio_mutex);
return change;
}
/*
* Left/Right swap
*/
#define wm_chswap_info snd_ctl_boolean_mono_info
static int wm_chswap_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
mutex_lock(&ice->gpio_mutex);
ucontrol->value.integer.value[0] =
(wm_get(ice, WM_DAC_CTRL1) & 0xf0) != 0x90;
mutex_unlock(&ice->gpio_mutex);
return 0;
}
static int wm_chswap_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_ice1712 *ice = snd_kcontrol_chip(kcontrol);
unsigned short val, oval;
int change = 0;
mutex_lock(&ice->gpio_mutex);
oval = wm_get(ice, WM_DAC_CTRL1);
val = oval & 0x0f;
if (ucontrol->value.integer.value[0])
val |= 0x60;
else
val |= 0x90;
if (val != oval) {
wm_put(ice, WM_DAC_CTRL1, val);
wm_put_nocache(ice, WM_DAC_CTRL1, val);
change = 1;
}
mutex_unlock(&ice->gpio_mutex);
return change;
}
/*
* mixers
*/
static struct snd_kcontrol_new prodigy_hifi_controls[] = {
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Master Playback Volume",
.info = wm_master_vol_info,
.get = wm_master_vol_get,
.put = wm_master_vol_put,
.tlv = { .p = db_scale_wm_dac }
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Front Playback Volume",
.info = wm_dac_vol_info,
.get = wm_dac_vol_get,
.put = wm_dac_vol_put,
.tlv = { .p = db_scale_wm_dac },
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Rear Playback Volume",
.info = wm8766_vol_info,
.get = wm8766_vol_get,
.put = wm8766_vol_put,
.private_value = (2 << 8) | 0,
.tlv = { .p = db_scale_wm_dac },
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Center Playback Volume",
.info = wm8766_vol_info,
.get = wm8766_vol_get,
.put = wm8766_vol_put,
.private_value = (1 << 8) | 4,
.tlv = { .p = db_scale_wm_dac }
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "LFE Playback Volume",
.info = wm8766_vol_info,
.get = wm8766_vol_get,
.put = wm8766_vol_put,
.private_value = (1 << 8) | 5,
.tlv = { .p = db_scale_wm_dac }
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Side Playback Volume",
.info = wm8766_vol_info,
.get = wm8766_vol_get,
.put = wm8766_vol_put,
.private_value = (2 << 8) | 6,
.tlv = { .p = db_scale_wm_dac },
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.access = (SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ),
.name = "Capture Volume",
.info = wm_adc_vol_info,
.get = wm_adc_vol_get,
.put = wm_adc_vol_put,
.tlv = { .p = db_scale_wm_dac },
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "CD Capture Switch",
.info = wm_adc_mux_info,
.get = wm_adc_mux_get,
.put = wm_adc_mux_put,
.private_value = 0,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Line Capture Switch",
.info = wm_adc_mux_info,
.get = wm_adc_mux_get,
.put = wm_adc_mux_put,
.private_value = 1,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Analog Bypass Switch",
.info = wm_bypass_info,
.get = wm_bypass_get,
.put = wm_bypass_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Swap Output Channels",
.info = wm_chswap_info,
.get = wm_chswap_get,
.put = wm_chswap_put,
},
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Analog Capture Source",
.info = wm_adc_mux_enum_info,
.get = wm_adc_mux_enum_get,
.put = wm_adc_mux_enum_put,
},
};
/*
* WM codec registers
*/
static void wm_proc_regs_write(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_ice1712 *ice = entry->private_data;
char line[64];
unsigned int reg, val;
mutex_lock(&ice->gpio_mutex);
while (!snd_info_get_line(buffer, line, sizeof(line))) {
if (sscanf(line, "%x %x", ®, &val) != 2)
continue;
if (reg <= 0x17 && val <= 0xffff)
wm_put(ice, reg, val);
}
mutex_unlock(&ice->gpio_mutex);
}
static void wm_proc_regs_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_ice1712 *ice = entry->private_data;
int reg, val;
mutex_lock(&ice->gpio_mutex);
for (reg = 0; reg <= 0x17; reg++) {
val = wm_get(ice, reg);
snd_iprintf(buffer, "%02x = %04x\n", reg, val);
}
mutex_unlock(&ice->gpio_mutex);
}
static void wm_proc_init(struct snd_ice1712 *ice)
{
struct snd_info_entry *entry;
if (!snd_card_proc_new(ice->card, "wm_codec", &entry)) {
snd_info_set_text_ops(entry, ice, wm_proc_regs_read);
entry->mode |= S_IWUSR;
entry->c.text.write = wm_proc_regs_write;
}
}
static int prodigy_hifi_add_controls(struct snd_ice1712 *ice)
{
unsigned int i;
int err;
for (i = 0; i < ARRAY_SIZE(prodigy_hifi_controls); i++) {
err = snd_ctl_add(ice->card,
snd_ctl_new1(&prodigy_hifi_controls[i], ice));
if (err < 0)
return err;
}
wm_proc_init(ice);
return 0;
}
static int prodigy_hd2_add_controls(struct snd_ice1712 *ice)
{
unsigned int i;
int err;
for (i = 0; i < ARRAY_SIZE(prodigy_hd2_controls); i++) {
err = snd_ctl_add(ice->card,
snd_ctl_new1(&prodigy_hd2_controls[i], ice));
if (err < 0)
return err;
}
wm_proc_init(ice);
return 0;
}
/*
* initialize the chip
*/
static int prodigy_hifi_init(struct snd_ice1712 *ice)
{
static unsigned short wm_inits[] = {
/* These come first to reduce init pop noise */
WM_ADC_MUX, 0x0003, /* ADC mute */
/* 0x00c0 replaced by 0x0003 */
WM_DAC_MUTE, 0x0001, /* DAC softmute */
WM_DAC_CTRL1, 0x0000, /* DAC mute */
WM_POWERDOWN, 0x0008, /* All power-up except HP */
WM_RESET, 0x0000, /* reset */
};
static unsigned short wm_inits2[] = {
WM_MASTER_CTRL, 0x0022, /* 256fs, slave mode */
WM_DAC_INT, 0x0022, /* I2S, normal polarity, 24bit */
WM_ADC_INT, 0x0022, /* I2S, normal polarity, 24bit */
WM_DAC_CTRL1, 0x0090, /* DAC L/R */
WM_OUT_MUX, 0x0001, /* OUT DAC */
WM_HP_ATTEN_L, 0x0179, /* HP 0dB */
WM_HP_ATTEN_R, 0x0179, /* HP 0dB */
WM_DAC_ATTEN_L, 0x0000, /* DAC 0dB */
WM_DAC_ATTEN_L, 0x0100, /* DAC 0dB */
WM_DAC_ATTEN_R, 0x0000, /* DAC 0dB */
WM_DAC_ATTEN_R, 0x0100, /* DAC 0dB */
WM_PHASE_SWAP, 0x0000, /* phase normal */
#if 0
WM_DAC_MASTER, 0x0100, /* DAC master muted */
#endif
WM_DAC_CTRL2, 0x0000, /* no deemphasis, no ZFLG */
WM_ADC_ATTEN_L, 0x0000, /* ADC muted */
WM_ADC_ATTEN_R, 0x0000, /* ADC muted */
#if 1
WM_ALC_CTRL1, 0x007b, /* */
WM_ALC_CTRL2, 0x0000, /* */
WM_ALC_CTRL3, 0x0000, /* */
WM_NOISE_GATE, 0x0000, /* */
#endif
WM_DAC_MUTE, 0x0000, /* DAC unmute */
WM_ADC_MUX, 0x0003, /* ADC unmute, both CD/Line On */
};
static unsigned short wm8766_inits[] = {
WM8766_RESET, 0x0000,
WM8766_DAC_CTRL, 0x0120,
WM8766_INT_CTRL, 0x0022, /* I2S Normal Mode, 24 bit */
WM8766_DAC_CTRL2, 0x0001,
WM8766_DAC_CTRL3, 0x0080,
WM8766_LDA1, 0x0100,
WM8766_LDA2, 0x0100,
WM8766_LDA3, 0x0100,
WM8766_RDA1, 0x0100,
WM8766_RDA2, 0x0100,
WM8766_RDA3, 0x0100,
WM8766_MUTE1, 0x0000,
WM8766_MUTE2, 0x0000,
};
struct prodigy_hifi_spec *spec;
unsigned int i;
ice->vt1720 = 0;
ice->vt1724 = 1;
ice->num_total_dacs = 8;
ice->num_total_adcs = 1;
/* HACK - use this as the SPDIF source.
* don't call snd_ice1712_gpio_get/put(), otherwise it's overwritten
*/
ice->gpio.saved[0] = 0;
/* to remember the register values */
ice->akm = kzalloc(sizeof(struct snd_akm4xxx), GFP_KERNEL);
if (! ice->akm)
return -ENOMEM;
ice->akm_codecs = 1;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (!spec)
return -ENOMEM;
ice->spec = spec;
/* initialize WM8776 codec */
for (i = 0; i < ARRAY_SIZE(wm_inits); i += 2)
wm_put(ice, wm_inits[i], wm_inits[i+1]);
schedule_timeout_uninterruptible(1);
for (i = 0; i < ARRAY_SIZE(wm_inits2); i += 2)
wm_put(ice, wm_inits2[i], wm_inits2[i+1]);
/* initialize WM8766 codec */
for (i = 0; i < ARRAY_SIZE(wm8766_inits); i += 2)
wm8766_spi_write(ice, wm8766_inits[i], wm8766_inits[i+1]);
return 0;
}
/*
* initialize the chip
*/
static void ak4396_init(struct snd_ice1712 *ice)
{
static unsigned short ak4396_inits[] = {
AK4396_CTRL1, 0x87, /* I2S Normal Mode, 24 bit */
AK4396_CTRL2, 0x02,
AK4396_CTRL3, 0x00,
AK4396_LCH_ATT, 0x00,
AK4396_RCH_ATT, 0x00,
};
unsigned int i;
/* initialize ak4396 codec */
/* reset codec */
ak4396_write(ice, AK4396_CTRL1, 0x86);
msleep(100);
ak4396_write(ice, AK4396_CTRL1, 0x87);
for (i = 0; i < ARRAY_SIZE(ak4396_inits); i += 2)
ak4396_write(ice, ak4396_inits[i], ak4396_inits[i+1]);
}
#ifdef CONFIG_PM_SLEEP
static int prodigy_hd2_resume(struct snd_ice1712 *ice)
{
/* initialize ak4396 codec and restore previous mixer volumes */
struct prodigy_hifi_spec *spec = ice->spec;
int i;
mutex_lock(&ice->gpio_mutex);
ak4396_init(ice);
for (i = 0; i < 2; i++)
ak4396_write(ice, AK4396_LCH_ATT + i, spec->vol[i] & 0xff);
mutex_unlock(&ice->gpio_mutex);
return 0;
}
#endif
static int prodigy_hd2_init(struct snd_ice1712 *ice)
{
struct prodigy_hifi_spec *spec;
ice->vt1720 = 0;
ice->vt1724 = 1;
ice->num_total_dacs = 1;
ice->num_total_adcs = 1;
/* HACK - use this as the SPDIF source.
* don't call snd_ice1712_gpio_get/put(), otherwise it's overwritten
*/
ice->gpio.saved[0] = 0;
/* to remember the register values */
ice->akm = kzalloc(sizeof(struct snd_akm4xxx), GFP_KERNEL);
if (! ice->akm)
return -ENOMEM;
ice->akm_codecs = 1;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (!spec)
return -ENOMEM;
ice->spec = spec;
#ifdef CONFIG_PM_SLEEP
ice->pm_resume = &prodigy_hd2_resume;
ice->pm_suspend_enabled = 1;
#endif
ak4396_init(ice);
return 0;
}
static unsigned char prodigy71hifi_eeprom[] = {
0x4b, /* SYSCONF: clock 512, spdif-in/ADC, 4DACs */
0x80, /* ACLINK: I2S */
0xfc, /* I2S: vol, 96k, 24bit, 192k */
0xc3, /* SPDIF: out-en, out-int, spdif-in */
0xff, /* GPIO_DIR */
0xff, /* GPIO_DIR1 */
0x5f, /* GPIO_DIR2 */
0x00, /* GPIO_MASK */
0x00, /* GPIO_MASK1 */
0x00, /* GPIO_MASK2 */
0x00, /* GPIO_STATE */
0x00, /* GPIO_STATE1 */
0x00, /* GPIO_STATE2 */
};
static unsigned char prodigyhd2_eeprom[] = {
0x4b, /* SYSCONF: clock 512, spdif-in/ADC, 4DACs */
0x80, /* ACLINK: I2S */
0xfc, /* I2S: vol, 96k, 24bit, 192k */
0xc3, /* SPDIF: out-en, out-int, spdif-in */
0xff, /* GPIO_DIR */
0xff, /* GPIO_DIR1 */
0x5f, /* GPIO_DIR2 */
0x00, /* GPIO_MASK */
0x00, /* GPIO_MASK1 */
0x00, /* GPIO_MASK2 */
0x00, /* GPIO_STATE */
0x00, /* GPIO_STATE1 */
0x00, /* GPIO_STATE2 */
};
static unsigned char fortissimo4_eeprom[] = {
0x43, /* SYSCONF: clock 512, ADC, 4DACs */
0x80, /* ACLINK: I2S */
0xfc, /* I2S: vol, 96k, 24bit, 192k */
0xc1, /* SPDIF: out-en, out-int */
0xff, /* GPIO_DIR */
0xff, /* GPIO_DIR1 */
0x5f, /* GPIO_DIR2 */
0x00, /* GPIO_MASK */
0x00, /* GPIO_MASK1 */
0x00, /* GPIO_MASK2 */
0x00, /* GPIO_STATE */
0x00, /* GPIO_STATE1 */
0x00, /* GPIO_STATE2 */
};
/* entry point */
struct snd_ice1712_card_info snd_vt1724_prodigy_hifi_cards[] = {
{
.subvendor = VT1724_SUBDEVICE_PRODIGY_HIFI,
.name = "Audiotrak Prodigy 7.1 HiFi",
.model = "prodigy71hifi",
.chip_init = prodigy_hifi_init,
.build_controls = prodigy_hifi_add_controls,
.eeprom_size = sizeof(prodigy71hifi_eeprom),
.eeprom_data = prodigy71hifi_eeprom,
.driver = "Prodigy71HIFI",
},
{
.subvendor = VT1724_SUBDEVICE_PRODIGY_HD2,
.name = "Audiotrak Prodigy HD2",
.model = "prodigyhd2",
.chip_init = prodigy_hd2_init,
.build_controls = prodigy_hd2_add_controls,
.eeprom_size = sizeof(prodigyhd2_eeprom),
.eeprom_data = prodigyhd2_eeprom,
.driver = "Prodigy71HD2",
},
{
.subvendor = VT1724_SUBDEVICE_FORTISSIMO4,
.name = "Hercules Fortissimo IV",
.model = "fortissimo4",
.chip_init = prodigy_hifi_init,
.build_controls = prodigy_hifi_add_controls,
.eeprom_size = sizeof(fortissimo4_eeprom),
.eeprom_data = fortissimo4_eeprom,
.driver = "Fortissimo4",
},
{ } /* terminator */
};
| gpl-2.0 |
aj700/nxzimg | net/wireless/mesh.c | 3507 | 4456 | #include <linux/ieee80211.h>
#include <linux/export.h>
#include <net/cfg80211.h>
#include "nl80211.h"
#include "core.h"
/* Default values, timeouts in ms */
#define MESH_TTL 31
#define MESH_DEFAULT_ELEMENT_TTL 31
#define MESH_MAX_RETR 3
#define MESH_RET_T 100
#define MESH_CONF_T 100
#define MESH_HOLD_T 100
#define MESH_PATH_TIMEOUT 5000
#define MESH_RANN_INTERVAL 5000
/*
* Minimum interval between two consecutive PREQs originated by the same
* interface
*/
#define MESH_PREQ_MIN_INT 10
#define MESH_PERR_MIN_INT 100
#define MESH_DIAM_TRAVERSAL_TIME 50
#define MESH_RSSI_THRESHOLD 0
/*
* A path will be refreshed if it is used PATH_REFRESH_TIME milliseconds
* before timing out. This way it will remain ACTIVE and no data frames
* will be unnecessarily held in the pending queue.
*/
#define MESH_PATH_REFRESH_TIME 1000
#define MESH_MIN_DISCOVERY_TIMEOUT (2 * MESH_DIAM_TRAVERSAL_TIME)
/* Default maximum number of established plinks per interface */
#define MESH_MAX_ESTAB_PLINKS 32
#define MESH_MAX_PREQ_RETRIES 4
const struct mesh_config default_mesh_config = {
.dot11MeshRetryTimeout = MESH_RET_T,
.dot11MeshConfirmTimeout = MESH_CONF_T,
.dot11MeshHoldingTimeout = MESH_HOLD_T,
.dot11MeshMaxRetries = MESH_MAX_RETR,
.dot11MeshTTL = MESH_TTL,
.element_ttl = MESH_DEFAULT_ELEMENT_TTL,
.auto_open_plinks = true,
.dot11MeshMaxPeerLinks = MESH_MAX_ESTAB_PLINKS,
.dot11MeshHWMPactivePathTimeout = MESH_PATH_TIMEOUT,
.dot11MeshHWMPpreqMinInterval = MESH_PREQ_MIN_INT,
.dot11MeshHWMPperrMinInterval = MESH_PERR_MIN_INT,
.dot11MeshHWMPnetDiameterTraversalTime = MESH_DIAM_TRAVERSAL_TIME,
.dot11MeshHWMPmaxPREQretries = MESH_MAX_PREQ_RETRIES,
.path_refresh_time = MESH_PATH_REFRESH_TIME,
.min_discovery_timeout = MESH_MIN_DISCOVERY_TIMEOUT,
.dot11MeshHWMPRannInterval = MESH_RANN_INTERVAL,
.dot11MeshGateAnnouncementProtocol = false,
.dot11MeshForwarding = true,
.rssi_threshold = MESH_RSSI_THRESHOLD,
};
const struct mesh_setup default_mesh_setup = {
.path_sel_proto = IEEE80211_PATH_PROTOCOL_HWMP,
.path_metric = IEEE80211_PATH_METRIC_AIRTIME,
.ie = NULL,
.ie_len = 0,
.is_secure = false,
};
int __cfg80211_join_mesh(struct cfg80211_registered_device *rdev,
struct net_device *dev,
const struct mesh_setup *setup,
const struct mesh_config *conf)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err;
BUILD_BUG_ON(IEEE80211_MAX_SSID_LEN != IEEE80211_MAX_MESH_ID_LEN);
ASSERT_WDEV_LOCK(wdev);
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
if (!(rdev->wiphy.flags & WIPHY_FLAG_MESH_AUTH) &&
setup->is_secure)
return -EOPNOTSUPP;
if (wdev->mesh_id_len)
return -EALREADY;
if (!setup->mesh_id_len)
return -EINVAL;
if (!rdev->ops->join_mesh)
return -EOPNOTSUPP;
err = rdev->ops->join_mesh(&rdev->wiphy, dev, conf, setup);
if (!err) {
memcpy(wdev->ssid, setup->mesh_id, setup->mesh_id_len);
wdev->mesh_id_len = setup->mesh_id_len;
}
return err;
}
int cfg80211_join_mesh(struct cfg80211_registered_device *rdev,
struct net_device *dev,
const struct mesh_setup *setup,
const struct mesh_config *conf)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err;
wdev_lock(wdev);
err = __cfg80211_join_mesh(rdev, dev, setup, conf);
wdev_unlock(wdev);
return err;
}
void cfg80211_notify_new_peer_candidate(struct net_device *dev,
const u8 *macaddr, const u8* ie, u8 ie_len, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_MESH_POINT))
return;
nl80211_send_new_peer_candidate(wiphy_to_dev(wdev->wiphy), dev,
macaddr, ie, ie_len, gfp);
}
EXPORT_SYMBOL(cfg80211_notify_new_peer_candidate);
static int __cfg80211_leave_mesh(struct cfg80211_registered_device *rdev,
struct net_device *dev)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err;
ASSERT_WDEV_LOCK(wdev);
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
if (!rdev->ops->leave_mesh)
return -EOPNOTSUPP;
if (!wdev->mesh_id_len)
return -ENOTCONN;
err = rdev->ops->leave_mesh(&rdev->wiphy, dev);
if (!err)
wdev->mesh_id_len = 0;
return err;
}
int cfg80211_leave_mesh(struct cfg80211_registered_device *rdev,
struct net_device *dev)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err;
wdev_lock(wdev);
err = __cfg80211_leave_mesh(rdev, dev);
wdev_unlock(wdev);
return err;
}
| gpl-2.0 |
hiikezoe/android_kernel_nec_n06e | arch/arm/mach-msm/rpc_server_dog_keepalive.c | 3507 | 2062 | /* arch/arm/mach-msm/rpc_server_dog_keepalive.c
*
* Copyright (C) 2007 Google, Inc.
* Copyright (c) 2009, The Linux Foundation. All rights reserved.
* Author: Iliyan Malchev <ibm@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <mach/msm_rpcrouter.h>
/* dog_keepalive server definitions */
#define DOG_KEEPALIVE_PROG 0x30000015
#if CONFIG_MSM_AMSS_VERSION==6210
#define DOG_KEEPALIVE_VERS 0
#define RPC_DOG_KEEPALIVE_BEACON 1
#elif (CONFIG_MSM_AMSS_VERSION==6220) || (CONFIG_MSM_AMSS_VERSION==6225)
#define DOG_KEEPALIVE_VERS 0x731fa727
#define RPC_DOG_KEEPALIVE_BEACON 2
#else
#error "Unsupported AMSS version"
#endif
#define DOG_KEEPALIVE_VERS_COMP 0x00010001
#define RPC_DOG_KEEPALIVE_NULL 0
/* TODO: Remove server registration with _VERS when modem is upated with _COMP*/
static int handle_rpc_call(struct msm_rpc_server *server,
struct rpc_request_hdr *req, unsigned len)
{
switch (req->procedure) {
case RPC_DOG_KEEPALIVE_NULL:
return 0;
case RPC_DOG_KEEPALIVE_BEACON:
return 0;
default:
return -ENODEV;
}
}
static struct msm_rpc_server rpc_server[] = {
{
.prog = DOG_KEEPALIVE_PROG,
.vers = DOG_KEEPALIVE_VERS,
.rpc_call = handle_rpc_call,
},
{
.prog = DOG_KEEPALIVE_PROG,
.vers = DOG_KEEPALIVE_VERS_COMP,
.rpc_call = handle_rpc_call,
},
};
static int __init rpc_server_init(void)
{
/* Dual server registration to support backwards compatibility vers */
int ret;
ret = msm_rpc_create_server(&rpc_server[1]);
if (ret < 0)
return ret;
return msm_rpc_create_server(&rpc_server[0]);
}
module_init(rpc_server_init);
| gpl-2.0 |
sjkoon/original-sgs3-soonjung | drivers/edac/i3000_edac.c | 4275 | 13771 | /*
* Intel 3000/3010 Memory Controller kernel module
* Copyright (C) 2007 Akamai Technologies, Inc.
* Shamelessly copied from:
* Intel D82875P Memory Controller kernel module
* (C) 2003 Linux Networx (http://lnxi.com)
*
* This file may be distributed under the terms of the
* GNU General Public License.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/edac.h>
#include "edac_core.h"
#define I3000_REVISION "1.1"
#define EDAC_MOD_STR "i3000_edac"
#define I3000_RANKS 8
#define I3000_RANKS_PER_CHANNEL 4
#define I3000_CHANNELS 2
/* Intel 3000 register addresses - device 0 function 0 - DRAM Controller */
#define I3000_MCHBAR 0x44 /* MCH Memory Mapped Register BAR */
#define I3000_MCHBAR_MASK 0xffffc000
#define I3000_MMR_WINDOW_SIZE 16384
#define I3000_EDEAP 0x70 /* Extended DRAM Error Address Pointer (8b)
*
* 7:1 reserved
* 0 bit 32 of address
*/
#define I3000_DEAP 0x58 /* DRAM Error Address Pointer (32b)
*
* 31:7 address
* 6:1 reserved
* 0 Error channel 0/1
*/
#define I3000_DEAP_GRAIN (1 << 7)
/*
* Helper functions to decode the DEAP/EDEAP hardware registers.
*
* The type promotion here is deliberate; we're deriving an
* unsigned long pfn and offset from hardware regs which are u8/u32.
*/
static inline unsigned long deap_pfn(u8 edeap, u32 deap)
{
deap >>= PAGE_SHIFT;
deap |= (edeap & 1) << (32 - PAGE_SHIFT);
return deap;
}
static inline unsigned long deap_offset(u32 deap)
{
return deap & ~(I3000_DEAP_GRAIN - 1) & ~PAGE_MASK;
}
static inline int deap_channel(u32 deap)
{
return deap & 1;
}
#define I3000_DERRSYN 0x5c /* DRAM Error Syndrome (8b)
*
* 7:0 DRAM ECC Syndrome
*/
#define I3000_ERRSTS 0xc8 /* Error Status Register (16b)
*
* 15:12 reserved
* 11 MCH Thermal Sensor Event
* for SMI/SCI/SERR
* 10 reserved
* 9 LOCK to non-DRAM Memory Flag (LCKF)
* 8 Received Refresh Timeout Flag (RRTOF)
* 7:2 reserved
* 1 Multi-bit DRAM ECC Error Flag (DMERR)
* 0 Single-bit DRAM ECC Error Flag (DSERR)
*/
#define I3000_ERRSTS_BITS 0x0b03 /* bits which indicate errors */
#define I3000_ERRSTS_UE 0x0002
#define I3000_ERRSTS_CE 0x0001
#define I3000_ERRCMD 0xca /* Error Command (16b)
*
* 15:12 reserved
* 11 SERR on MCH Thermal Sensor Event
* (TSESERR)
* 10 reserved
* 9 SERR on LOCK to non-DRAM Memory
* (LCKERR)
* 8 SERR on DRAM Refresh Timeout
* (DRTOERR)
* 7:2 reserved
* 1 SERR Multi-Bit DRAM ECC Error
* (DMERR)
* 0 SERR on Single-Bit ECC Error
* (DSERR)
*/
/* Intel MMIO register space - device 0 function 0 - MMR space */
#define I3000_DRB_SHIFT 25 /* 32MiB grain */
#define I3000_C0DRB 0x100 /* Channel 0 DRAM Rank Boundary (8b x 4)
*
* 7:0 Channel 0 DRAM Rank Boundary Address
*/
#define I3000_C1DRB 0x180 /* Channel 1 DRAM Rank Boundary (8b x 4)
*
* 7:0 Channel 1 DRAM Rank Boundary Address
*/
#define I3000_C0DRA 0x108 /* Channel 0 DRAM Rank Attribute (8b x 2)
*
* 7 reserved
* 6:4 DRAM odd Rank Attribute
* 3 reserved
* 2:0 DRAM even Rank Attribute
*
* Each attribute defines the page
* size of the corresponding rank:
* 000: unpopulated
* 001: reserved
* 010: 4 KB
* 011: 8 KB
* 100: 16 KB
* Others: reserved
*/
#define I3000_C1DRA 0x188 /* Channel 1 DRAM Rank Attribute (8b x 2) */
static inline unsigned char odd_rank_attrib(unsigned char dra)
{
return (dra & 0x70) >> 4;
}
static inline unsigned char even_rank_attrib(unsigned char dra)
{
return dra & 0x07;
}
#define I3000_C0DRC0 0x120 /* DRAM Controller Mode 0 (32b)
*
* 31:30 reserved
* 29 Initialization Complete (IC)
* 28:11 reserved
* 10:8 Refresh Mode Select (RMS)
* 7 reserved
* 6:4 Mode Select (SMS)
* 3:2 reserved
* 1:0 DRAM Type (DT)
*/
#define I3000_C0DRC1 0x124 /* DRAM Controller Mode 1 (32b)
*
* 31 Enhanced Addressing Enable (ENHADE)
* 30:0 reserved
*/
enum i3000p_chips {
I3000 = 0,
};
struct i3000_dev_info {
const char *ctl_name;
};
struct i3000_error_info {
u16 errsts;
u8 derrsyn;
u8 edeap;
u32 deap;
u16 errsts2;
};
static const struct i3000_dev_info i3000_devs[] = {
[I3000] = {
.ctl_name = "i3000"},
};
static struct pci_dev *mci_pdev;
static int i3000_registered = 1;
static struct edac_pci_ctl_info *i3000_pci;
static void i3000_get_error_info(struct mem_ctl_info *mci,
struct i3000_error_info *info)
{
struct pci_dev *pdev;
pdev = to_pci_dev(mci->dev);
/*
* This is a mess because there is no atomic way to read all the
* registers at once and the registers can transition from CE being
* overwritten by UE.
*/
pci_read_config_word(pdev, I3000_ERRSTS, &info->errsts);
if (!(info->errsts & I3000_ERRSTS_BITS))
return;
pci_read_config_byte(pdev, I3000_EDEAP, &info->edeap);
pci_read_config_dword(pdev, I3000_DEAP, &info->deap);
pci_read_config_byte(pdev, I3000_DERRSYN, &info->derrsyn);
pci_read_config_word(pdev, I3000_ERRSTS, &info->errsts2);
/*
* If the error is the same for both reads then the first set
* of reads is valid. If there is a change then there is a CE
* with no info and the second set of reads is valid and
* should be UE info.
*/
if ((info->errsts ^ info->errsts2) & I3000_ERRSTS_BITS) {
pci_read_config_byte(pdev, I3000_EDEAP, &info->edeap);
pci_read_config_dword(pdev, I3000_DEAP, &info->deap);
pci_read_config_byte(pdev, I3000_DERRSYN, &info->derrsyn);
}
/*
* Clear any error bits.
* (Yes, we really clear bits by writing 1 to them.)
*/
pci_write_bits16(pdev, I3000_ERRSTS, I3000_ERRSTS_BITS,
I3000_ERRSTS_BITS);
}
static int i3000_process_error_info(struct mem_ctl_info *mci,
struct i3000_error_info *info,
int handle_errors)
{
int row, multi_chan, channel;
unsigned long pfn, offset;
multi_chan = mci->csrows[0].nr_channels - 1;
if (!(info->errsts & I3000_ERRSTS_BITS))
return 0;
if (!handle_errors)
return 1;
if ((info->errsts ^ info->errsts2) & I3000_ERRSTS_BITS) {
edac_mc_handle_ce_no_info(mci, "UE overwrote CE");
info->errsts = info->errsts2;
}
pfn = deap_pfn(info->edeap, info->deap);
offset = deap_offset(info->deap);
channel = deap_channel(info->deap);
row = edac_mc_find_csrow_by_page(mci, pfn);
if (info->errsts & I3000_ERRSTS_UE)
edac_mc_handle_ue(mci, pfn, offset, row, "i3000 UE");
else
edac_mc_handle_ce(mci, pfn, offset, info->derrsyn, row,
multi_chan ? channel : 0, "i3000 CE");
return 1;
}
static void i3000_check(struct mem_ctl_info *mci)
{
struct i3000_error_info info;
debugf1("MC%d: %s()\n", mci->mc_idx, __func__);
i3000_get_error_info(mci, &info);
i3000_process_error_info(mci, &info, 1);
}
static int i3000_is_interleaved(const unsigned char *c0dra,
const unsigned char *c1dra,
const unsigned char *c0drb,
const unsigned char *c1drb)
{
int i;
/*
* If the channels aren't populated identically then
* we're not interleaved.
*/
for (i = 0; i < I3000_RANKS_PER_CHANNEL / 2; i++)
if (odd_rank_attrib(c0dra[i]) != odd_rank_attrib(c1dra[i]) ||
even_rank_attrib(c0dra[i]) !=
even_rank_attrib(c1dra[i]))
return 0;
/*
* If the rank boundaries for the two channels are different
* then we're not interleaved.
*/
for (i = 0; i < I3000_RANKS_PER_CHANNEL; i++)
if (c0drb[i] != c1drb[i])
return 0;
return 1;
}
static int i3000_probe1(struct pci_dev *pdev, int dev_idx)
{
int rc;
int i;
struct mem_ctl_info *mci = NULL;
unsigned long last_cumul_size;
int interleaved, nr_channels;
unsigned char dra[I3000_RANKS / 2], drb[I3000_RANKS];
unsigned char *c0dra = dra, *c1dra = &dra[I3000_RANKS_PER_CHANNEL / 2];
unsigned char *c0drb = drb, *c1drb = &drb[I3000_RANKS_PER_CHANNEL];
unsigned long mchbar;
void __iomem *window;
debugf0("MC: %s()\n", __func__);
pci_read_config_dword(pdev, I3000_MCHBAR, (u32 *) & mchbar);
mchbar &= I3000_MCHBAR_MASK;
window = ioremap_nocache(mchbar, I3000_MMR_WINDOW_SIZE);
if (!window) {
printk(KERN_ERR "i3000: cannot map mmio space at 0x%lx\n",
mchbar);
return -ENODEV;
}
c0dra[0] = readb(window + I3000_C0DRA + 0); /* ranks 0,1 */
c0dra[1] = readb(window + I3000_C0DRA + 1); /* ranks 2,3 */
c1dra[0] = readb(window + I3000_C1DRA + 0); /* ranks 0,1 */
c1dra[1] = readb(window + I3000_C1DRA + 1); /* ranks 2,3 */
for (i = 0; i < I3000_RANKS_PER_CHANNEL; i++) {
c0drb[i] = readb(window + I3000_C0DRB + i);
c1drb[i] = readb(window + I3000_C1DRB + i);
}
iounmap(window);
/*
* Figure out how many channels we have.
*
* If we have what the datasheet calls "asymmetric channels"
* (essentially the same as what was called "virtual single
* channel mode" in the i82875) then it's a single channel as
* far as EDAC is concerned.
*/
interleaved = i3000_is_interleaved(c0dra, c1dra, c0drb, c1drb);
nr_channels = interleaved ? 2 : 1;
mci = edac_mc_alloc(0, I3000_RANKS / nr_channels, nr_channels, 0);
if (!mci)
return -ENOMEM;
debugf3("MC: %s(): init mci\n", __func__);
mci->dev = &pdev->dev;
mci->mtype_cap = MEM_FLAG_DDR2;
mci->edac_ctl_cap = EDAC_FLAG_SECDED;
mci->edac_cap = EDAC_FLAG_SECDED;
mci->mod_name = EDAC_MOD_STR;
mci->mod_ver = I3000_REVISION;
mci->ctl_name = i3000_devs[dev_idx].ctl_name;
mci->dev_name = pci_name(pdev);
mci->edac_check = i3000_check;
mci->ctl_page_to_phys = NULL;
/*
* The dram rank boundary (DRB) reg values are boundary addresses
* for each DRAM rank with a granularity of 32MB. DRB regs are
* cumulative; the last one will contain the total memory
* contained in all ranks.
*
* If we're in interleaved mode then we're only walking through
* the ranks of controller 0, so we double all the values we see.
*/
for (last_cumul_size = i = 0; i < mci->nr_csrows; i++) {
u8 value;
u32 cumul_size;
struct csrow_info *csrow = &mci->csrows[i];
value = drb[i];
cumul_size = value << (I3000_DRB_SHIFT - PAGE_SHIFT);
if (interleaved)
cumul_size <<= 1;
debugf3("MC: %s(): (%d) cumul_size 0x%x\n",
__func__, i, cumul_size);
if (cumul_size == last_cumul_size) {
csrow->mtype = MEM_EMPTY;
continue;
}
csrow->first_page = last_cumul_size;
csrow->last_page = cumul_size - 1;
csrow->nr_pages = cumul_size - last_cumul_size;
last_cumul_size = cumul_size;
csrow->grain = I3000_DEAP_GRAIN;
csrow->mtype = MEM_DDR2;
csrow->dtype = DEV_UNKNOWN;
csrow->edac_mode = EDAC_UNKNOWN;
}
/*
* Clear any error bits.
* (Yes, we really clear bits by writing 1 to them.)
*/
pci_write_bits16(pdev, I3000_ERRSTS, I3000_ERRSTS_BITS,
I3000_ERRSTS_BITS);
rc = -ENODEV;
if (edac_mc_add_mc(mci)) {
debugf3("MC: %s(): failed edac_mc_add_mc()\n", __func__);
goto fail;
}
/* allocating generic PCI control info */
i3000_pci = edac_pci_create_generic_ctl(&pdev->dev, EDAC_MOD_STR);
if (!i3000_pci) {
printk(KERN_WARNING
"%s(): Unable to create PCI control\n",
__func__);
printk(KERN_WARNING
"%s(): PCI error report via EDAC not setup\n",
__func__);
}
/* get this far and it's successful */
debugf3("MC: %s(): success\n", __func__);
return 0;
fail:
if (mci)
edac_mc_free(mci);
return rc;
}
/* returns count (>= 0), or negative on error */
static int __devinit i3000_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
int rc;
debugf0("MC: %s()\n", __func__);
if (pci_enable_device(pdev) < 0)
return -EIO;
rc = i3000_probe1(pdev, ent->driver_data);
if (!mci_pdev)
mci_pdev = pci_dev_get(pdev);
return rc;
}
static void __devexit i3000_remove_one(struct pci_dev *pdev)
{
struct mem_ctl_info *mci;
debugf0("%s()\n", __func__);
if (i3000_pci)
edac_pci_release_generic_ctl(i3000_pci);
mci = edac_mc_del_mc(&pdev->dev);
if (!mci)
return;
edac_mc_free(mci);
}
static const struct pci_device_id i3000_pci_tbl[] __devinitdata = {
{
PCI_VEND_DEV(INTEL, 3000_HB), PCI_ANY_ID, PCI_ANY_ID, 0, 0,
I3000},
{
0,
} /* 0 terminated list. */
};
MODULE_DEVICE_TABLE(pci, i3000_pci_tbl);
static struct pci_driver i3000_driver = {
.name = EDAC_MOD_STR,
.probe = i3000_init_one,
.remove = __devexit_p(i3000_remove_one),
.id_table = i3000_pci_tbl,
};
static int __init i3000_init(void)
{
int pci_rc;
debugf3("MC: %s()\n", __func__);
/* Ensure that the OPSTATE is set correctly for POLL or NMI */
opstate_init();
pci_rc = pci_register_driver(&i3000_driver);
if (pci_rc < 0)
goto fail0;
if (!mci_pdev) {
i3000_registered = 0;
mci_pdev = pci_get_device(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_3000_HB, NULL);
if (!mci_pdev) {
debugf0("i3000 pci_get_device fail\n");
pci_rc = -ENODEV;
goto fail1;
}
pci_rc = i3000_init_one(mci_pdev, i3000_pci_tbl);
if (pci_rc < 0) {
debugf0("i3000 init fail\n");
pci_rc = -ENODEV;
goto fail1;
}
}
return 0;
fail1:
pci_unregister_driver(&i3000_driver);
fail0:
if (mci_pdev)
pci_dev_put(mci_pdev);
return pci_rc;
}
static void __exit i3000_exit(void)
{
debugf3("MC: %s()\n", __func__);
pci_unregister_driver(&i3000_driver);
if (!i3000_registered) {
i3000_remove_one(mci_pdev);
pci_dev_put(mci_pdev);
}
}
module_init(i3000_init);
module_exit(i3000_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Akamai Technologies Arthur Ulfeldt/Jason Uhlenkott");
MODULE_DESCRIPTION("MC support for Intel 3000 memory hub controllers");
module_param(edac_op_state, int, 0444);
MODULE_PARM_DESC(edac_op_state, "EDAC Error Reporting state: 0=Poll,1=NMI");
| gpl-2.0 |
jfdsmabalot/kernel_samsung_msm8974ab | arch/arm/mach-omap2/omap_hwmod_2xxx_ipblock_data.c | 4787 | 4642 | /*
* omap_hwmod_2xxx_ipblock_data.c - common IP block data for OMAP2xxx
*
* Copyright (C) 2011 Nokia Corporation
* Paul Walmsley
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <plat/omap_hwmod.h>
#include <plat/serial.h>
#include <plat/dma.h>
#include <plat/dmtimer.h>
#include <plat/mcspi.h>
#include <mach/irqs.h>
#include "omap_hwmod_common_data.h"
#include "wd_timer.h"
struct omap_hwmod_irq_info omap2xxx_timer12_mpu_irqs[] = {
{ .irq = 48, },
{ .irq = -1 }
};
struct omap_hwmod_dma_info omap2xxx_dss_sdma_chs[] = {
{ .name = "dispc", .dma_req = 5 },
{ .dma_req = -1 }
};
/*
* 'dispc' class
* display controller
*/
static struct omap_hwmod_class_sysconfig omap2_dispc_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_SIDLEMODE | SYSC_HAS_MIDLEMODE |
SYSC_HAS_SOFTRESET | SYSC_HAS_AUTOIDLE),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART |
MSTANDBY_FORCE | MSTANDBY_NO | MSTANDBY_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
struct omap_hwmod_class omap2_dispc_hwmod_class = {
.name = "dispc",
.sysc = &omap2_dispc_sysc,
};
/* OMAP2xxx Timer Common */
static struct omap_hwmod_class_sysconfig omap2xxx_timer_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_SIDLEMODE | SYSC_HAS_CLOCKACTIVITY |
SYSC_HAS_ENAWAKEUP | SYSC_HAS_SOFTRESET |
SYSC_HAS_AUTOIDLE),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
struct omap_hwmod_class omap2xxx_timer_hwmod_class = {
.name = "timer",
.sysc = &omap2xxx_timer_sysc,
.rev = OMAP_TIMER_IP_VERSION_1,
};
/*
* 'wd_timer' class
* 32-bit watchdog upward counter that generates a pulse on the reset pin on
* overflow condition
*/
static struct omap_hwmod_class_sysconfig omap2xxx_wd_timer_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_EMUFREE | SYSC_HAS_SOFTRESET |
SYSC_HAS_AUTOIDLE | SYSS_HAS_RESET_STATUS),
.sysc_fields = &omap_hwmod_sysc_type1,
};
struct omap_hwmod_class omap2xxx_wd_timer_hwmod_class = {
.name = "wd_timer",
.sysc = &omap2xxx_wd_timer_sysc,
.pre_shutdown = &omap2_wd_timer_disable
};
/*
* 'gpio' class
* general purpose io module
*/
static struct omap_hwmod_class_sysconfig omap2xxx_gpio_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_ENAWAKEUP | SYSC_HAS_SIDLEMODE |
SYSC_HAS_SOFTRESET | SYSC_HAS_AUTOIDLE |
SYSS_HAS_RESET_STATUS),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
struct omap_hwmod_class omap2xxx_gpio_hwmod_class = {
.name = "gpio",
.sysc = &omap2xxx_gpio_sysc,
.rev = 0,
};
/* system dma */
static struct omap_hwmod_class_sysconfig omap2xxx_dma_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x002c,
.syss_offs = 0x0028,
.sysc_flags = (SYSC_HAS_SOFTRESET | SYSC_HAS_MIDLEMODE |
SYSC_HAS_CLOCKACTIVITY | SYSC_HAS_EMUFREE |
SYSC_HAS_AUTOIDLE | SYSS_HAS_RESET_STATUS),
.idlemodes = (MSTANDBY_FORCE | MSTANDBY_NO | MSTANDBY_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
struct omap_hwmod_class omap2xxx_dma_hwmod_class = {
.name = "dma",
.sysc = &omap2xxx_dma_sysc,
};
/*
* 'mailbox' class
* mailbox module allowing communication between the on-chip processors
* using a queued mailbox-interrupt mechanism.
*/
static struct omap_hwmod_class_sysconfig omap2xxx_mailbox_sysc = {
.rev_offs = 0x000,
.sysc_offs = 0x010,
.syss_offs = 0x014,
.sysc_flags = (SYSC_HAS_CLOCKACTIVITY | SYSC_HAS_SIDLEMODE |
SYSC_HAS_SOFTRESET | SYSC_HAS_AUTOIDLE),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
struct omap_hwmod_class omap2xxx_mailbox_hwmod_class = {
.name = "mailbox",
.sysc = &omap2xxx_mailbox_sysc,
};
/*
* 'mcspi' class
* multichannel serial port interface (mcspi) / master/slave synchronous serial
* bus
*/
static struct omap_hwmod_class_sysconfig omap2xxx_mcspi_sysc = {
.rev_offs = 0x0000,
.sysc_offs = 0x0010,
.syss_offs = 0x0014,
.sysc_flags = (SYSC_HAS_CLOCKACTIVITY | SYSC_HAS_SIDLEMODE |
SYSC_HAS_ENAWAKEUP | SYSC_HAS_SOFTRESET |
SYSC_HAS_AUTOIDLE | SYSS_HAS_RESET_STATUS),
.idlemodes = (SIDLE_FORCE | SIDLE_NO | SIDLE_SMART),
.sysc_fields = &omap_hwmod_sysc_type1,
};
struct omap_hwmod_class omap2xxx_mcspi_class = {
.name = "mcspi",
.sysc = &omap2xxx_mcspi_sysc,
.rev = OMAP2_MCSPI_REV,
};
| gpl-2.0 |
StelixROM/android_kernel_google_msm | drivers/input/touchscreen/tsc2005.c | 4787 | 18592 | /*
* TSC2005 touchscreen driver
*
* Copyright (C) 2006-2010 Nokia Corporation
*
* Author: Lauri Leukkunen <lauri.leukkunen@nokia.com>
* based on TSC2301 driver by Klaus K. Pedersen <klaus.k.pedersen@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/module.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/pm.h>
#include <linux/spi/spi.h>
#include <linux/spi/tsc2005.h>
/*
* The touchscreen interface operates as follows:
*
* 1) Pen is pressed against the touchscreen.
* 2) TSC2005 performs AD conversion.
* 3) After the conversion is done TSC2005 drives DAV line down.
* 4) GPIO IRQ is received and tsc2005_irq_thread() is scheduled.
* 5) tsc2005_irq_thread() queues up an spi transfer to fetch the x, y, z1, z2
* values.
* 6) tsc2005_irq_thread() reports coordinates to input layer and sets up
* tsc2005_penup_timer() to be called after TSC2005_PENUP_TIME_MS (40ms).
* 7) When the penup timer expires, there have not been touch or DAV interrupts
* during the last 40ms which means the pen has been lifted.
*
* ESD recovery via a hardware reset is done if the TSC2005 doesn't respond
* after a configurable period (in ms) of activity. If esd_timeout is 0, the
* watchdog is disabled.
*/
/* control byte 1 */
#define TSC2005_CMD 0x80
#define TSC2005_CMD_NORMAL 0x00
#define TSC2005_CMD_STOP 0x01
#define TSC2005_CMD_12BIT 0x04
/* control byte 0 */
#define TSC2005_REG_READ 0x0001
#define TSC2005_REG_PND0 0x0002
#define TSC2005_REG_X 0x0000
#define TSC2005_REG_Y 0x0008
#define TSC2005_REG_Z1 0x0010
#define TSC2005_REG_Z2 0x0018
#define TSC2005_REG_TEMP_HIGH 0x0050
#define TSC2005_REG_CFR0 0x0060
#define TSC2005_REG_CFR1 0x0068
#define TSC2005_REG_CFR2 0x0070
/* configuration register 0 */
#define TSC2005_CFR0_PRECHARGE_276US 0x0040
#define TSC2005_CFR0_STABTIME_1MS 0x0300
#define TSC2005_CFR0_CLOCK_1MHZ 0x1000
#define TSC2005_CFR0_RESOLUTION12 0x2000
#define TSC2005_CFR0_PENMODE 0x8000
#define TSC2005_CFR0_INITVALUE (TSC2005_CFR0_STABTIME_1MS | \
TSC2005_CFR0_CLOCK_1MHZ | \
TSC2005_CFR0_RESOLUTION12 | \
TSC2005_CFR0_PRECHARGE_276US | \
TSC2005_CFR0_PENMODE)
/* bits common to both read and write of configuration register 0 */
#define TSC2005_CFR0_RW_MASK 0x3fff
/* configuration register 1 */
#define TSC2005_CFR1_BATCHDELAY_4MS 0x0003
#define TSC2005_CFR1_INITVALUE TSC2005_CFR1_BATCHDELAY_4MS
/* configuration register 2 */
#define TSC2005_CFR2_MAVE_Z 0x0004
#define TSC2005_CFR2_MAVE_Y 0x0008
#define TSC2005_CFR2_MAVE_X 0x0010
#define TSC2005_CFR2_AVG_7 0x0800
#define TSC2005_CFR2_MEDIUM_15 0x3000
#define TSC2005_CFR2_INITVALUE (TSC2005_CFR2_MAVE_X | \
TSC2005_CFR2_MAVE_Y | \
TSC2005_CFR2_MAVE_Z | \
TSC2005_CFR2_MEDIUM_15 | \
TSC2005_CFR2_AVG_7)
#define MAX_12BIT 0xfff
#define TSC2005_SPI_MAX_SPEED_HZ 10000000
#define TSC2005_PENUP_TIME_MS 40
struct tsc2005_spi_rd {
struct spi_transfer spi_xfer;
u32 spi_tx;
u32 spi_rx;
};
struct tsc2005 {
struct spi_device *spi;
struct spi_message spi_read_msg;
struct tsc2005_spi_rd spi_x;
struct tsc2005_spi_rd spi_y;
struct tsc2005_spi_rd spi_z1;
struct tsc2005_spi_rd spi_z2;
struct input_dev *idev;
char phys[32];
struct mutex mutex;
/* raw copy of previous x,y,z */
int in_x;
int in_y;
int in_z1;
int in_z2;
spinlock_t lock;
struct timer_list penup_timer;
unsigned int esd_timeout;
struct delayed_work esd_work;
unsigned long last_valid_interrupt;
unsigned int x_plate_ohm;
bool opened;
bool suspended;
bool pen_down;
void (*set_reset)(bool enable);
};
static int tsc2005_cmd(struct tsc2005 *ts, u8 cmd)
{
u8 tx = TSC2005_CMD | TSC2005_CMD_12BIT | cmd;
struct spi_transfer xfer = {
.tx_buf = &tx,
.len = 1,
.bits_per_word = 8,
};
struct spi_message msg;
int error;
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
error = spi_sync(ts->spi, &msg);
if (error) {
dev_err(&ts->spi->dev, "%s: failed, command: %x, error: %d\n",
__func__, cmd, error);
return error;
}
return 0;
}
static int tsc2005_write(struct tsc2005 *ts, u8 reg, u16 value)
{
u32 tx = ((reg | TSC2005_REG_PND0) << 16) | value;
struct spi_transfer xfer = {
.tx_buf = &tx,
.len = 4,
.bits_per_word = 24,
};
struct spi_message msg;
int error;
spi_message_init(&msg);
spi_message_add_tail(&xfer, &msg);
error = spi_sync(ts->spi, &msg);
if (error) {
dev_err(&ts->spi->dev,
"%s: failed, register: %x, value: %x, error: %d\n",
__func__, reg, value, error);
return error;
}
return 0;
}
static void tsc2005_setup_read(struct tsc2005_spi_rd *rd, u8 reg, bool last)
{
memset(rd, 0, sizeof(*rd));
rd->spi_tx = (reg | TSC2005_REG_READ) << 16;
rd->spi_xfer.tx_buf = &rd->spi_tx;
rd->spi_xfer.rx_buf = &rd->spi_rx;
rd->spi_xfer.len = 4;
rd->spi_xfer.bits_per_word = 24;
rd->spi_xfer.cs_change = !last;
}
static int tsc2005_read(struct tsc2005 *ts, u8 reg, u16 *value)
{
struct tsc2005_spi_rd spi_rd;
struct spi_message msg;
int error;
tsc2005_setup_read(&spi_rd, reg, true);
spi_message_init(&msg);
spi_message_add_tail(&spi_rd.spi_xfer, &msg);
error = spi_sync(ts->spi, &msg);
if (error)
return error;
*value = spi_rd.spi_rx;
return 0;
}
static void tsc2005_update_pen_state(struct tsc2005 *ts,
int x, int y, int pressure)
{
if (pressure) {
input_report_abs(ts->idev, ABS_X, x);
input_report_abs(ts->idev, ABS_Y, y);
input_report_abs(ts->idev, ABS_PRESSURE, pressure);
if (!ts->pen_down) {
input_report_key(ts->idev, BTN_TOUCH, !!pressure);
ts->pen_down = true;
}
} else {
input_report_abs(ts->idev, ABS_PRESSURE, 0);
if (ts->pen_down) {
input_report_key(ts->idev, BTN_TOUCH, 0);
ts->pen_down = false;
}
}
input_sync(ts->idev);
dev_dbg(&ts->spi->dev, "point(%4d,%4d), pressure (%4d)\n", x, y,
pressure);
}
static irqreturn_t tsc2005_irq_thread(int irq, void *_ts)
{
struct tsc2005 *ts = _ts;
unsigned long flags;
unsigned int pressure;
u32 x, y;
u32 z1, z2;
int error;
/* read the coordinates */
error = spi_sync(ts->spi, &ts->spi_read_msg);
if (unlikely(error))
goto out;
x = ts->spi_x.spi_rx;
y = ts->spi_y.spi_rx;
z1 = ts->spi_z1.spi_rx;
z2 = ts->spi_z2.spi_rx;
/* validate position */
if (unlikely(x > MAX_12BIT || y > MAX_12BIT))
goto out;
/* Skip reading if the pressure components are out of range */
if (unlikely(z1 == 0 || z2 > MAX_12BIT || z1 >= z2))
goto out;
/*
* Skip point if this is a pen down with the exact same values as
* the value before pen-up - that implies SPI fed us stale data
*/
if (!ts->pen_down &&
ts->in_x == x && ts->in_y == y &&
ts->in_z1 == z1 && ts->in_z2 == z2) {
goto out;
}
/*
* At this point we are happy we have a valid and useful reading.
* Remember it for later comparisons. We may now begin downsampling.
*/
ts->in_x = x;
ts->in_y = y;
ts->in_z1 = z1;
ts->in_z2 = z2;
/* Compute touch pressure resistance using equation #1 */
pressure = x * (z2 - z1) / z1;
pressure = pressure * ts->x_plate_ohm / 4096;
if (unlikely(pressure > MAX_12BIT))
goto out;
spin_lock_irqsave(&ts->lock, flags);
tsc2005_update_pen_state(ts, x, y, pressure);
mod_timer(&ts->penup_timer,
jiffies + msecs_to_jiffies(TSC2005_PENUP_TIME_MS));
spin_unlock_irqrestore(&ts->lock, flags);
ts->last_valid_interrupt = jiffies;
out:
return IRQ_HANDLED;
}
static void tsc2005_penup_timer(unsigned long data)
{
struct tsc2005 *ts = (struct tsc2005 *)data;
unsigned long flags;
spin_lock_irqsave(&ts->lock, flags);
tsc2005_update_pen_state(ts, 0, 0, 0);
spin_unlock_irqrestore(&ts->lock, flags);
}
static void tsc2005_start_scan(struct tsc2005 *ts)
{
tsc2005_write(ts, TSC2005_REG_CFR0, TSC2005_CFR0_INITVALUE);
tsc2005_write(ts, TSC2005_REG_CFR1, TSC2005_CFR1_INITVALUE);
tsc2005_write(ts, TSC2005_REG_CFR2, TSC2005_CFR2_INITVALUE);
tsc2005_cmd(ts, TSC2005_CMD_NORMAL);
}
static void tsc2005_stop_scan(struct tsc2005 *ts)
{
tsc2005_cmd(ts, TSC2005_CMD_STOP);
}
/* must be called with ts->mutex held */
static void __tsc2005_disable(struct tsc2005 *ts)
{
tsc2005_stop_scan(ts);
disable_irq(ts->spi->irq);
del_timer_sync(&ts->penup_timer);
cancel_delayed_work_sync(&ts->esd_work);
enable_irq(ts->spi->irq);
}
/* must be called with ts->mutex held */
static void __tsc2005_enable(struct tsc2005 *ts)
{
tsc2005_start_scan(ts);
if (ts->esd_timeout && ts->set_reset) {
ts->last_valid_interrupt = jiffies;
schedule_delayed_work(&ts->esd_work,
round_jiffies_relative(
msecs_to_jiffies(ts->esd_timeout)));
}
}
static ssize_t tsc2005_selftest_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct spi_device *spi = to_spi_device(dev);
struct tsc2005 *ts = spi_get_drvdata(spi);
u16 temp_high;
u16 temp_high_orig;
u16 temp_high_test;
bool success = true;
int error;
mutex_lock(&ts->mutex);
/*
* Test TSC2005 communications via temp high register.
*/
__tsc2005_disable(ts);
error = tsc2005_read(ts, TSC2005_REG_TEMP_HIGH, &temp_high_orig);
if (error) {
dev_warn(dev, "selftest failed: read error %d\n", error);
success = false;
goto out;
}
temp_high_test = (temp_high_orig - 1) & MAX_12BIT;
error = tsc2005_write(ts, TSC2005_REG_TEMP_HIGH, temp_high_test);
if (error) {
dev_warn(dev, "selftest failed: write error %d\n", error);
success = false;
goto out;
}
error = tsc2005_read(ts, TSC2005_REG_TEMP_HIGH, &temp_high);
if (error) {
dev_warn(dev, "selftest failed: read error %d after write\n",
error);
success = false;
goto out;
}
if (temp_high != temp_high_test) {
dev_warn(dev, "selftest failed: %d != %d\n",
temp_high, temp_high_test);
success = false;
}
/* hardware reset */
ts->set_reset(false);
usleep_range(100, 500); /* only 10us required */
ts->set_reset(true);
if (!success)
goto out;
/* test that the reset really happened */
error = tsc2005_read(ts, TSC2005_REG_TEMP_HIGH, &temp_high);
if (error) {
dev_warn(dev, "selftest failed: read error %d after reset\n",
error);
success = false;
goto out;
}
if (temp_high != temp_high_orig) {
dev_warn(dev, "selftest failed after reset: %d != %d\n",
temp_high, temp_high_orig);
success = false;
}
out:
__tsc2005_enable(ts);
mutex_unlock(&ts->mutex);
return sprintf(buf, "%d\n", success);
}
static DEVICE_ATTR(selftest, S_IRUGO, tsc2005_selftest_show, NULL);
static struct attribute *tsc2005_attrs[] = {
&dev_attr_selftest.attr,
NULL
};
static umode_t tsc2005_attr_is_visible(struct kobject *kobj,
struct attribute *attr, int n)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct spi_device *spi = to_spi_device(dev);
struct tsc2005 *ts = spi_get_drvdata(spi);
umode_t mode = attr->mode;
if (attr == &dev_attr_selftest.attr) {
if (!ts->set_reset)
mode = 0;
}
return mode;
}
static const struct attribute_group tsc2005_attr_group = {
.is_visible = tsc2005_attr_is_visible,
.attrs = tsc2005_attrs,
};
static void tsc2005_esd_work(struct work_struct *work)
{
struct tsc2005 *ts = container_of(work, struct tsc2005, esd_work.work);
int error;
u16 r;
if (!mutex_trylock(&ts->mutex)) {
/*
* If the mutex is taken, it means that disable or enable is in
* progress. In that case just reschedule the work. If the work
* is not needed, it will be canceled by disable.
*/
goto reschedule;
}
if (time_is_after_jiffies(ts->last_valid_interrupt +
msecs_to_jiffies(ts->esd_timeout)))
goto out;
/* We should be able to read register without disabling interrupts. */
error = tsc2005_read(ts, TSC2005_REG_CFR0, &r);
if (!error &&
!((r ^ TSC2005_CFR0_INITVALUE) & TSC2005_CFR0_RW_MASK)) {
goto out;
}
/*
* If we could not read our known value from configuration register 0
* then we should reset the controller as if from power-up and start
* scanning again.
*/
dev_info(&ts->spi->dev, "TSC2005 not responding - resetting\n");
disable_irq(ts->spi->irq);
del_timer_sync(&ts->penup_timer);
tsc2005_update_pen_state(ts, 0, 0, 0);
ts->set_reset(false);
usleep_range(100, 500); /* only 10us required */
ts->set_reset(true);
enable_irq(ts->spi->irq);
tsc2005_start_scan(ts);
out:
mutex_unlock(&ts->mutex);
reschedule:
/* re-arm the watchdog */
schedule_delayed_work(&ts->esd_work,
round_jiffies_relative(
msecs_to_jiffies(ts->esd_timeout)));
}
static int tsc2005_open(struct input_dev *input)
{
struct tsc2005 *ts = input_get_drvdata(input);
mutex_lock(&ts->mutex);
if (!ts->suspended)
__tsc2005_enable(ts);
ts->opened = true;
mutex_unlock(&ts->mutex);
return 0;
}
static void tsc2005_close(struct input_dev *input)
{
struct tsc2005 *ts = input_get_drvdata(input);
mutex_lock(&ts->mutex);
if (!ts->suspended)
__tsc2005_disable(ts);
ts->opened = false;
mutex_unlock(&ts->mutex);
}
static void __devinit tsc2005_setup_spi_xfer(struct tsc2005 *ts)
{
tsc2005_setup_read(&ts->spi_x, TSC2005_REG_X, false);
tsc2005_setup_read(&ts->spi_y, TSC2005_REG_Y, false);
tsc2005_setup_read(&ts->spi_z1, TSC2005_REG_Z1, false);
tsc2005_setup_read(&ts->spi_z2, TSC2005_REG_Z2, true);
spi_message_init(&ts->spi_read_msg);
spi_message_add_tail(&ts->spi_x.spi_xfer, &ts->spi_read_msg);
spi_message_add_tail(&ts->spi_y.spi_xfer, &ts->spi_read_msg);
spi_message_add_tail(&ts->spi_z1.spi_xfer, &ts->spi_read_msg);
spi_message_add_tail(&ts->spi_z2.spi_xfer, &ts->spi_read_msg);
}
static int __devinit tsc2005_probe(struct spi_device *spi)
{
const struct tsc2005_platform_data *pdata = spi->dev.platform_data;
struct tsc2005 *ts;
struct input_dev *input_dev;
unsigned int max_x, max_y, max_p;
unsigned int fudge_x, fudge_y, fudge_p;
int error;
if (!pdata) {
dev_dbg(&spi->dev, "no platform data\n");
return -ENODEV;
}
fudge_x = pdata->ts_x_fudge ? : 4;
fudge_y = pdata->ts_y_fudge ? : 8;
fudge_p = pdata->ts_pressure_fudge ? : 2;
max_x = pdata->ts_x_max ? : MAX_12BIT;
max_y = pdata->ts_y_max ? : MAX_12BIT;
max_p = pdata->ts_pressure_max ? : MAX_12BIT;
if (spi->irq <= 0) {
dev_dbg(&spi->dev, "no irq\n");
return -ENODEV;
}
spi->mode = SPI_MODE_0;
spi->bits_per_word = 8;
if (!spi->max_speed_hz)
spi->max_speed_hz = TSC2005_SPI_MAX_SPEED_HZ;
error = spi_setup(spi);
if (error)
return error;
ts = kzalloc(sizeof(*ts), GFP_KERNEL);
input_dev = input_allocate_device();
if (!ts || !input_dev) {
error = -ENOMEM;
goto err_free_mem;
}
ts->spi = spi;
ts->idev = input_dev;
ts->x_plate_ohm = pdata->ts_x_plate_ohm ? : 280;
ts->esd_timeout = pdata->esd_timeout_ms;
ts->set_reset = pdata->set_reset;
mutex_init(&ts->mutex);
spin_lock_init(&ts->lock);
setup_timer(&ts->penup_timer, tsc2005_penup_timer, (unsigned long)ts);
INIT_DELAYED_WORK(&ts->esd_work, tsc2005_esd_work);
tsc2005_setup_spi_xfer(ts);
snprintf(ts->phys, sizeof(ts->phys),
"%s/input-ts", dev_name(&spi->dev));
input_dev->name = "TSC2005 touchscreen";
input_dev->phys = ts->phys;
input_dev->id.bustype = BUS_SPI;
input_dev->dev.parent = &spi->dev;
input_dev->evbit[0] = BIT(EV_ABS) | BIT(EV_KEY);
input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(input_dev, ABS_X, 0, max_x, fudge_x, 0);
input_set_abs_params(input_dev, ABS_Y, 0, max_y, fudge_y, 0);
input_set_abs_params(input_dev, ABS_PRESSURE, 0, max_p, fudge_p, 0);
input_dev->open = tsc2005_open;
input_dev->close = tsc2005_close;
input_set_drvdata(input_dev, ts);
/* Ensure the touchscreen is off */
tsc2005_stop_scan(ts);
error = request_threaded_irq(spi->irq, NULL, tsc2005_irq_thread,
IRQF_TRIGGER_RISING, "tsc2005", ts);
if (error) {
dev_err(&spi->dev, "Failed to request irq, err: %d\n", error);
goto err_free_mem;
}
spi_set_drvdata(spi, ts);
error = sysfs_create_group(&spi->dev.kobj, &tsc2005_attr_group);
if (error) {
dev_err(&spi->dev,
"Failed to create sysfs attributes, err: %d\n", error);
goto err_clear_drvdata;
}
error = input_register_device(ts->idev);
if (error) {
dev_err(&spi->dev,
"Failed to register input device, err: %d\n", error);
goto err_remove_sysfs;
}
irq_set_irq_wake(spi->irq, 1);
return 0;
err_remove_sysfs:
sysfs_remove_group(&spi->dev.kobj, &tsc2005_attr_group);
err_clear_drvdata:
spi_set_drvdata(spi, NULL);
free_irq(spi->irq, ts);
err_free_mem:
input_free_device(input_dev);
kfree(ts);
return error;
}
static int __devexit tsc2005_remove(struct spi_device *spi)
{
struct tsc2005 *ts = spi_get_drvdata(spi);
sysfs_remove_group(&ts->spi->dev.kobj, &tsc2005_attr_group);
free_irq(ts->spi->irq, ts);
input_unregister_device(ts->idev);
kfree(ts);
spi_set_drvdata(spi, NULL);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int tsc2005_suspend(struct device *dev)
{
struct spi_device *spi = to_spi_device(dev);
struct tsc2005 *ts = spi_get_drvdata(spi);
mutex_lock(&ts->mutex);
if (!ts->suspended && ts->opened)
__tsc2005_disable(ts);
ts->suspended = true;
mutex_unlock(&ts->mutex);
return 0;
}
static int tsc2005_resume(struct device *dev)
{
struct spi_device *spi = to_spi_device(dev);
struct tsc2005 *ts = spi_get_drvdata(spi);
mutex_lock(&ts->mutex);
if (ts->suspended && ts->opened)
__tsc2005_enable(ts);
ts->suspended = false;
mutex_unlock(&ts->mutex);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(tsc2005_pm_ops, tsc2005_suspend, tsc2005_resume);
static struct spi_driver tsc2005_driver = {
.driver = {
.name = "tsc2005",
.owner = THIS_MODULE,
.pm = &tsc2005_pm_ops,
},
.probe = tsc2005_probe,
.remove = __devexit_p(tsc2005_remove),
};
module_spi_driver(tsc2005_driver);
MODULE_AUTHOR("Lauri Leukkunen <lauri.leukkunen@nokia.com>");
MODULE_DESCRIPTION("TSC2005 Touchscreen Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
motley-git/Kernel-Nexus7 | arch/arm/mach-at91/sam9_smc.c | 4787 | 1230 | /*
* linux/arch/arm/mach-at91/sam9_smc.c
*
* Copyright (C) 2008 Andrew Victor
*
* 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/io.h>
#include <mach/at91sam9_smc.h>
#include "sam9_smc.h"
void __init sam9_smc_configure(int cs, struct sam9_smc_config* config)
{
/* Setup register */
at91_sys_write(AT91_SMC_SETUP(cs),
AT91_SMC_NWESETUP_(config->nwe_setup)
| AT91_SMC_NCS_WRSETUP_(config->ncs_write_setup)
| AT91_SMC_NRDSETUP_(config->nrd_setup)
| AT91_SMC_NCS_RDSETUP_(config->ncs_read_setup)
);
/* Pulse register */
at91_sys_write(AT91_SMC_PULSE(cs),
AT91_SMC_NWEPULSE_(config->nwe_pulse)
| AT91_SMC_NCS_WRPULSE_(config->ncs_write_pulse)
| AT91_SMC_NRDPULSE_(config->nrd_pulse)
| AT91_SMC_NCS_RDPULSE_(config->ncs_read_pulse)
);
/* Cycle register */
at91_sys_write(AT91_SMC_CYCLE(cs),
AT91_SMC_NWECYCLE_(config->write_cycle)
| AT91_SMC_NRDCYCLE_(config->read_cycle)
);
/* Mode register */
at91_sys_write(AT91_SMC_MODE(cs),
config->mode
| AT91_SMC_TDF_(config->tdf_cycles)
);
}
| gpl-2.0 |
talnoah/m8_sense | arch/arm/mach-imx/mach-pca100.c | 4787 | 10294 | /*
* Copyright 2007 Robert Schwebel <r.schwebel@pengutronix.de>, Pengutronix
* Copyright (C) 2009 Sascha Hauer (kernel@pengutronix.de)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/i2c/at24.h>
#include <linux/dma-mapping.h>
#include <linux/spi/spi.h>
#include <linux/spi/eeprom.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/usb/otg.h>
#include <linux/usb/ulpi.h>
#include <asm/mach/arch.h>
#include <asm/mach-types.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/iomux-mx27.h>
#include <asm/mach/time.h>
#include <mach/irqs.h>
#include <mach/ulpi.h>
#include "devices-imx27.h"
#define OTG_PHY_CS_GPIO (GPIO_PORTB + 23)
#define USBH2_PHY_CS_GPIO (GPIO_PORTB + 24)
#define SPI1_SS0 (GPIO_PORTD + 28)
#define SPI1_SS1 (GPIO_PORTD + 27)
#define SD2_CD (GPIO_PORTC + 29)
static const int pca100_pins[] __initconst = {
/* UART1 */
PE12_PF_UART1_TXD,
PE13_PF_UART1_RXD,
PE14_PF_UART1_CTS,
PE15_PF_UART1_RTS,
/* SDHC */
PB4_PF_SD2_D0,
PB5_PF_SD2_D1,
PB6_PF_SD2_D2,
PB7_PF_SD2_D3,
PB8_PF_SD2_CMD,
PB9_PF_SD2_CLK,
SD2_CD | GPIO_GPIO | GPIO_IN,
/* FEC */
PD0_AIN_FEC_TXD0,
PD1_AIN_FEC_TXD1,
PD2_AIN_FEC_TXD2,
PD3_AIN_FEC_TXD3,
PD4_AOUT_FEC_RX_ER,
PD5_AOUT_FEC_RXD1,
PD6_AOUT_FEC_RXD2,
PD7_AOUT_FEC_RXD3,
PD8_AF_FEC_MDIO,
PD9_AIN_FEC_MDC,
PD10_AOUT_FEC_CRS,
PD11_AOUT_FEC_TX_CLK,
PD12_AOUT_FEC_RXD0,
PD13_AOUT_FEC_RX_DV,
PD14_AOUT_FEC_RX_CLK,
PD15_AOUT_FEC_COL,
PD16_AIN_FEC_TX_ER,
PF23_AIN_FEC_TX_EN,
/* SSI1 */
PC20_PF_SSI1_FS,
PC21_PF_SSI1_RXD,
PC22_PF_SSI1_TXD,
PC23_PF_SSI1_CLK,
/* onboard I2C */
PC5_PF_I2C2_SDA,
PC6_PF_I2C2_SCL,
/* external I2C */
PD17_PF_I2C_DATA,
PD18_PF_I2C_CLK,
/* SPI1 */
PD25_PF_CSPI1_RDY,
PD29_PF_CSPI1_SCLK,
PD30_PF_CSPI1_MISO,
PD31_PF_CSPI1_MOSI,
/* OTG */
OTG_PHY_CS_GPIO | GPIO_GPIO | GPIO_OUT,
PC7_PF_USBOTG_DATA5,
PC8_PF_USBOTG_DATA6,
PC9_PF_USBOTG_DATA0,
PC10_PF_USBOTG_DATA2,
PC11_PF_USBOTG_DATA1,
PC12_PF_USBOTG_DATA4,
PC13_PF_USBOTG_DATA3,
PE0_PF_USBOTG_NXT,
PE1_PF_USBOTG_STP,
PE2_PF_USBOTG_DIR,
PE24_PF_USBOTG_CLK,
PE25_PF_USBOTG_DATA7,
/* USBH2 */
USBH2_PHY_CS_GPIO | GPIO_GPIO | GPIO_OUT,
PA0_PF_USBH2_CLK,
PA1_PF_USBH2_DIR,
PA2_PF_USBH2_DATA7,
PA3_PF_USBH2_NXT,
PA4_PF_USBH2_STP,
PD19_AF_USBH2_DATA4,
PD20_AF_USBH2_DATA3,
PD21_AF_USBH2_DATA6,
PD22_AF_USBH2_DATA0,
PD23_AF_USBH2_DATA2,
PD24_AF_USBH2_DATA1,
PD26_AF_USBH2_DATA5,
/* display */
PA5_PF_LSCLK,
PA6_PF_LD0,
PA7_PF_LD1,
PA8_PF_LD2,
PA9_PF_LD3,
PA10_PF_LD4,
PA11_PF_LD5,
PA12_PF_LD6,
PA13_PF_LD7,
PA14_PF_LD8,
PA15_PF_LD9,
PA16_PF_LD10,
PA17_PF_LD11,
PA18_PF_LD12,
PA19_PF_LD13,
PA20_PF_LD14,
PA21_PF_LD15,
PA22_PF_LD16,
PA23_PF_LD17,
PA26_PF_PS,
PA28_PF_HSYNC,
PA29_PF_VSYNC,
PA31_PF_OE_ACD,
/* free GPIO */
GPIO_PORTC | 31 | GPIO_GPIO | GPIO_IN, /* GPIO0_IRQ */
GPIO_PORTC | 25 | GPIO_GPIO | GPIO_IN, /* GPIO1_IRQ */
GPIO_PORTE | 5 | GPIO_GPIO | GPIO_IN, /* GPIO2_IRQ */
};
static const struct imxuart_platform_data uart_pdata __initconst = {
.flags = IMXUART_HAVE_RTSCTS,
};
static const struct mxc_nand_platform_data
pca100_nand_board_info __initconst = {
.width = 1,
.hw_ecc = 1,
};
static const struct imxi2c_platform_data pca100_i2c1_data __initconst = {
.bitrate = 100000,
};
static struct at24_platform_data board_eeprom = {
.byte_len = 4096,
.page_size = 32,
.flags = AT24_FLAG_ADDR16,
};
static struct i2c_board_info pca100_i2c_devices[] = {
{
I2C_BOARD_INFO("at24", 0x52), /* E0=0, E1=1, E2=0 */
.platform_data = &board_eeprom,
}, {
I2C_BOARD_INFO("pcf8563", 0x51),
}, {
I2C_BOARD_INFO("lm75", 0x4a),
}
};
static struct spi_eeprom at25320 = {
.name = "at25320an",
.byte_len = 4096,
.page_size = 32,
.flags = EE_ADDR2,
};
static struct spi_board_info pca100_spi_board_info[] __initdata = {
{
.modalias = "at25",
.max_speed_hz = 30000,
.bus_num = 0,
.chip_select = 1,
.platform_data = &at25320,
},
};
static int pca100_spi_cs[] = {SPI1_SS0, SPI1_SS1};
static const struct spi_imx_master pca100_spi0_data __initconst = {
.chipselect = pca100_spi_cs,
.num_chipselect = ARRAY_SIZE(pca100_spi_cs),
};
static void pca100_ac97_warm_reset(struct snd_ac97 *ac97)
{
mxc_gpio_mode(GPIO_PORTC | 20 | GPIO_GPIO | GPIO_OUT);
gpio_set_value(GPIO_PORTC + 20, 1);
udelay(2);
gpio_set_value(GPIO_PORTC + 20, 0);
mxc_gpio_mode(PC20_PF_SSI1_FS);
msleep(2);
}
static void pca100_ac97_cold_reset(struct snd_ac97 *ac97)
{
mxc_gpio_mode(GPIO_PORTC | 20 | GPIO_GPIO | GPIO_OUT); /* FS */
gpio_set_value(GPIO_PORTC + 20, 0);
mxc_gpio_mode(GPIO_PORTC | 22 | GPIO_GPIO | GPIO_OUT); /* TX */
gpio_set_value(GPIO_PORTC + 22, 0);
mxc_gpio_mode(GPIO_PORTC | 28 | GPIO_GPIO | GPIO_OUT); /* reset */
gpio_set_value(GPIO_PORTC + 28, 0);
udelay(10);
gpio_set_value(GPIO_PORTC + 28, 1);
mxc_gpio_mode(PC20_PF_SSI1_FS);
mxc_gpio_mode(PC22_PF_SSI1_TXD);
msleep(2);
}
static const struct imx_ssi_platform_data pca100_ssi_pdata __initconst = {
.ac97_reset = pca100_ac97_cold_reset,
.ac97_warm_reset = pca100_ac97_warm_reset,
.flags = IMX_SSI_USE_AC97,
};
static int pca100_sdhc2_init(struct device *dev, irq_handler_t detect_irq,
void *data)
{
int ret;
ret = request_irq(IRQ_GPIOC(29), detect_irq,
IRQF_DISABLED | IRQF_TRIGGER_FALLING,
"imx-mmc-detect", data);
if (ret)
printk(KERN_ERR
"pca100: Failed to reuest irq for sd/mmc detection\n");
return ret;
}
static void pca100_sdhc2_exit(struct device *dev, void *data)
{
free_irq(IRQ_GPIOC(29), data);
}
static const struct imxmmc_platform_data sdhc_pdata __initconst = {
.init = pca100_sdhc2_init,
.exit = pca100_sdhc2_exit,
};
static int otg_phy_init(struct platform_device *pdev)
{
gpio_set_value(OTG_PHY_CS_GPIO, 0);
mdelay(10);
return mx27_initialize_usb_hw(pdev->id, MXC_EHCI_INTERFACE_DIFF_UNI);
}
static struct mxc_usbh_platform_data otg_pdata __initdata = {
.init = otg_phy_init,
.portsc = MXC_EHCI_MODE_ULPI,
};
static int usbh2_phy_init(struct platform_device *pdev)
{
gpio_set_value(USBH2_PHY_CS_GPIO, 0);
mdelay(10);
return mx27_initialize_usb_hw(pdev->id, MXC_EHCI_INTERFACE_DIFF_UNI);
}
static struct mxc_usbh_platform_data usbh2_pdata __initdata = {
.init = usbh2_phy_init,
.portsc = MXC_EHCI_MODE_ULPI,
};
static const struct fsl_usb2_platform_data otg_device_pdata __initconst = {
.operating_mode = FSL_USB2_DR_DEVICE,
.phy_mode = FSL_USB2_PHY_ULPI,
};
static int otg_mode_host;
static int __init pca100_otg_mode(char *options)
{
if (!strcmp(options, "host"))
otg_mode_host = 1;
else if (!strcmp(options, "device"))
otg_mode_host = 0;
else
pr_info("otg_mode neither \"host\" nor \"device\". "
"Defaulting to device\n");
return 0;
}
__setup("otg_mode=", pca100_otg_mode);
/* framebuffer info */
static struct imx_fb_videomode pca100_fb_modes[] = {
{
.mode = {
.name = "EMERGING-ETV570G0DHU",
.refresh = 60,
.xres = 640,
.yres = 480,
.pixclock = 39722, /* in ps (25.175 MHz) */
.hsync_len = 30,
.left_margin = 114,
.right_margin = 16,
.vsync_len = 3,
.upper_margin = 32,
.lower_margin = 0,
},
/*
* TFT
* Pixel pol active high
* HSYNC active low
* VSYNC active low
* use HSYNC for ACD count
* line clock disable while idle
* always enable line clock even if no data
*/
.pcr = 0xf0c08080,
.bpp = 16,
},
};
static const struct imx_fb_platform_data pca100_fb_data __initconst = {
.mode = pca100_fb_modes,
.num_modes = ARRAY_SIZE(pca100_fb_modes),
.pwmr = 0x00A903FF,
.lscr1 = 0x00120300,
.dmacr = 0x00020010,
};
static void __init pca100_init(void)
{
int ret;
imx27_soc_init();
ret = mxc_gpio_setup_multiple_pins(pca100_pins,
ARRAY_SIZE(pca100_pins), "PCA100");
if (ret)
printk(KERN_ERR "pca100: Failed to setup pins (%d)\n", ret);
imx27_add_imx_ssi(0, &pca100_ssi_pdata);
imx27_add_imx_uart0(&uart_pdata);
imx27_add_mxc_mmc(1, &sdhc_pdata);
imx27_add_mxc_nand(&pca100_nand_board_info);
/* only the i2c master 1 is used on this CPU card */
i2c_register_board_info(1, pca100_i2c_devices,
ARRAY_SIZE(pca100_i2c_devices));
imx27_add_imx_i2c(1, &pca100_i2c1_data);
mxc_gpio_mode(GPIO_PORTD | 28 | GPIO_GPIO | GPIO_IN);
mxc_gpio_mode(GPIO_PORTD | 27 | GPIO_GPIO | GPIO_IN);
spi_register_board_info(pca100_spi_board_info,
ARRAY_SIZE(pca100_spi_board_info));
imx27_add_spi_imx0(&pca100_spi0_data);
gpio_request(OTG_PHY_CS_GPIO, "usb-otg-cs");
gpio_direction_output(OTG_PHY_CS_GPIO, 1);
gpio_request(USBH2_PHY_CS_GPIO, "usb-host2-cs");
gpio_direction_output(USBH2_PHY_CS_GPIO, 1);
if (otg_mode_host) {
otg_pdata.otg = imx_otg_ulpi_create(ULPI_OTG_DRVVBUS |
ULPI_OTG_DRVVBUS_EXT);
if (otg_pdata.otg)
imx27_add_mxc_ehci_otg(&otg_pdata);
} else {
gpio_set_value(OTG_PHY_CS_GPIO, 0);
imx27_add_fsl_usb2_udc(&otg_device_pdata);
}
usbh2_pdata.otg = otg_ulpi_create(&mxc_ulpi_access_ops,
ULPI_OTG_DRVVBUS | ULPI_OTG_DRVVBUS_EXT);
if (usbh2_pdata.otg)
imx27_add_mxc_ehci_hs(2, &usbh2_pdata);
imx27_add_imx_fb(&pca100_fb_data);
imx27_add_fec(NULL);
imx27_add_imx2_wdt(NULL);
imx27_add_mxc_w1(NULL);
}
static void __init pca100_timer_init(void)
{
mx27_clocks_init(26000000);
}
static struct sys_timer pca100_timer = {
.init = pca100_timer_init,
};
MACHINE_START(PCA100, "phyCARD-i.MX27")
.atag_offset = 0x100,
.map_io = mx27_map_io,
.init_early = imx27_init_early,
.init_irq = mx27_init_irq,
.handle_irq = imx27_handle_irq,
.init_machine = pca100_init,
.timer = &pca100_timer,
.restart = mxc_restart,
MACHINE_END
| gpl-2.0 |
SM-G920P/S6-MM | arch/powerpc/platforms/52xx/mpc52xx_pci.c | 8115 | 12199 | /*
* PCI code for the Freescale MPC52xx embedded CPU.
*
* Copyright (C) 2006 Secret Lab Technologies Ltd.
* Grant Likely <grant.likely@secretlab.ca>
* Copyright (C) 2004 Sylvain Munaut <tnt@246tNt.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.
*/
#undef DEBUG
#include <asm/pci.h>
#include <asm/mpc52xx.h>
#include <asm/delay.h>
#include <asm/machdep.h>
#include <linux/kernel.h>
/* ======================================================================== */
/* Structures mapping & Defines for PCI Unit */
/* ======================================================================== */
#define MPC52xx_PCI_GSCR_BM 0x40000000
#define MPC52xx_PCI_GSCR_PE 0x20000000
#define MPC52xx_PCI_GSCR_SE 0x10000000
#define MPC52xx_PCI_GSCR_XLB2PCI_MASK 0x07000000
#define MPC52xx_PCI_GSCR_XLB2PCI_SHIFT 24
#define MPC52xx_PCI_GSCR_IPG2PCI_MASK 0x00070000
#define MPC52xx_PCI_GSCR_IPG2PCI_SHIFT 16
#define MPC52xx_PCI_GSCR_BME 0x00004000
#define MPC52xx_PCI_GSCR_PEE 0x00002000
#define MPC52xx_PCI_GSCR_SEE 0x00001000
#define MPC52xx_PCI_GSCR_PR 0x00000001
#define MPC52xx_PCI_IWBTAR_TRANSLATION(proc_ad,pci_ad,size) \
( ( (proc_ad) & 0xff000000 ) | \
( (((size) - 1) >> 8) & 0x00ff0000 ) | \
( ((pci_ad) >> 16) & 0x0000ff00 ) )
#define MPC52xx_PCI_IWCR_PACK(win0,win1,win2) (((win0) << 24) | \
((win1) << 16) | \
((win2) << 8))
#define MPC52xx_PCI_IWCR_DISABLE 0x0
#define MPC52xx_PCI_IWCR_ENABLE 0x1
#define MPC52xx_PCI_IWCR_READ 0x0
#define MPC52xx_PCI_IWCR_READ_LINE 0x2
#define MPC52xx_PCI_IWCR_READ_MULTI 0x4
#define MPC52xx_PCI_IWCR_MEM 0x0
#define MPC52xx_PCI_IWCR_IO 0x8
#define MPC52xx_PCI_TCR_P 0x01000000
#define MPC52xx_PCI_TCR_LD 0x00010000
#define MPC52xx_PCI_TCR_WCT8 0x00000008
#define MPC52xx_PCI_TBATR_DISABLE 0x0
#define MPC52xx_PCI_TBATR_ENABLE 0x1
struct mpc52xx_pci {
u32 idr; /* PCI + 0x00 */
u32 scr; /* PCI + 0x04 */
u32 ccrir; /* PCI + 0x08 */
u32 cr1; /* PCI + 0x0C */
u32 bar0; /* PCI + 0x10 */
u32 bar1; /* PCI + 0x14 */
u8 reserved1[16]; /* PCI + 0x18 */
u32 ccpr; /* PCI + 0x28 */
u32 sid; /* PCI + 0x2C */
u32 erbar; /* PCI + 0x30 */
u32 cpr; /* PCI + 0x34 */
u8 reserved2[4]; /* PCI + 0x38 */
u32 cr2; /* PCI + 0x3C */
u8 reserved3[32]; /* PCI + 0x40 */
u32 gscr; /* PCI + 0x60 */
u32 tbatr0; /* PCI + 0x64 */
u32 tbatr1; /* PCI + 0x68 */
u32 tcr; /* PCI + 0x6C */
u32 iw0btar; /* PCI + 0x70 */
u32 iw1btar; /* PCI + 0x74 */
u32 iw2btar; /* PCI + 0x78 */
u8 reserved4[4]; /* PCI + 0x7C */
u32 iwcr; /* PCI + 0x80 */
u32 icr; /* PCI + 0x84 */
u32 isr; /* PCI + 0x88 */
u32 arb; /* PCI + 0x8C */
u8 reserved5[104]; /* PCI + 0x90 */
u32 car; /* PCI + 0xF8 */
u8 reserved6[4]; /* PCI + 0xFC */
};
/* MPC5200 device tree match tables */
const struct of_device_id mpc52xx_pci_ids[] __initconst = {
{ .type = "pci", .compatible = "fsl,mpc5200-pci", },
{ .type = "pci", .compatible = "mpc5200-pci", },
{}
};
/* ======================================================================== */
/* PCI configuration access */
/* ======================================================================== */
static int
mpc52xx_pci_read_config(struct pci_bus *bus, unsigned int devfn,
int offset, int len, u32 *val)
{
struct pci_controller *hose = pci_bus_to_host(bus);
u32 value;
if (ppc_md.pci_exclude_device)
if (ppc_md.pci_exclude_device(hose, bus->number, devfn))
return PCIBIOS_DEVICE_NOT_FOUND;
out_be32(hose->cfg_addr,
(1 << 31) |
(bus->number << 16) |
(devfn << 8) |
(offset & 0xfc));
mb();
#if defined(CONFIG_PPC_MPC5200_BUGFIX)
if (bus->number) {
/* workaround for the bug 435 of the MPC5200 (L25R);
* Don't do 32 bits config access during type-1 cycles */
switch (len) {
case 1:
value = in_8(((u8 __iomem *)hose->cfg_data) +
(offset & 3));
break;
case 2:
value = in_le16(((u16 __iomem *)hose->cfg_data) +
((offset>>1) & 1));
break;
default:
value = in_le16((u16 __iomem *)hose->cfg_data) |
(in_le16(((u16 __iomem *)hose->cfg_data) + 1) << 16);
break;
}
}
else
#endif
{
value = in_le32(hose->cfg_data);
if (len != 4) {
value >>= ((offset & 0x3) << 3);
value &= 0xffffffff >> (32 - (len << 3));
}
}
*val = value;
out_be32(hose->cfg_addr, 0);
mb();
return PCIBIOS_SUCCESSFUL;
}
static int
mpc52xx_pci_write_config(struct pci_bus *bus, unsigned int devfn,
int offset, int len, u32 val)
{
struct pci_controller *hose = pci_bus_to_host(bus);
u32 value, mask;
if (ppc_md.pci_exclude_device)
if (ppc_md.pci_exclude_device(hose, bus->number, devfn))
return PCIBIOS_DEVICE_NOT_FOUND;
out_be32(hose->cfg_addr,
(1 << 31) |
(bus->number << 16) |
(devfn << 8) |
(offset & 0xfc));
mb();
#if defined(CONFIG_PPC_MPC5200_BUGFIX)
if (bus->number) {
/* workaround for the bug 435 of the MPC5200 (L25R);
* Don't do 32 bits config access during type-1 cycles */
switch (len) {
case 1:
out_8(((u8 __iomem *)hose->cfg_data) +
(offset & 3), val);
break;
case 2:
out_le16(((u16 __iomem *)hose->cfg_data) +
((offset>>1) & 1), val);
break;
default:
out_le16((u16 __iomem *)hose->cfg_data,
(u16)val);
out_le16(((u16 __iomem *)hose->cfg_data) + 1,
(u16)(val>>16));
break;
}
}
else
#endif
{
if (len != 4) {
value = in_le32(hose->cfg_data);
offset = (offset & 0x3) << 3;
mask = (0xffffffff >> (32 - (len << 3)));
mask <<= offset;
value &= ~mask;
val = value | ((val << offset) & mask);
}
out_le32(hose->cfg_data, val);
}
mb();
out_be32(hose->cfg_addr, 0);
mb();
return PCIBIOS_SUCCESSFUL;
}
static struct pci_ops mpc52xx_pci_ops = {
.read = mpc52xx_pci_read_config,
.write = mpc52xx_pci_write_config
};
/* ======================================================================== */
/* PCI setup */
/* ======================================================================== */
static void __init
mpc52xx_pci_setup(struct pci_controller *hose,
struct mpc52xx_pci __iomem *pci_regs, phys_addr_t pci_phys)
{
struct resource *res;
u32 tmp;
int iwcr0 = 0, iwcr1 = 0, iwcr2 = 0;
pr_debug("mpc52xx_pci_setup(hose=%p, pci_regs=%p)\n", hose, pci_regs);
/* pci_process_bridge_OF_ranges() found all our addresses for us;
* now store them in the right places */
hose->cfg_addr = &pci_regs->car;
hose->cfg_data = hose->io_base_virt;
/* Control regs */
tmp = in_be32(&pci_regs->scr);
tmp |= PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY;
out_be32(&pci_regs->scr, tmp);
/* Memory windows */
res = &hose->mem_resources[0];
if (res->flags) {
pr_debug("mem_resource[0] = "
"{.start=%llx, .end=%llx, .flags=%llx}\n",
(unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned long long)res->flags);
out_be32(&pci_regs->iw0btar,
MPC52xx_PCI_IWBTAR_TRANSLATION(res->start, res->start,
resource_size(res)));
iwcr0 = MPC52xx_PCI_IWCR_ENABLE | MPC52xx_PCI_IWCR_MEM;
if (res->flags & IORESOURCE_PREFETCH)
iwcr0 |= MPC52xx_PCI_IWCR_READ_MULTI;
else
iwcr0 |= MPC52xx_PCI_IWCR_READ;
}
res = &hose->mem_resources[1];
if (res->flags) {
pr_debug("mem_resource[1] = {.start=%x, .end=%x, .flags=%lx}\n",
res->start, res->end, res->flags);
out_be32(&pci_regs->iw1btar,
MPC52xx_PCI_IWBTAR_TRANSLATION(res->start, res->start,
resource_size(res)));
iwcr1 = MPC52xx_PCI_IWCR_ENABLE | MPC52xx_PCI_IWCR_MEM;
if (res->flags & IORESOURCE_PREFETCH)
iwcr1 |= MPC52xx_PCI_IWCR_READ_MULTI;
else
iwcr1 |= MPC52xx_PCI_IWCR_READ;
}
/* IO resources */
res = &hose->io_resource;
if (!res) {
printk(KERN_ERR "%s: Didn't find IO resources\n", __FILE__);
return;
}
pr_debug(".io_resource={.start=%llx,.end=%llx,.flags=%llx} "
".io_base_phys=0x%p\n",
(unsigned long long)res->start,
(unsigned long long)res->end,
(unsigned long long)res->flags, (void*)hose->io_base_phys);
out_be32(&pci_regs->iw2btar,
MPC52xx_PCI_IWBTAR_TRANSLATION(hose->io_base_phys,
res->start,
resource_size(res)));
iwcr2 = MPC52xx_PCI_IWCR_ENABLE | MPC52xx_PCI_IWCR_IO;
/* Set all the IWCR fields at once; they're in the same reg */
out_be32(&pci_regs->iwcr, MPC52xx_PCI_IWCR_PACK(iwcr0, iwcr1, iwcr2));
/* Map IMMR onto PCI bus */
pci_phys &= 0xfffc0000; /* bar0 has only 14 significant bits */
out_be32(&pci_regs->tbatr0, MPC52xx_PCI_TBATR_ENABLE | pci_phys);
out_be32(&pci_regs->bar0, PCI_BASE_ADDRESS_MEM_PREFETCH | pci_phys);
/* Map memory onto PCI bus */
out_be32(&pci_regs->tbatr1, MPC52xx_PCI_TBATR_ENABLE);
out_be32(&pci_regs->bar1, PCI_BASE_ADDRESS_MEM_PREFETCH);
out_be32(&pci_regs->tcr, MPC52xx_PCI_TCR_LD | MPC52xx_PCI_TCR_WCT8);
tmp = in_be32(&pci_regs->gscr);
#if 0
/* Reset the exteral bus ( internal PCI controller is NOT resetted ) */
/* Not necessary and can be a bad thing if for example the bootloader
is displaying a splash screen or ... Just left here for
documentation purpose if anyone need it */
out_be32(&pci_regs->gscr, tmp | MPC52xx_PCI_GSCR_PR);
udelay(50);
#endif
/* Make sure the PCI bridge is out of reset */
out_be32(&pci_regs->gscr, tmp & ~MPC52xx_PCI_GSCR_PR);
}
static void
mpc52xx_pci_fixup_resources(struct pci_dev *dev)
{
int i;
pr_debug("mpc52xx_pci_fixup_resources() %.4x:%.4x\n",
dev->vendor, dev->device);
/* We don't rely on boot loader for PCI and resets all
devices */
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
struct resource *res = &dev->resource[i];
if (res->end > res->start) { /* Only valid resources */
res->end -= res->start;
res->start = 0;
res->flags |= IORESOURCE_UNSET;
}
}
/* The PCI Host bridge of MPC52xx has a prefetch memory resource
fixed to 1Gb. Doesn't fit in the resource system so we remove it */
if ( (dev->vendor == PCI_VENDOR_ID_MOTOROLA) &&
( dev->device == PCI_DEVICE_ID_MOTOROLA_MPC5200
|| dev->device == PCI_DEVICE_ID_MOTOROLA_MPC5200B) ) {
struct resource *res = &dev->resource[1];
res->start = res->end = res->flags = 0;
}
}
int __init
mpc52xx_add_bridge(struct device_node *node)
{
int len;
struct mpc52xx_pci __iomem *pci_regs;
struct pci_controller *hose;
const int *bus_range;
struct resource rsrc;
pr_debug("Adding MPC52xx PCI host bridge %s\n", node->full_name);
pci_add_flags(PCI_REASSIGN_ALL_BUS);
if (of_address_to_resource(node, 0, &rsrc) != 0) {
printk(KERN_ERR "Can't get %s resources\n", node->full_name);
return -EINVAL;
}
bus_range = of_get_property(node, "bus-range", &len);
if (bus_range == NULL || len < 2 * sizeof(int)) {
printk(KERN_WARNING "Can't get %s bus-range, assume bus 0\n",
node->full_name);
bus_range = NULL;
}
/* There are some PCI quirks on the 52xx, register the hook to
* fix them. */
ppc_md.pcibios_fixup_resources = mpc52xx_pci_fixup_resources;
/* Alloc and initialize the pci controller. Values in the device
* tree are needed to configure the 52xx PCI controller. Rather
* than parse the tree here, let pci_process_bridge_OF_ranges()
* do it for us and extract the values after the fact */
hose = pcibios_alloc_controller(node);
if (!hose)
return -ENOMEM;
hose->first_busno = bus_range ? bus_range[0] : 0;
hose->last_busno = bus_range ? bus_range[1] : 0xff;
hose->ops = &mpc52xx_pci_ops;
pci_regs = ioremap(rsrc.start, resource_size(&rsrc));
if (!pci_regs)
return -ENOMEM;
pci_process_bridge_OF_ranges(hose, node, 1);
/* Finish setting up PCI using values obtained by
* pci_proces_bridge_OF_ranges */
mpc52xx_pci_setup(hose, pci_regs, rsrc.start);
return 0;
}
void __init mpc52xx_setup_pci(void)
{
struct device_node *pci;
pci = of_find_matching_node(NULL, mpc52xx_pci_ids);
if (!pci)
return;
mpc52xx_add_bridge(pci);
of_node_put(pci);
}
| gpl-2.0 |
TMartinPPC/maru_kernel_flo | drivers/scsi/aic94xx/aic94xx_hwi.c | 9395 | 38899 | /*
* Aic94xx SAS/SATA driver hardware interface.
*
* Copyright (C) 2005 Adaptec, Inc. All rights reserved.
* Copyright (C) 2005 Luben Tuikov <luben_tuikov@adaptec.com>
*
* This file is licensed under GPLv2.
*
* This file is part of the aic94xx driver.
*
* The aic94xx driver is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; version 2 of the
* License.
*
* The aic94xx driver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the aic94xx driver; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/firmware.h>
#include "aic94xx.h"
#include "aic94xx_reg.h"
#include "aic94xx_hwi.h"
#include "aic94xx_seq.h"
#include "aic94xx_dump.h"
u32 MBAR0_SWB_SIZE;
/* ---------- Initialization ---------- */
static int asd_get_user_sas_addr(struct asd_ha_struct *asd_ha)
{
/* adapter came with a sas address */
if (asd_ha->hw_prof.sas_addr[0])
return 0;
return sas_request_addr(asd_ha->sas_ha.core.shost,
asd_ha->hw_prof.sas_addr);
}
static void asd_propagate_sas_addr(struct asd_ha_struct *asd_ha)
{
int i;
for (i = 0; i < ASD_MAX_PHYS; i++) {
if (asd_ha->hw_prof.phy_desc[i].sas_addr[0] == 0)
continue;
/* Set a phy's address only if it has none.
*/
ASD_DPRINTK("setting phy%d addr to %llx\n", i,
SAS_ADDR(asd_ha->hw_prof.sas_addr));
memcpy(asd_ha->hw_prof.phy_desc[i].sas_addr,
asd_ha->hw_prof.sas_addr, SAS_ADDR_SIZE);
}
}
/* ---------- PHY initialization ---------- */
static void asd_init_phy_identify(struct asd_phy *phy)
{
phy->identify_frame = phy->id_frm_tok->vaddr;
memset(phy->identify_frame, 0, sizeof(*phy->identify_frame));
phy->identify_frame->dev_type = SAS_END_DEV;
if (phy->sas_phy.role & PHY_ROLE_INITIATOR)
phy->identify_frame->initiator_bits = phy->sas_phy.iproto;
if (phy->sas_phy.role & PHY_ROLE_TARGET)
phy->identify_frame->target_bits = phy->sas_phy.tproto;
memcpy(phy->identify_frame->sas_addr, phy->phy_desc->sas_addr,
SAS_ADDR_SIZE);
phy->identify_frame->phy_id = phy->sas_phy.id;
}
static int asd_init_phy(struct asd_phy *phy)
{
struct asd_ha_struct *asd_ha = phy->sas_phy.ha->lldd_ha;
struct asd_sas_phy *sas_phy = &phy->sas_phy;
sas_phy->enabled = 1;
sas_phy->class = SAS;
sas_phy->iproto = SAS_PROTOCOL_ALL;
sas_phy->tproto = 0;
sas_phy->type = PHY_TYPE_PHYSICAL;
sas_phy->role = PHY_ROLE_INITIATOR;
sas_phy->oob_mode = OOB_NOT_CONNECTED;
sas_phy->linkrate = SAS_LINK_RATE_UNKNOWN;
phy->id_frm_tok = asd_alloc_coherent(asd_ha,
sizeof(*phy->identify_frame),
GFP_KERNEL);
if (!phy->id_frm_tok) {
asd_printk("no mem for IDENTIFY for phy%d\n", sas_phy->id);
return -ENOMEM;
} else
asd_init_phy_identify(phy);
memset(phy->frame_rcvd, 0, sizeof(phy->frame_rcvd));
return 0;
}
static void asd_init_ports(struct asd_ha_struct *asd_ha)
{
int i;
spin_lock_init(&asd_ha->asd_ports_lock);
for (i = 0; i < ASD_MAX_PHYS; i++) {
struct asd_port *asd_port = &asd_ha->asd_ports[i];
memset(asd_port->sas_addr, 0, SAS_ADDR_SIZE);
memset(asd_port->attached_sas_addr, 0, SAS_ADDR_SIZE);
asd_port->phy_mask = 0;
asd_port->num_phys = 0;
}
}
static int asd_init_phys(struct asd_ha_struct *asd_ha)
{
u8 i;
u8 phy_mask = asd_ha->hw_prof.enabled_phys;
for (i = 0; i < ASD_MAX_PHYS; i++) {
struct asd_phy *phy = &asd_ha->phys[i];
phy->phy_desc = &asd_ha->hw_prof.phy_desc[i];
phy->asd_port = NULL;
phy->sas_phy.enabled = 0;
phy->sas_phy.id = i;
phy->sas_phy.sas_addr = &phy->phy_desc->sas_addr[0];
phy->sas_phy.frame_rcvd = &phy->frame_rcvd[0];
phy->sas_phy.ha = &asd_ha->sas_ha;
phy->sas_phy.lldd_phy = phy;
}
/* Now enable and initialize only the enabled phys. */
for_each_phy(phy_mask, phy_mask, i) {
int err = asd_init_phy(&asd_ha->phys[i]);
if (err)
return err;
}
return 0;
}
/* ---------- Sliding windows ---------- */
static int asd_init_sw(struct asd_ha_struct *asd_ha)
{
struct pci_dev *pcidev = asd_ha->pcidev;
int err;
u32 v;
/* Unlock MBARs */
err = pci_read_config_dword(pcidev, PCI_CONF_MBAR_KEY, &v);
if (err) {
asd_printk("couldn't access conf. space of %s\n",
pci_name(pcidev));
goto Err;
}
if (v)
err = pci_write_config_dword(pcidev, PCI_CONF_MBAR_KEY, v);
if (err) {
asd_printk("couldn't write to MBAR_KEY of %s\n",
pci_name(pcidev));
goto Err;
}
/* Set sliding windows A, B and C to point to proper internal
* memory regions.
*/
pci_write_config_dword(pcidev, PCI_CONF_MBAR0_SWA, REG_BASE_ADDR);
pci_write_config_dword(pcidev, PCI_CONF_MBAR0_SWB,
REG_BASE_ADDR_CSEQCIO);
pci_write_config_dword(pcidev, PCI_CONF_MBAR0_SWC, REG_BASE_ADDR_EXSI);
asd_ha->io_handle[0].swa_base = REG_BASE_ADDR;
asd_ha->io_handle[0].swb_base = REG_BASE_ADDR_CSEQCIO;
asd_ha->io_handle[0].swc_base = REG_BASE_ADDR_EXSI;
MBAR0_SWB_SIZE = asd_ha->io_handle[0].len - 0x80;
if (!asd_ha->iospace) {
/* MBAR1 will point to OCM (On Chip Memory) */
pci_write_config_dword(pcidev, PCI_CONF_MBAR1, OCM_BASE_ADDR);
asd_ha->io_handle[1].swa_base = OCM_BASE_ADDR;
}
spin_lock_init(&asd_ha->iolock);
Err:
return err;
}
/* ---------- SCB initialization ---------- */
/**
* asd_init_scbs - manually allocate the first SCB.
* @asd_ha: pointer to host adapter structure
*
* This allocates the very first SCB which would be sent to the
* sequencer for execution. Its bus address is written to
* CSEQ_Q_NEW_POINTER, mode page 2, mode 8. Since the bus address of
* the _next_ scb to be DMA-ed to the host adapter is read from the last
* SCB DMA-ed to the host adapter, we have to always stay one step
* ahead of the sequencer and keep one SCB already allocated.
*/
static int asd_init_scbs(struct asd_ha_struct *asd_ha)
{
struct asd_seq_data *seq = &asd_ha->seq;
int bitmap_bytes;
/* allocate the index array and bitmap */
asd_ha->seq.tc_index_bitmap_bits = asd_ha->hw_prof.max_scbs;
asd_ha->seq.tc_index_array = kzalloc(asd_ha->seq.tc_index_bitmap_bits*
sizeof(void *), GFP_KERNEL);
if (!asd_ha->seq.tc_index_array)
return -ENOMEM;
bitmap_bytes = (asd_ha->seq.tc_index_bitmap_bits+7)/8;
bitmap_bytes = BITS_TO_LONGS(bitmap_bytes*8)*sizeof(unsigned long);
asd_ha->seq.tc_index_bitmap = kzalloc(bitmap_bytes, GFP_KERNEL);
if (!asd_ha->seq.tc_index_bitmap)
return -ENOMEM;
spin_lock_init(&seq->tc_index_lock);
seq->next_scb.size = sizeof(struct scb);
seq->next_scb.vaddr = dma_pool_alloc(asd_ha->scb_pool, GFP_KERNEL,
&seq->next_scb.dma_handle);
if (!seq->next_scb.vaddr) {
kfree(asd_ha->seq.tc_index_bitmap);
kfree(asd_ha->seq.tc_index_array);
asd_ha->seq.tc_index_bitmap = NULL;
asd_ha->seq.tc_index_array = NULL;
return -ENOMEM;
}
seq->pending = 0;
spin_lock_init(&seq->pend_q_lock);
INIT_LIST_HEAD(&seq->pend_q);
return 0;
}
static void asd_get_max_scb_ddb(struct asd_ha_struct *asd_ha)
{
asd_ha->hw_prof.max_scbs = asd_get_cmdctx_size(asd_ha)/ASD_SCB_SIZE;
asd_ha->hw_prof.max_ddbs = asd_get_devctx_size(asd_ha)/ASD_DDB_SIZE;
ASD_DPRINTK("max_scbs:%d, max_ddbs:%d\n",
asd_ha->hw_prof.max_scbs,
asd_ha->hw_prof.max_ddbs);
}
/* ---------- Done List initialization ---------- */
static void asd_dl_tasklet_handler(unsigned long);
static int asd_init_dl(struct asd_ha_struct *asd_ha)
{
asd_ha->seq.actual_dl
= asd_alloc_coherent(asd_ha,
ASD_DL_SIZE * sizeof(struct done_list_struct),
GFP_KERNEL);
if (!asd_ha->seq.actual_dl)
return -ENOMEM;
asd_ha->seq.dl = asd_ha->seq.actual_dl->vaddr;
asd_ha->seq.dl_toggle = ASD_DEF_DL_TOGGLE;
asd_ha->seq.dl_next = 0;
tasklet_init(&asd_ha->seq.dl_tasklet, asd_dl_tasklet_handler,
(unsigned long) asd_ha);
return 0;
}
/* ---------- EDB and ESCB init ---------- */
static int asd_alloc_edbs(struct asd_ha_struct *asd_ha, gfp_t gfp_flags)
{
struct asd_seq_data *seq = &asd_ha->seq;
int i;
seq->edb_arr = kmalloc(seq->num_edbs*sizeof(*seq->edb_arr), gfp_flags);
if (!seq->edb_arr)
return -ENOMEM;
for (i = 0; i < seq->num_edbs; i++) {
seq->edb_arr[i] = asd_alloc_coherent(asd_ha, ASD_EDB_SIZE,
gfp_flags);
if (!seq->edb_arr[i])
goto Err_unroll;
memset(seq->edb_arr[i]->vaddr, 0, ASD_EDB_SIZE);
}
ASD_DPRINTK("num_edbs:%d\n", seq->num_edbs);
return 0;
Err_unroll:
for (i-- ; i >= 0; i--)
asd_free_coherent(asd_ha, seq->edb_arr[i]);
kfree(seq->edb_arr);
seq->edb_arr = NULL;
return -ENOMEM;
}
static int asd_alloc_escbs(struct asd_ha_struct *asd_ha,
gfp_t gfp_flags)
{
struct asd_seq_data *seq = &asd_ha->seq;
struct asd_ascb *escb;
int i, escbs;
seq->escb_arr = kmalloc(seq->num_escbs*sizeof(*seq->escb_arr),
gfp_flags);
if (!seq->escb_arr)
return -ENOMEM;
escbs = seq->num_escbs;
escb = asd_ascb_alloc_list(asd_ha, &escbs, gfp_flags);
if (!escb) {
asd_printk("couldn't allocate list of escbs\n");
goto Err;
}
seq->num_escbs -= escbs; /* subtract what was not allocated */
ASD_DPRINTK("num_escbs:%d\n", seq->num_escbs);
for (i = 0; i < seq->num_escbs; i++, escb = list_entry(escb->list.next,
struct asd_ascb,
list)) {
seq->escb_arr[i] = escb;
escb->scb->header.opcode = EMPTY_SCB;
}
return 0;
Err:
kfree(seq->escb_arr);
seq->escb_arr = NULL;
return -ENOMEM;
}
static void asd_assign_edbs2escbs(struct asd_ha_struct *asd_ha)
{
struct asd_seq_data *seq = &asd_ha->seq;
int i, k, z = 0;
for (i = 0; i < seq->num_escbs; i++) {
struct asd_ascb *ascb = seq->escb_arr[i];
struct empty_scb *escb = &ascb->scb->escb;
ascb->edb_index = z;
escb->num_valid = ASD_EDBS_PER_SCB;
for (k = 0; k < ASD_EDBS_PER_SCB; k++) {
struct sg_el *eb = &escb->eb[k];
struct asd_dma_tok *edb = seq->edb_arr[z++];
memset(eb, 0, sizeof(*eb));
eb->bus_addr = cpu_to_le64(((u64) edb->dma_handle));
eb->size = cpu_to_le32(((u32) edb->size));
}
}
}
/**
* asd_init_escbs -- allocate and initialize empty scbs
* @asd_ha: pointer to host adapter structure
*
* An empty SCB has sg_elements of ASD_EDBS_PER_SCB (7) buffers.
* They transport sense data, etc.
*/
static int asd_init_escbs(struct asd_ha_struct *asd_ha)
{
struct asd_seq_data *seq = &asd_ha->seq;
int err = 0;
/* Allocate two empty data buffers (edb) per sequencer. */
int edbs = 2*(1+asd_ha->hw_prof.num_phys);
seq->num_escbs = (edbs+ASD_EDBS_PER_SCB-1)/ASD_EDBS_PER_SCB;
seq->num_edbs = seq->num_escbs * ASD_EDBS_PER_SCB;
err = asd_alloc_edbs(asd_ha, GFP_KERNEL);
if (err) {
asd_printk("couldn't allocate edbs\n");
return err;
}
err = asd_alloc_escbs(asd_ha, GFP_KERNEL);
if (err) {
asd_printk("couldn't allocate escbs\n");
return err;
}
asd_assign_edbs2escbs(asd_ha);
/* In order to insure that normal SCBs do not overfill sequencer
* memory and leave no space for escbs (halting condition),
* we increment pending here by the number of escbs. However,
* escbs are never pending.
*/
seq->pending = seq->num_escbs;
seq->can_queue = 1 + (asd_ha->hw_prof.max_scbs - seq->pending)/2;
return 0;
}
/* ---------- HW initialization ---------- */
/**
* asd_chip_hardrst -- hard reset the chip
* @asd_ha: pointer to host adapter structure
*
* This takes 16 cycles and is synchronous to CFCLK, which runs
* at 200 MHz, so this should take at most 80 nanoseconds.
*/
int asd_chip_hardrst(struct asd_ha_struct *asd_ha)
{
int i;
int count = 100;
u32 reg;
for (i = 0 ; i < 4 ; i++) {
asd_write_reg_dword(asd_ha, COMBIST, HARDRST);
}
do {
udelay(1);
reg = asd_read_reg_dword(asd_ha, CHIMINT);
if (reg & HARDRSTDET) {
asd_write_reg_dword(asd_ha, CHIMINT,
HARDRSTDET|PORRSTDET);
return 0;
}
} while (--count > 0);
return -ENODEV;
}
/**
* asd_init_chip -- initialize the chip
* @asd_ha: pointer to host adapter structure
*
* Hard resets the chip, disables HA interrupts, downloads the sequnecer
* microcode and starts the sequencers. The caller has to explicitly
* enable HA interrupts with asd_enable_ints(asd_ha).
*/
static int asd_init_chip(struct asd_ha_struct *asd_ha)
{
int err;
err = asd_chip_hardrst(asd_ha);
if (err) {
asd_printk("couldn't hard reset %s\n",
pci_name(asd_ha->pcidev));
goto out;
}
asd_disable_ints(asd_ha);
err = asd_init_seqs(asd_ha);
if (err) {
asd_printk("couldn't init seqs for %s\n",
pci_name(asd_ha->pcidev));
goto out;
}
err = asd_start_seqs(asd_ha);
if (err) {
asd_printk("coudln't start seqs for %s\n",
pci_name(asd_ha->pcidev));
goto out;
}
out:
return err;
}
#define MAX_DEVS ((OCM_MAX_SIZE) / (ASD_DDB_SIZE))
static int max_devs = 0;
module_param_named(max_devs, max_devs, int, S_IRUGO);
MODULE_PARM_DESC(max_devs, "\n"
"\tMaximum number of SAS devices to support (not LUs).\n"
"\tDefault: 2176, Maximum: 65663.\n");
static int max_cmnds = 0;
module_param_named(max_cmnds, max_cmnds, int, S_IRUGO);
MODULE_PARM_DESC(max_cmnds, "\n"
"\tMaximum number of commands queuable.\n"
"\tDefault: 512, Maximum: 66047.\n");
static void asd_extend_devctx_ocm(struct asd_ha_struct *asd_ha)
{
unsigned long dma_addr = OCM_BASE_ADDR;
u32 d;
dma_addr -= asd_ha->hw_prof.max_ddbs * ASD_DDB_SIZE;
asd_write_reg_addr(asd_ha, DEVCTXBASE, (dma_addr_t) dma_addr);
d = asd_read_reg_dword(asd_ha, CTXDOMAIN);
d |= 4;
asd_write_reg_dword(asd_ha, CTXDOMAIN, d);
asd_ha->hw_prof.max_ddbs += MAX_DEVS;
}
static int asd_extend_devctx(struct asd_ha_struct *asd_ha)
{
dma_addr_t dma_handle;
unsigned long dma_addr;
u32 d;
int size;
asd_extend_devctx_ocm(asd_ha);
asd_ha->hw_prof.ddb_ext = NULL;
if (max_devs <= asd_ha->hw_prof.max_ddbs || max_devs > 0xFFFF) {
max_devs = asd_ha->hw_prof.max_ddbs;
return 0;
}
size = (max_devs - asd_ha->hw_prof.max_ddbs + 1) * ASD_DDB_SIZE;
asd_ha->hw_prof.ddb_ext = asd_alloc_coherent(asd_ha, size, GFP_KERNEL);
if (!asd_ha->hw_prof.ddb_ext) {
asd_printk("couldn't allocate memory for %d devices\n",
max_devs);
max_devs = asd_ha->hw_prof.max_ddbs;
return -ENOMEM;
}
dma_handle = asd_ha->hw_prof.ddb_ext->dma_handle;
dma_addr = ALIGN((unsigned long) dma_handle, ASD_DDB_SIZE);
dma_addr -= asd_ha->hw_prof.max_ddbs * ASD_DDB_SIZE;
dma_handle = (dma_addr_t) dma_addr;
asd_write_reg_addr(asd_ha, DEVCTXBASE, dma_handle);
d = asd_read_reg_dword(asd_ha, CTXDOMAIN);
d &= ~4;
asd_write_reg_dword(asd_ha, CTXDOMAIN, d);
asd_ha->hw_prof.max_ddbs = max_devs;
return 0;
}
static int asd_extend_cmdctx(struct asd_ha_struct *asd_ha)
{
dma_addr_t dma_handle;
unsigned long dma_addr;
u32 d;
int size;
asd_ha->hw_prof.scb_ext = NULL;
if (max_cmnds <= asd_ha->hw_prof.max_scbs || max_cmnds > 0xFFFF) {
max_cmnds = asd_ha->hw_prof.max_scbs;
return 0;
}
size = (max_cmnds - asd_ha->hw_prof.max_scbs + 1) * ASD_SCB_SIZE;
asd_ha->hw_prof.scb_ext = asd_alloc_coherent(asd_ha, size, GFP_KERNEL);
if (!asd_ha->hw_prof.scb_ext) {
asd_printk("couldn't allocate memory for %d commands\n",
max_cmnds);
max_cmnds = asd_ha->hw_prof.max_scbs;
return -ENOMEM;
}
dma_handle = asd_ha->hw_prof.scb_ext->dma_handle;
dma_addr = ALIGN((unsigned long) dma_handle, ASD_SCB_SIZE);
dma_addr -= asd_ha->hw_prof.max_scbs * ASD_SCB_SIZE;
dma_handle = (dma_addr_t) dma_addr;
asd_write_reg_addr(asd_ha, CMDCTXBASE, dma_handle);
d = asd_read_reg_dword(asd_ha, CTXDOMAIN);
d &= ~1;
asd_write_reg_dword(asd_ha, CTXDOMAIN, d);
asd_ha->hw_prof.max_scbs = max_cmnds;
return 0;
}
/**
* asd_init_ctxmem -- initialize context memory
* asd_ha: pointer to host adapter structure
*
* This function sets the maximum number of SCBs and
* DDBs which can be used by the sequencer. This is normally
* 512 and 128 respectively. If support for more SCBs or more DDBs
* is required then CMDCTXBASE, DEVCTXBASE and CTXDOMAIN are
* initialized here to extend context memory to point to host memory,
* thus allowing unlimited support for SCBs and DDBs -- only limited
* by host memory.
*/
static int asd_init_ctxmem(struct asd_ha_struct *asd_ha)
{
int bitmap_bytes;
asd_get_max_scb_ddb(asd_ha);
asd_extend_devctx(asd_ha);
asd_extend_cmdctx(asd_ha);
/* The kernel wants bitmaps to be unsigned long sized. */
bitmap_bytes = (asd_ha->hw_prof.max_ddbs+7)/8;
bitmap_bytes = BITS_TO_LONGS(bitmap_bytes*8)*sizeof(unsigned long);
asd_ha->hw_prof.ddb_bitmap = kzalloc(bitmap_bytes, GFP_KERNEL);
if (!asd_ha->hw_prof.ddb_bitmap)
return -ENOMEM;
spin_lock_init(&asd_ha->hw_prof.ddb_lock);
return 0;
}
int asd_init_hw(struct asd_ha_struct *asd_ha)
{
int err;
u32 v;
err = asd_init_sw(asd_ha);
if (err)
return err;
err = pci_read_config_dword(asd_ha->pcidev, PCIC_HSTPCIX_CNTRL, &v);
if (err) {
asd_printk("couldn't read PCIC_HSTPCIX_CNTRL of %s\n",
pci_name(asd_ha->pcidev));
return err;
}
pci_write_config_dword(asd_ha->pcidev, PCIC_HSTPCIX_CNTRL,
v | SC_TMR_DIS);
if (err) {
asd_printk("couldn't disable split completion timer of %s\n",
pci_name(asd_ha->pcidev));
return err;
}
err = asd_read_ocm(asd_ha);
if (err) {
asd_printk("couldn't read ocm(%d)\n", err);
/* While suspicios, it is not an error that we
* couldn't read the OCM. */
}
err = asd_read_flash(asd_ha);
if (err) {
asd_printk("couldn't read flash(%d)\n", err);
/* While suspicios, it is not an error that we
* couldn't read FLASH memory.
*/
}
asd_init_ctxmem(asd_ha);
if (asd_get_user_sas_addr(asd_ha)) {
asd_printk("No SAS Address provided for %s\n",
pci_name(asd_ha->pcidev));
err = -ENODEV;
goto Out;
}
asd_propagate_sas_addr(asd_ha);
err = asd_init_phys(asd_ha);
if (err) {
asd_printk("couldn't initialize phys for %s\n",
pci_name(asd_ha->pcidev));
goto Out;
}
asd_init_ports(asd_ha);
err = asd_init_scbs(asd_ha);
if (err) {
asd_printk("couldn't initialize scbs for %s\n",
pci_name(asd_ha->pcidev));
goto Out;
}
err = asd_init_dl(asd_ha);
if (err) {
asd_printk("couldn't initialize the done list:%d\n",
err);
goto Out;
}
err = asd_init_escbs(asd_ha);
if (err) {
asd_printk("couldn't initialize escbs\n");
goto Out;
}
err = asd_init_chip(asd_ha);
if (err) {
asd_printk("couldn't init the chip\n");
goto Out;
}
Out:
return err;
}
/* ---------- Chip reset ---------- */
/**
* asd_chip_reset -- reset the host adapter, etc
* @asd_ha: pointer to host adapter structure of interest
*
* Called from the ISR. Hard reset the chip. Let everything
* timeout. This should be no different than hot-unplugging the
* host adapter. Once everything times out we'll init the chip with
* a call to asd_init_chip() and enable interrupts with asd_enable_ints().
* XXX finish.
*/
static void asd_chip_reset(struct asd_ha_struct *asd_ha)
{
struct sas_ha_struct *sas_ha = &asd_ha->sas_ha;
ASD_DPRINTK("chip reset for %s\n", pci_name(asd_ha->pcidev));
asd_chip_hardrst(asd_ha);
sas_ha->notify_ha_event(sas_ha, HAE_RESET);
}
/* ---------- Done List Routines ---------- */
static void asd_dl_tasklet_handler(unsigned long data)
{
struct asd_ha_struct *asd_ha = (struct asd_ha_struct *) data;
struct asd_seq_data *seq = &asd_ha->seq;
unsigned long flags;
while (1) {
struct done_list_struct *dl = &seq->dl[seq->dl_next];
struct asd_ascb *ascb;
if ((dl->toggle & DL_TOGGLE_MASK) != seq->dl_toggle)
break;
/* find the aSCB */
spin_lock_irqsave(&seq->tc_index_lock, flags);
ascb = asd_tc_index_find(seq, (int)le16_to_cpu(dl->index));
spin_unlock_irqrestore(&seq->tc_index_lock, flags);
if (unlikely(!ascb)) {
ASD_DPRINTK("BUG:sequencer:dl:no ascb?!\n");
goto next_1;
} else if (ascb->scb->header.opcode == EMPTY_SCB) {
goto out;
} else if (!ascb->uldd_timer && !del_timer(&ascb->timer)) {
goto next_1;
}
spin_lock_irqsave(&seq->pend_q_lock, flags);
list_del_init(&ascb->list);
seq->pending--;
spin_unlock_irqrestore(&seq->pend_q_lock, flags);
out:
ascb->tasklet_complete(ascb, dl);
next_1:
seq->dl_next = (seq->dl_next + 1) & (ASD_DL_SIZE-1);
if (!seq->dl_next)
seq->dl_toggle ^= DL_TOGGLE_MASK;
}
}
/* ---------- Interrupt Service Routines ---------- */
/**
* asd_process_donelist_isr -- schedule processing of done list entries
* @asd_ha: pointer to host adapter structure
*/
static void asd_process_donelist_isr(struct asd_ha_struct *asd_ha)
{
tasklet_schedule(&asd_ha->seq.dl_tasklet);
}
/**
* asd_com_sas_isr -- process device communication interrupt (COMINT)
* @asd_ha: pointer to host adapter structure
*/
static void asd_com_sas_isr(struct asd_ha_struct *asd_ha)
{
u32 comstat = asd_read_reg_dword(asd_ha, COMSTAT);
/* clear COMSTAT int */
asd_write_reg_dword(asd_ha, COMSTAT, 0xFFFFFFFF);
if (comstat & CSBUFPERR) {
asd_printk("%s: command/status buffer dma parity error\n",
pci_name(asd_ha->pcidev));
} else if (comstat & CSERR) {
int i;
u32 dmaerr = asd_read_reg_dword(asd_ha, DMAERR);
dmaerr &= 0xFF;
asd_printk("%s: command/status dma error, DMAERR: 0x%02x, "
"CSDMAADR: 0x%04x, CSDMAADR+4: 0x%04x\n",
pci_name(asd_ha->pcidev),
dmaerr,
asd_read_reg_dword(asd_ha, CSDMAADR),
asd_read_reg_dword(asd_ha, CSDMAADR+4));
asd_printk("CSBUFFER:\n");
for (i = 0; i < 8; i++) {
asd_printk("%08x %08x %08x %08x\n",
asd_read_reg_dword(asd_ha, CSBUFFER),
asd_read_reg_dword(asd_ha, CSBUFFER+4),
asd_read_reg_dword(asd_ha, CSBUFFER+8),
asd_read_reg_dword(asd_ha, CSBUFFER+12));
}
asd_dump_seq_state(asd_ha, 0);
} else if (comstat & OVLYERR) {
u32 dmaerr = asd_read_reg_dword(asd_ha, DMAERR);
dmaerr = (dmaerr >> 8) & 0xFF;
asd_printk("%s: overlay dma error:0x%x\n",
pci_name(asd_ha->pcidev),
dmaerr);
}
asd_chip_reset(asd_ha);
}
static void asd_arp2_err(struct asd_ha_struct *asd_ha, u32 dchstatus)
{
static const char *halt_code[256] = {
"UNEXPECTED_INTERRUPT0",
"UNEXPECTED_INTERRUPT1",
"UNEXPECTED_INTERRUPT2",
"UNEXPECTED_INTERRUPT3",
"UNEXPECTED_INTERRUPT4",
"UNEXPECTED_INTERRUPT5",
"UNEXPECTED_INTERRUPT6",
"UNEXPECTED_INTERRUPT7",
"UNEXPECTED_INTERRUPT8",
"UNEXPECTED_INTERRUPT9",
"UNEXPECTED_INTERRUPT10",
[11 ... 19] = "unknown[11,19]",
"NO_FREE_SCB_AVAILABLE",
"INVALID_SCB_OPCODE",
"INVALID_MBX_OPCODE",
"INVALID_ATA_STATE",
"ATA_QUEUE_FULL",
"ATA_TAG_TABLE_FAULT",
"ATA_TAG_MASK_FAULT",
"BAD_LINK_QUEUE_STATE",
"DMA2CHIM_QUEUE_ERROR",
"EMPTY_SCB_LIST_FULL",
"unknown[30]",
"IN_USE_SCB_ON_FREE_LIST",
"BAD_OPEN_WAIT_STATE",
"INVALID_STP_AFFILIATION",
"unknown[34]",
"EXEC_QUEUE_ERROR",
"TOO_MANY_EMPTIES_NEEDED",
"EMPTY_REQ_QUEUE_ERROR",
"Q_MONIRTT_MGMT_ERROR",
"TARGET_MODE_FLOW_ERROR",
"DEVICE_QUEUE_NOT_FOUND",
"START_IRTT_TIMER_ERROR",
"ABORT_TASK_ILLEGAL_REQ",
[43 ... 255] = "unknown[43,255]"
};
if (dchstatus & CSEQINT) {
u32 arp2int = asd_read_reg_dword(asd_ha, CARP2INT);
if (arp2int & (ARP2WAITTO|ARP2ILLOPC|ARP2PERR|ARP2CIOPERR)) {
asd_printk("%s: CSEQ arp2int:0x%x\n",
pci_name(asd_ha->pcidev),
arp2int);
} else if (arp2int & ARP2HALTC)
asd_printk("%s: CSEQ halted: %s\n",
pci_name(asd_ha->pcidev),
halt_code[(arp2int>>16)&0xFF]);
else
asd_printk("%s: CARP2INT:0x%x\n",
pci_name(asd_ha->pcidev),
arp2int);
}
if (dchstatus & LSEQINT_MASK) {
int lseq;
u8 lseq_mask = dchstatus & LSEQINT_MASK;
for_each_sequencer(lseq_mask, lseq_mask, lseq) {
u32 arp2int = asd_read_reg_dword(asd_ha,
LmARP2INT(lseq));
if (arp2int & (ARP2WAITTO | ARP2ILLOPC | ARP2PERR
| ARP2CIOPERR)) {
asd_printk("%s: LSEQ%d arp2int:0x%x\n",
pci_name(asd_ha->pcidev),
lseq, arp2int);
/* XXX we should only do lseq reset */
} else if (arp2int & ARP2HALTC)
asd_printk("%s: LSEQ%d halted: %s\n",
pci_name(asd_ha->pcidev),
lseq,halt_code[(arp2int>>16)&0xFF]);
else
asd_printk("%s: LSEQ%d ARP2INT:0x%x\n",
pci_name(asd_ha->pcidev), lseq,
arp2int);
}
}
asd_chip_reset(asd_ha);
}
/**
* asd_dch_sas_isr -- process device channel interrupt (DEVINT)
* @asd_ha: pointer to host adapter structure
*/
static void asd_dch_sas_isr(struct asd_ha_struct *asd_ha)
{
u32 dchstatus = asd_read_reg_dword(asd_ha, DCHSTATUS);
if (dchstatus & CFIFTOERR) {
asd_printk("%s: CFIFTOERR\n", pci_name(asd_ha->pcidev));
asd_chip_reset(asd_ha);
} else
asd_arp2_err(asd_ha, dchstatus);
}
/**
* ads_rbi_exsi_isr -- process external system interface interrupt (INITERR)
* @asd_ha: pointer to host adapter structure
*/
static void asd_rbi_exsi_isr(struct asd_ha_struct *asd_ha)
{
u32 stat0r = asd_read_reg_dword(asd_ha, ASISTAT0R);
if (!(stat0r & ASIERR)) {
asd_printk("hmm, EXSI interrupted but no error?\n");
return;
}
if (stat0r & ASIFMTERR) {
asd_printk("ASI SEEPROM format error for %s\n",
pci_name(asd_ha->pcidev));
} else if (stat0r & ASISEECHKERR) {
u32 stat1r = asd_read_reg_dword(asd_ha, ASISTAT1R);
asd_printk("ASI SEEPROM checksum 0x%x error for %s\n",
stat1r & CHECKSUM_MASK,
pci_name(asd_ha->pcidev));
} else {
u32 statr = asd_read_reg_dword(asd_ha, ASIERRSTATR);
if (!(statr & CPI2ASIMSTERR_MASK)) {
ASD_DPRINTK("hmm, ASIERR?\n");
return;
} else {
u32 addr = asd_read_reg_dword(asd_ha, ASIERRADDR);
u32 data = asd_read_reg_dword(asd_ha, ASIERRDATAR);
asd_printk("%s: CPI2 xfer err: addr: 0x%x, wdata: 0x%x, "
"count: 0x%x, byteen: 0x%x, targerr: 0x%x "
"master id: 0x%x, master err: 0x%x\n",
pci_name(asd_ha->pcidev),
addr, data,
(statr & CPI2ASIBYTECNT_MASK) >> 16,
(statr & CPI2ASIBYTEEN_MASK) >> 12,
(statr & CPI2ASITARGERR_MASK) >> 8,
(statr & CPI2ASITARGMID_MASK) >> 4,
(statr & CPI2ASIMSTERR_MASK));
}
}
asd_chip_reset(asd_ha);
}
/**
* asd_hst_pcix_isr -- process host interface interrupts
* @asd_ha: pointer to host adapter structure
*
* Asserted on PCIX errors: target abort, etc.
*/
static void asd_hst_pcix_isr(struct asd_ha_struct *asd_ha)
{
u16 status;
u32 pcix_status;
u32 ecc_status;
pci_read_config_word(asd_ha->pcidev, PCI_STATUS, &status);
pci_read_config_dword(asd_ha->pcidev, PCIX_STATUS, &pcix_status);
pci_read_config_dword(asd_ha->pcidev, ECC_CTRL_STAT, &ecc_status);
if (status & PCI_STATUS_DETECTED_PARITY)
asd_printk("parity error for %s\n", pci_name(asd_ha->pcidev));
else if (status & PCI_STATUS_REC_MASTER_ABORT)
asd_printk("master abort for %s\n", pci_name(asd_ha->pcidev));
else if (status & PCI_STATUS_REC_TARGET_ABORT)
asd_printk("target abort for %s\n", pci_name(asd_ha->pcidev));
else if (status & PCI_STATUS_PARITY)
asd_printk("data parity for %s\n", pci_name(asd_ha->pcidev));
else if (pcix_status & RCV_SCE) {
asd_printk("received split completion error for %s\n",
pci_name(asd_ha->pcidev));
pci_write_config_dword(asd_ha->pcidev,PCIX_STATUS,pcix_status);
/* XXX: Abort task? */
return;
} else if (pcix_status & UNEXP_SC) {
asd_printk("unexpected split completion for %s\n",
pci_name(asd_ha->pcidev));
pci_write_config_dword(asd_ha->pcidev,PCIX_STATUS,pcix_status);
/* ignore */
return;
} else if (pcix_status & SC_DISCARD)
asd_printk("split completion discarded for %s\n",
pci_name(asd_ha->pcidev));
else if (ecc_status & UNCOR_ECCERR)
asd_printk("uncorrectable ECC error for %s\n",
pci_name(asd_ha->pcidev));
asd_chip_reset(asd_ha);
}
/**
* asd_hw_isr -- host adapter interrupt service routine
* @irq: ignored
* @dev_id: pointer to host adapter structure
*
* The ISR processes done list entries and level 3 error handling.
*/
irqreturn_t asd_hw_isr(int irq, void *dev_id)
{
struct asd_ha_struct *asd_ha = dev_id;
u32 chimint = asd_read_reg_dword(asd_ha, CHIMINT);
if (!chimint)
return IRQ_NONE;
asd_write_reg_dword(asd_ha, CHIMINT, chimint);
(void) asd_read_reg_dword(asd_ha, CHIMINT);
if (chimint & DLAVAIL)
asd_process_donelist_isr(asd_ha);
if (chimint & COMINT)
asd_com_sas_isr(asd_ha);
if (chimint & DEVINT)
asd_dch_sas_isr(asd_ha);
if (chimint & INITERR)
asd_rbi_exsi_isr(asd_ha);
if (chimint & HOSTERR)
asd_hst_pcix_isr(asd_ha);
return IRQ_HANDLED;
}
/* ---------- SCB handling ---------- */
static struct asd_ascb *asd_ascb_alloc(struct asd_ha_struct *asd_ha,
gfp_t gfp_flags)
{
extern struct kmem_cache *asd_ascb_cache;
struct asd_seq_data *seq = &asd_ha->seq;
struct asd_ascb *ascb;
unsigned long flags;
ascb = kmem_cache_zalloc(asd_ascb_cache, gfp_flags);
if (ascb) {
ascb->dma_scb.size = sizeof(struct scb);
ascb->dma_scb.vaddr = dma_pool_alloc(asd_ha->scb_pool,
gfp_flags,
&ascb->dma_scb.dma_handle);
if (!ascb->dma_scb.vaddr) {
kmem_cache_free(asd_ascb_cache, ascb);
return NULL;
}
memset(ascb->dma_scb.vaddr, 0, sizeof(struct scb));
asd_init_ascb(asd_ha, ascb);
spin_lock_irqsave(&seq->tc_index_lock, flags);
ascb->tc_index = asd_tc_index_get(seq, ascb);
spin_unlock_irqrestore(&seq->tc_index_lock, flags);
if (ascb->tc_index == -1)
goto undo;
ascb->scb->header.index = cpu_to_le16((u16)ascb->tc_index);
}
return ascb;
undo:
dma_pool_free(asd_ha->scb_pool, ascb->dma_scb.vaddr,
ascb->dma_scb.dma_handle);
kmem_cache_free(asd_ascb_cache, ascb);
ASD_DPRINTK("no index for ascb\n");
return NULL;
}
/**
* asd_ascb_alloc_list -- allocate a list of aSCBs
* @asd_ha: pointer to host adapter structure
* @num: pointer to integer number of aSCBs
* @gfp_flags: GFP_ flags.
*
* This is the only function which is used to allocate aSCBs.
* It can allocate one or many. If more than one, then they form
* a linked list in two ways: by their list field of the ascb struct
* and by the next_scb field of the scb_header.
*
* Returns NULL if no memory was available, else pointer to a list
* of ascbs. When this function returns, @num would be the number
* of SCBs which were not able to be allocated, 0 if all requested
* were able to be allocated.
*/
struct asd_ascb *asd_ascb_alloc_list(struct asd_ha_struct
*asd_ha, int *num,
gfp_t gfp_flags)
{
struct asd_ascb *first = NULL;
for ( ; *num > 0; --*num) {
struct asd_ascb *ascb = asd_ascb_alloc(asd_ha, gfp_flags);
if (!ascb)
break;
else if (!first)
first = ascb;
else {
struct asd_ascb *last = list_entry(first->list.prev,
struct asd_ascb,
list);
list_add_tail(&ascb->list, &first->list);
last->scb->header.next_scb =
cpu_to_le64(((u64)ascb->dma_scb.dma_handle));
}
}
return first;
}
/**
* asd_swap_head_scb -- swap the head scb
* @asd_ha: pointer to host adapter structure
* @ascb: pointer to the head of an ascb list
*
* The sequencer knows the DMA address of the next SCB to be DMAed to
* the host adapter, from initialization or from the last list DMAed.
* seq->next_scb keeps the address of this SCB. The sequencer will
* DMA to the host adapter this list of SCBs. But the head (first
* element) of this list is not known to the sequencer. Here we swap
* the head of the list with the known SCB (memcpy()).
* Only one memcpy() is required per list so it is in our interest
* to keep the list of SCB as long as possible so that the ratio
* of number of memcpy calls to the number of SCB DMA-ed is as small
* as possible.
*
* LOCKING: called with the pending list lock held.
*/
static void asd_swap_head_scb(struct asd_ha_struct *asd_ha,
struct asd_ascb *ascb)
{
struct asd_seq_data *seq = &asd_ha->seq;
struct asd_ascb *last = list_entry(ascb->list.prev,
struct asd_ascb,
list);
struct asd_dma_tok t = ascb->dma_scb;
memcpy(seq->next_scb.vaddr, ascb->scb, sizeof(*ascb->scb));
ascb->dma_scb = seq->next_scb;
ascb->scb = ascb->dma_scb.vaddr;
seq->next_scb = t;
last->scb->header.next_scb =
cpu_to_le64(((u64)seq->next_scb.dma_handle));
}
/**
* asd_start_timers -- (add and) start timers of SCBs
* @list: pointer to struct list_head of the scbs
* @to: timeout in jiffies
*
* If an SCB in the @list has no timer function, assign the default
* one, then start the timer of the SCB. This function is
* intended to be called from asd_post_ascb_list(), just prior to
* posting the SCBs to the sequencer.
*/
static void asd_start_scb_timers(struct list_head *list)
{
struct asd_ascb *ascb;
list_for_each_entry(ascb, list, list) {
if (!ascb->uldd_timer) {
ascb->timer.data = (unsigned long) ascb;
ascb->timer.function = asd_ascb_timedout;
ascb->timer.expires = jiffies + AIC94XX_SCB_TIMEOUT;
add_timer(&ascb->timer);
}
}
}
/**
* asd_post_ascb_list -- post a list of 1 or more aSCBs to the host adapter
* @asd_ha: pointer to a host adapter structure
* @ascb: pointer to the first aSCB in the list
* @num: number of aSCBs in the list (to be posted)
*
* See queueing comment in asd_post_escb_list().
*
* Additional note on queuing: In order to minimize the ratio of memcpy()
* to the number of ascbs sent, we try to batch-send as many ascbs as possible
* in one go.
* Two cases are possible:
* A) can_queue >= num,
* B) can_queue < num.
* Case A: we can send the whole batch at once. Increment "pending"
* in the beginning of this function, when it is checked, in order to
* eliminate races when this function is called by multiple processes.
* Case B: should never happen if the managing layer considers
* lldd_queue_size.
*/
int asd_post_ascb_list(struct asd_ha_struct *asd_ha, struct asd_ascb *ascb,
int num)
{
unsigned long flags;
LIST_HEAD(list);
int can_queue;
spin_lock_irqsave(&asd_ha->seq.pend_q_lock, flags);
can_queue = asd_ha->hw_prof.max_scbs - asd_ha->seq.pending;
if (can_queue >= num)
asd_ha->seq.pending += num;
else
can_queue = 0;
if (!can_queue) {
spin_unlock_irqrestore(&asd_ha->seq.pend_q_lock, flags);
asd_printk("%s: scb queue full\n", pci_name(asd_ha->pcidev));
return -SAS_QUEUE_FULL;
}
asd_swap_head_scb(asd_ha, ascb);
__list_add(&list, ascb->list.prev, &ascb->list);
asd_start_scb_timers(&list);
asd_ha->seq.scbpro += num;
list_splice_init(&list, asd_ha->seq.pend_q.prev);
asd_write_reg_dword(asd_ha, SCBPRO, (u32)asd_ha->seq.scbpro);
spin_unlock_irqrestore(&asd_ha->seq.pend_q_lock, flags);
return 0;
}
/**
* asd_post_escb_list -- post a list of 1 or more empty scb
* @asd_ha: pointer to a host adapter structure
* @ascb: pointer to the first empty SCB in the list
* @num: number of aSCBs in the list (to be posted)
*
* This is essentially the same as asd_post_ascb_list, but we do not
* increment pending, add those to the pending list or get indexes.
* See asd_init_escbs() and asd_init_post_escbs().
*
* Since sending a list of ascbs is a superset of sending a single
* ascb, this function exists to generalize this. More specifically,
* when sending a list of those, we want to do only a _single_
* memcpy() at swap head, as opposed to for each ascb sent (in the
* case of sending them one by one). That is, we want to minimize the
* ratio of memcpy() operations to the number of ascbs sent. The same
* logic applies to asd_post_ascb_list().
*/
int asd_post_escb_list(struct asd_ha_struct *asd_ha, struct asd_ascb *ascb,
int num)
{
unsigned long flags;
spin_lock_irqsave(&asd_ha->seq.pend_q_lock, flags);
asd_swap_head_scb(asd_ha, ascb);
asd_ha->seq.scbpro += num;
asd_write_reg_dword(asd_ha, SCBPRO, (u32)asd_ha->seq.scbpro);
spin_unlock_irqrestore(&asd_ha->seq.pend_q_lock, flags);
return 0;
}
/* ---------- LED ---------- */
/**
* asd_turn_led -- turn on/off an LED
* @asd_ha: pointer to host adapter structure
* @phy_id: the PHY id whose LED we want to manupulate
* @op: 1 to turn on, 0 to turn off
*/
void asd_turn_led(struct asd_ha_struct *asd_ha, int phy_id, int op)
{
if (phy_id < ASD_MAX_PHYS) {
u32 v = asd_read_reg_dword(asd_ha, LmCONTROL(phy_id));
if (op)
v |= LEDPOL;
else
v &= ~LEDPOL;
asd_write_reg_dword(asd_ha, LmCONTROL(phy_id), v);
}
}
/**
* asd_control_led -- enable/disable an LED on the board
* @asd_ha: pointer to host adapter structure
* @phy_id: integer, the phy id
* @op: integer, 1 to enable, 0 to disable the LED
*
* First we output enable the LED, then we set the source
* to be an external module.
*/
void asd_control_led(struct asd_ha_struct *asd_ha, int phy_id, int op)
{
if (phy_id < ASD_MAX_PHYS) {
u32 v;
v = asd_read_reg_dword(asd_ha, GPIOOER);
if (op)
v |= (1 << phy_id);
else
v &= ~(1 << phy_id);
asd_write_reg_dword(asd_ha, GPIOOER, v);
v = asd_read_reg_dword(asd_ha, GPIOCNFGR);
if (op)
v |= (1 << phy_id);
else
v &= ~(1 << phy_id);
asd_write_reg_dword(asd_ha, GPIOCNFGR, v);
}
}
/* ---------- PHY enable ---------- */
static int asd_enable_phy(struct asd_ha_struct *asd_ha, int phy_id)
{
struct asd_phy *phy = &asd_ha->phys[phy_id];
asd_write_reg_byte(asd_ha, LmSEQ_OOB_REG(phy_id, INT_ENABLE_2), 0);
asd_write_reg_byte(asd_ha, LmSEQ_OOB_REG(phy_id, HOT_PLUG_DELAY),
HOTPLUG_DELAY_TIMEOUT);
/* Get defaults from manuf. sector */
/* XXX we need defaults for those in case MS is broken. */
asd_write_reg_byte(asd_ha, LmSEQ_OOB_REG(phy_id, PHY_CONTROL_0),
phy->phy_desc->phy_control_0);
asd_write_reg_byte(asd_ha, LmSEQ_OOB_REG(phy_id, PHY_CONTROL_1),
phy->phy_desc->phy_control_1);
asd_write_reg_byte(asd_ha, LmSEQ_OOB_REG(phy_id, PHY_CONTROL_2),
phy->phy_desc->phy_control_2);
asd_write_reg_byte(asd_ha, LmSEQ_OOB_REG(phy_id, PHY_CONTROL_3),
phy->phy_desc->phy_control_3);
asd_write_reg_dword(asd_ha, LmSEQ_TEN_MS_COMINIT_TIMEOUT(phy_id),
ASD_COMINIT_TIMEOUT);
asd_write_reg_addr(asd_ha, LmSEQ_TX_ID_ADDR_FRAME(phy_id),
phy->id_frm_tok->dma_handle);
asd_control_led(asd_ha, phy_id, 1);
return 0;
}
int asd_enable_phys(struct asd_ha_struct *asd_ha, const u8 phy_mask)
{
u8 phy_m;
u8 i;
int num = 0, k;
struct asd_ascb *ascb;
struct asd_ascb *ascb_list;
if (!phy_mask) {
asd_printk("%s called with phy_mask of 0!?\n", __func__);
return 0;
}
for_each_phy(phy_mask, phy_m, i) {
num++;
asd_enable_phy(asd_ha, i);
}
k = num;
ascb_list = asd_ascb_alloc_list(asd_ha, &k, GFP_KERNEL);
if (!ascb_list) {
asd_printk("no memory for control phy ascb list\n");
return -ENOMEM;
}
num -= k;
ascb = ascb_list;
for_each_phy(phy_mask, phy_m, i) {
asd_build_control_phy(ascb, i, ENABLE_PHY);
ascb = list_entry(ascb->list.next, struct asd_ascb, list);
}
ASD_DPRINTK("posting %d control phy scbs\n", num);
k = asd_post_ascb_list(asd_ha, ascb_list, num);
if (k)
asd_ascb_free_list(ascb_list);
return k;
}
| gpl-2.0 |
GustavoRD78/78Kernel-6.0.1-23.5.A.0.575 | arch/powerpc/platforms/ps3/time.c | 9395 | 2507 | /*
* PS3 time and rtc routines.
*
* Copyright (C) 2006 Sony Computer Entertainment Inc.
* Copyright 2006 Sony 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; 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/platform_device.h>
#include <asm/firmware.h>
#include <asm/rtc.h>
#include <asm/lv1call.h>
#include <asm/ps3.h>
#include "platform.h"
#define dump_tm(_a) _dump_tm(_a, __func__, __LINE__)
static void _dump_tm(const struct rtc_time *tm, const char* func, int line)
{
pr_debug("%s:%d tm_sec %d\n", func, line, tm->tm_sec);
pr_debug("%s:%d tm_min %d\n", func, line, tm->tm_min);
pr_debug("%s:%d tm_hour %d\n", func, line, tm->tm_hour);
pr_debug("%s:%d tm_mday %d\n", func, line, tm->tm_mday);
pr_debug("%s:%d tm_mon %d\n", func, line, tm->tm_mon);
pr_debug("%s:%d tm_year %d\n", func, line, tm->tm_year);
pr_debug("%s:%d tm_wday %d\n", func, line, tm->tm_wday);
}
#define dump_time(_a) _dump_time(_a, __func__, __LINE__)
static void __maybe_unused _dump_time(int time, const char *func,
int line)
{
struct rtc_time tm;
to_tm(time, &tm);
pr_debug("%s:%d time %d\n", func, line, time);
_dump_tm(&tm, func, line);
}
void __init ps3_calibrate_decr(void)
{
int result;
u64 tmp;
result = ps3_repository_read_be_tb_freq(0, &tmp);
BUG_ON(result);
ppc_tb_freq = tmp;
ppc_proc_freq = ppc_tb_freq * 40;
}
static u64 read_rtc(void)
{
int result;
u64 rtc_val;
u64 tb_val;
result = lv1_get_rtc(&rtc_val, &tb_val);
BUG_ON(result);
return rtc_val;
}
unsigned long __init ps3_get_boot_time(void)
{
return read_rtc() + ps3_os_area_get_rtc_diff();
}
static int __init ps3_rtc_init(void)
{
struct platform_device *pdev;
if (!firmware_has_feature(FW_FEATURE_PS3_LV1))
return -ENODEV;
pdev = platform_device_register_simple("rtc-ps3", -1, NULL, 0);
if (IS_ERR(pdev))
return PTR_ERR(pdev);
return 0;
}
module_init(ps3_rtc_init);
| gpl-2.0 |
jfdsmabalot/kernel_moto-x | drivers/uwb/uwbd.c | 9651 | 10482 | /*
* Ultra Wide Band
* Neighborhood Management Daemon
*
* Copyright (C) 2005-2006 Intel Corporation
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*
* This daemon takes care of maintaing information that describes the
* UWB neighborhood that the radios in this machine can see. It also
* keeps a tab of which devices are visible, makes sure each HC sits
* on a different channel to avoid interfering, etc.
*
* Different drivers (radio controller, device, any API in general)
* communicate with this daemon through an event queue. Daemon wakes
* up, takes a list of events and handles them one by one; handling
* function is extracted from a table based on the event's type and
* subtype. Events are freed only if the handling function says so.
*
* . Lock protecting the event list has to be an spinlock and locked
* with IRQSAVE because it might be called from an interrupt
* context (ie: when events arrive and the notification drops
* down from the ISR).
*
* . UWB radio controller drivers queue events to the daemon using
* uwbd_event_queue(). They just get the event, chew it to make it
* look like UWBD likes it and pass it in a buffer allocated with
* uwb_event_alloc().
*
* EVENTS
*
* Events have a type, a subtype, a length, some other stuff and the
* data blob, which depends on the event. The header is 'struct
* uwb_event'; for payloads, see 'struct uwbd_evt_*'.
*
* EVENT HANDLER TABLES
*
* To find a handling function for an event, the type is used to index
* a subtype-table in the type-table. The subtype-table is indexed
* with the subtype to get the function that handles the event. Start
* with the main type-table 'uwbd_evt_type_handler'.
*
* DEVICES
*
* Devices are created when a bunch of beacons have been received and
* it is stablished that the device has stable radio presence. CREATED
* only, not configured. Devices are ONLY configured when an
* Application-Specific IE Probe is receieved, in which the device
* declares which Protocol ID it groks. Then the device is CONFIGURED
* (and the driver->probe() stuff of the device model is invoked).
*
* Devices are considered disconnected when a certain number of
* beacons are not received in an amount of time.
*
* Handler functions are called normally uwbd_evt_handle_*().
*/
#include <linux/kthread.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/freezer.h>
#include "uwb-internal.h"
/*
* UWBD Event handler function signature
*
* Return !0 if the event needs not to be freed (ie the handler
* takes/took care of it). 0 means the daemon code will free the
* event.
*
* @evt->rc is already referenced and guaranteed to exist. See
* uwb_evt_handle().
*/
typedef int (*uwbd_evt_handler_f)(struct uwb_event *);
/**
* Properties of a UWBD event
*
* @handler: the function that will handle this event
* @name: text name of event
*/
struct uwbd_event {
uwbd_evt_handler_f handler;
const char *name;
};
/* Table of handlers for and properties of the UWBD Radio Control Events */
static struct uwbd_event uwbd_urc_events[] = {
[UWB_RC_EVT_IE_RCV] = {
.handler = uwbd_evt_handle_rc_ie_rcv,
.name = "IE_RECEIVED"
},
[UWB_RC_EVT_BEACON] = {
.handler = uwbd_evt_handle_rc_beacon,
.name = "BEACON_RECEIVED"
},
[UWB_RC_EVT_BEACON_SIZE] = {
.handler = uwbd_evt_handle_rc_beacon_size,
.name = "BEACON_SIZE_CHANGE"
},
[UWB_RC_EVT_BPOIE_CHANGE] = {
.handler = uwbd_evt_handle_rc_bpoie_change,
.name = "BPOIE_CHANGE"
},
[UWB_RC_EVT_BP_SLOT_CHANGE] = {
.handler = uwbd_evt_handle_rc_bp_slot_change,
.name = "BP_SLOT_CHANGE"
},
[UWB_RC_EVT_DRP_AVAIL] = {
.handler = uwbd_evt_handle_rc_drp_avail,
.name = "DRP_AVAILABILITY_CHANGE"
},
[UWB_RC_EVT_DRP] = {
.handler = uwbd_evt_handle_rc_drp,
.name = "DRP"
},
[UWB_RC_EVT_DEV_ADDR_CONFLICT] = {
.handler = uwbd_evt_handle_rc_dev_addr_conflict,
.name = "DEV_ADDR_CONFLICT",
},
};
struct uwbd_evt_type_handler {
const char *name;
struct uwbd_event *uwbd_events;
size_t size;
};
/* Table of handlers for each UWBD Event type. */
static struct uwbd_evt_type_handler uwbd_urc_evt_type_handlers[] = {
[UWB_RC_CET_GENERAL] = {
.name = "URC",
.uwbd_events = uwbd_urc_events,
.size = ARRAY_SIZE(uwbd_urc_events),
},
};
static const struct uwbd_event uwbd_message_handlers[] = {
[UWB_EVT_MSG_RESET] = {
.handler = uwbd_msg_handle_reset,
.name = "reset",
},
};
/*
* Handle an URC event passed to the UWB Daemon
*
* @evt: the event to handle
* @returns: 0 if the event can be kfreed, !0 on the contrary
* (somebody else took ownership) [coincidentally, returning
* a <0 errno code will free it :)].
*
* Looks up the two indirection tables (one for the type, one for the
* subtype) to decide which function handles it and then calls the
* handler.
*
* The event structure passed to the event handler has the radio
* controller in @evt->rc referenced. The reference will be dropped
* once the handler returns, so if it needs it for longer (async),
* it'll need to take another one.
*/
static
int uwbd_event_handle_urc(struct uwb_event *evt)
{
int result = -EINVAL;
struct uwbd_evt_type_handler *type_table;
uwbd_evt_handler_f handler;
u8 type, context;
u16 event;
type = evt->notif.rceb->bEventType;
event = le16_to_cpu(evt->notif.rceb->wEvent);
context = evt->notif.rceb->bEventContext;
if (type >= ARRAY_SIZE(uwbd_urc_evt_type_handlers))
goto out;
type_table = &uwbd_urc_evt_type_handlers[type];
if (type_table->uwbd_events == NULL)
goto out;
if (event >= type_table->size)
goto out;
handler = type_table->uwbd_events[event].handler;
if (handler == NULL)
goto out;
result = (*handler)(evt);
out:
if (result < 0)
dev_err(&evt->rc->uwb_dev.dev,
"UWBD: event 0x%02x/%04x/%02x, handling failed: %d\n",
type, event, context, result);
return result;
}
static void uwbd_event_handle_message(struct uwb_event *evt)
{
struct uwb_rc *rc;
int result;
rc = evt->rc;
if (evt->message < 0 || evt->message >= ARRAY_SIZE(uwbd_message_handlers)) {
dev_err(&rc->uwb_dev.dev, "UWBD: invalid message type %d\n", evt->message);
return;
}
result = uwbd_message_handlers[evt->message].handler(evt);
if (result < 0)
dev_err(&rc->uwb_dev.dev, "UWBD: '%s' message failed: %d\n",
uwbd_message_handlers[evt->message].name, result);
}
static void uwbd_event_handle(struct uwb_event *evt)
{
struct uwb_rc *rc;
int should_keep;
rc = evt->rc;
if (rc->ready) {
switch (evt->type) {
case UWB_EVT_TYPE_NOTIF:
should_keep = uwbd_event_handle_urc(evt);
if (should_keep <= 0)
kfree(evt->notif.rceb);
break;
case UWB_EVT_TYPE_MSG:
uwbd_event_handle_message(evt);
break;
default:
dev_err(&rc->uwb_dev.dev, "UWBD: invalid event type %d\n", evt->type);
break;
}
}
__uwb_rc_put(rc); /* for the __uwb_rc_get() in uwb_rc_notif_cb() */
}
/**
* UWB Daemon
*
* Listens to all UWB notifications and takes care to track the state
* of the UWB neighbourhood for the kernel. When we do a run, we
* spinlock, move the list to a private copy and release the
* lock. Hold it as little as possible. Not a conflict: it is
* guaranteed we own the events in the private list.
*
* FIXME: should change so we don't have a 1HZ timer all the time, but
* only if there are devices.
*/
static int uwbd(void *param)
{
struct uwb_rc *rc = param;
unsigned long flags;
struct uwb_event *evt;
int should_stop = 0;
while (1) {
wait_event_interruptible_timeout(
rc->uwbd.wq,
!list_empty(&rc->uwbd.event_list)
|| (should_stop = kthread_should_stop()),
HZ);
if (should_stop)
break;
try_to_freeze();
spin_lock_irqsave(&rc->uwbd.event_list_lock, flags);
if (!list_empty(&rc->uwbd.event_list)) {
evt = list_first_entry(&rc->uwbd.event_list, struct uwb_event, list_node);
list_del(&evt->list_node);
} else
evt = NULL;
spin_unlock_irqrestore(&rc->uwbd.event_list_lock, flags);
if (evt) {
uwbd_event_handle(evt);
kfree(evt);
}
uwb_beca_purge(rc); /* Purge devices that left */
}
return 0;
}
/** Start the UWB daemon */
void uwbd_start(struct uwb_rc *rc)
{
rc->uwbd.task = kthread_run(uwbd, rc, "uwbd");
if (rc->uwbd.task == NULL)
printk(KERN_ERR "UWB: Cannot start management daemon; "
"UWB won't work\n");
else
rc->uwbd.pid = rc->uwbd.task->pid;
}
/* Stop the UWB daemon and free any unprocessed events */
void uwbd_stop(struct uwb_rc *rc)
{
kthread_stop(rc->uwbd.task);
uwbd_flush(rc);
}
/*
* Queue an event for the management daemon
*
* When some lower layer receives an event, it uses this function to
* push it forward to the UWB daemon.
*
* Once you pass the event, you don't own it any more, but the daemon
* does. It will uwb_event_free() it when done, so make sure you
* uwb_event_alloc()ed it or bad things will happen.
*
* If the daemon is not running, we just free the event.
*/
void uwbd_event_queue(struct uwb_event *evt)
{
struct uwb_rc *rc = evt->rc;
unsigned long flags;
spin_lock_irqsave(&rc->uwbd.event_list_lock, flags);
if (rc->uwbd.pid != 0) {
list_add(&evt->list_node, &rc->uwbd.event_list);
wake_up_all(&rc->uwbd.wq);
} else {
__uwb_rc_put(evt->rc);
if (evt->type == UWB_EVT_TYPE_NOTIF)
kfree(evt->notif.rceb);
kfree(evt);
}
spin_unlock_irqrestore(&rc->uwbd.event_list_lock, flags);
return;
}
void uwbd_flush(struct uwb_rc *rc)
{
struct uwb_event *evt, *nxt;
spin_lock_irq(&rc->uwbd.event_list_lock);
list_for_each_entry_safe(evt, nxt, &rc->uwbd.event_list, list_node) {
if (evt->rc == rc) {
__uwb_rc_put(rc);
list_del(&evt->list_node);
if (evt->type == UWB_EVT_TYPE_NOTIF)
kfree(evt->notif.rceb);
kfree(evt);
}
}
spin_unlock_irq(&rc->uwbd.event_list_lock);
}
| gpl-2.0 |
Angor00/linux-aura-hd-android-2.6.35.3 | drivers/infiniband/hw/ehca/ehca_av.c | 13491 | 8046 | /*
* IBM eServer eHCA Infiniband device driver for Linux on POWER
*
* address vector functions
*
* Authors: Hoang-Nam Nguyen <hnguyen@de.ibm.com>
* Khadija Souissi <souissik@de.ibm.com>
* Reinhard Ernst <rernst@de.ibm.com>
* Christoph Raisch <raisch@de.ibm.com>
*
* Copyright (c) 2005 IBM Corporation
*
* All rights reserved.
*
* This source code is distributed under a dual license of GPL v2.0 and OpenIB
* BSD.
*
* OpenIB BSD License
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <linux/slab.h>
#include "ehca_tools.h"
#include "ehca_iverbs.h"
#include "hcp_if.h"
static struct kmem_cache *av_cache;
int ehca_calc_ipd(struct ehca_shca *shca, int port,
enum ib_rate path_rate, u32 *ipd)
{
int path = ib_rate_to_mult(path_rate);
int link, ret;
struct ib_port_attr pa;
if (path_rate == IB_RATE_PORT_CURRENT) {
*ipd = 0;
return 0;
}
if (unlikely(path < 0)) {
ehca_err(&shca->ib_device, "Invalid static rate! path_rate=%x",
path_rate);
return -EINVAL;
}
ret = ehca_query_port(&shca->ib_device, port, &pa);
if (unlikely(ret < 0)) {
ehca_err(&shca->ib_device, "Failed to query port ret=%i", ret);
return ret;
}
link = ib_width_enum_to_int(pa.active_width) * pa.active_speed;
if (path >= link)
/* no need to throttle if path faster than link */
*ipd = 0;
else
/* IPD = round((link / path) - 1) */
*ipd = ((link + (path >> 1)) / path) - 1;
return 0;
}
struct ib_ah *ehca_create_ah(struct ib_pd *pd, struct ib_ah_attr *ah_attr)
{
int ret;
struct ehca_av *av;
struct ehca_shca *shca = container_of(pd->device, struct ehca_shca,
ib_device);
av = kmem_cache_alloc(av_cache, GFP_KERNEL);
if (!av) {
ehca_err(pd->device, "Out of memory pd=%p ah_attr=%p",
pd, ah_attr);
return ERR_PTR(-ENOMEM);
}
av->av.sl = ah_attr->sl;
av->av.dlid = ah_attr->dlid;
av->av.slid_path_bits = ah_attr->src_path_bits;
if (ehca_static_rate < 0) {
u32 ipd;
if (ehca_calc_ipd(shca, ah_attr->port_num,
ah_attr->static_rate, &ipd)) {
ret = -EINVAL;
goto create_ah_exit1;
}
av->av.ipd = ipd;
} else
av->av.ipd = ehca_static_rate;
av->av.lnh = ah_attr->ah_flags;
av->av.grh.word_0 = EHCA_BMASK_SET(GRH_IPVERSION_MASK, 6);
av->av.grh.word_0 |= EHCA_BMASK_SET(GRH_TCLASS_MASK,
ah_attr->grh.traffic_class);
av->av.grh.word_0 |= EHCA_BMASK_SET(GRH_FLOWLABEL_MASK,
ah_attr->grh.flow_label);
av->av.grh.word_0 |= EHCA_BMASK_SET(GRH_HOPLIMIT_MASK,
ah_attr->grh.hop_limit);
av->av.grh.word_0 |= EHCA_BMASK_SET(GRH_NEXTHEADER_MASK, 0x1B);
/* set sgid in grh.word_1 */
if (ah_attr->ah_flags & IB_AH_GRH) {
int rc;
struct ib_port_attr port_attr;
union ib_gid gid;
memset(&port_attr, 0, sizeof(port_attr));
rc = ehca_query_port(pd->device, ah_attr->port_num,
&port_attr);
if (rc) { /* invalid port number */
ret = -EINVAL;
ehca_err(pd->device, "Invalid port number "
"ehca_query_port() returned %x "
"pd=%p ah_attr=%p", rc, pd, ah_attr);
goto create_ah_exit1;
}
memset(&gid, 0, sizeof(gid));
rc = ehca_query_gid(pd->device,
ah_attr->port_num,
ah_attr->grh.sgid_index, &gid);
if (rc) {
ret = -EINVAL;
ehca_err(pd->device, "Failed to retrieve sgid "
"ehca_query_gid() returned %x "
"pd=%p ah_attr=%p", rc, pd, ah_attr);
goto create_ah_exit1;
}
memcpy(&av->av.grh.word_1, &gid, sizeof(gid));
}
av->av.pmtu = shca->max_mtu;
/* dgid comes in grh.word_3 */
memcpy(&av->av.grh.word_3, &ah_attr->grh.dgid,
sizeof(ah_attr->grh.dgid));
return &av->ib_ah;
create_ah_exit1:
kmem_cache_free(av_cache, av);
return ERR_PTR(ret);
}
int ehca_modify_ah(struct ib_ah *ah, struct ib_ah_attr *ah_attr)
{
struct ehca_av *av;
struct ehca_ud_av new_ehca_av;
struct ehca_shca *shca = container_of(ah->pd->device, struct ehca_shca,
ib_device);
memset(&new_ehca_av, 0, sizeof(new_ehca_av));
new_ehca_av.sl = ah_attr->sl;
new_ehca_av.dlid = ah_attr->dlid;
new_ehca_av.slid_path_bits = ah_attr->src_path_bits;
new_ehca_av.ipd = ah_attr->static_rate;
new_ehca_av.lnh = EHCA_BMASK_SET(GRH_FLAG_MASK,
(ah_attr->ah_flags & IB_AH_GRH) > 0);
new_ehca_av.grh.word_0 = EHCA_BMASK_SET(GRH_TCLASS_MASK,
ah_attr->grh.traffic_class);
new_ehca_av.grh.word_0 |= EHCA_BMASK_SET(GRH_FLOWLABEL_MASK,
ah_attr->grh.flow_label);
new_ehca_av.grh.word_0 |= EHCA_BMASK_SET(GRH_HOPLIMIT_MASK,
ah_attr->grh.hop_limit);
new_ehca_av.grh.word_0 |= EHCA_BMASK_SET(GRH_NEXTHEADER_MASK, 0x1b);
/* set sgid in grh.word_1 */
if (ah_attr->ah_flags & IB_AH_GRH) {
int rc;
struct ib_port_attr port_attr;
union ib_gid gid;
memset(&port_attr, 0, sizeof(port_attr));
rc = ehca_query_port(ah->device, ah_attr->port_num,
&port_attr);
if (rc) { /* invalid port number */
ehca_err(ah->device, "Invalid port number "
"ehca_query_port() returned %x "
"ah=%p ah_attr=%p port_num=%x",
rc, ah, ah_attr, ah_attr->port_num);
return -EINVAL;
}
memset(&gid, 0, sizeof(gid));
rc = ehca_query_gid(ah->device,
ah_attr->port_num,
ah_attr->grh.sgid_index, &gid);
if (rc) {
ehca_err(ah->device, "Failed to retrieve sgid "
"ehca_query_gid() returned %x "
"ah=%p ah_attr=%p port_num=%x "
"sgid_index=%x",
rc, ah, ah_attr, ah_attr->port_num,
ah_attr->grh.sgid_index);
return -EINVAL;
}
memcpy(&new_ehca_av.grh.word_1, &gid, sizeof(gid));
}
new_ehca_av.pmtu = shca->max_mtu;
memcpy(&new_ehca_av.grh.word_3, &ah_attr->grh.dgid,
sizeof(ah_attr->grh.dgid));
av = container_of(ah, struct ehca_av, ib_ah);
av->av = new_ehca_av;
return 0;
}
int ehca_query_ah(struct ib_ah *ah, struct ib_ah_attr *ah_attr)
{
struct ehca_av *av = container_of(ah, struct ehca_av, ib_ah);
memcpy(&ah_attr->grh.dgid, &av->av.grh.word_3,
sizeof(ah_attr->grh.dgid));
ah_attr->sl = av->av.sl;
ah_attr->dlid = av->av.dlid;
ah_attr->src_path_bits = av->av.slid_path_bits;
ah_attr->static_rate = av->av.ipd;
ah_attr->ah_flags = EHCA_BMASK_GET(GRH_FLAG_MASK, av->av.lnh);
ah_attr->grh.traffic_class = EHCA_BMASK_GET(GRH_TCLASS_MASK,
av->av.grh.word_0);
ah_attr->grh.hop_limit = EHCA_BMASK_GET(GRH_HOPLIMIT_MASK,
av->av.grh.word_0);
ah_attr->grh.flow_label = EHCA_BMASK_GET(GRH_FLOWLABEL_MASK,
av->av.grh.word_0);
return 0;
}
int ehca_destroy_ah(struct ib_ah *ah)
{
kmem_cache_free(av_cache, container_of(ah, struct ehca_av, ib_ah));
return 0;
}
int ehca_init_av_cache(void)
{
av_cache = kmem_cache_create("ehca_cache_av",
sizeof(struct ehca_av), 0,
SLAB_HWCACHE_ALIGN,
NULL);
if (!av_cache)
return -ENOMEM;
return 0;
}
void ehca_cleanup_av_cache(void)
{
if (av_cache)
kmem_cache_destroy(av_cache);
}
| gpl-2.0 |
npe9/qemu-acid | linux-user/arm/nwfpe/fpa11_cprt.c | 180 | 7648 | /*
NetWinder Floating Point Emulator
(c) Rebel.COM, 1998,1999
(c) Philip Blundell, 1999
Direct questions, comments to Scott Bambrough <scottb@netwinder.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "fpa11.h"
#include "softfloat.h"
#include "fpopcode.h"
#include "fpa11.inl"
//#include "fpmodule.h"
//#include "fpmodule.inl"
unsigned int PerformFLT(const unsigned int opcode);
unsigned int PerformFIX(const unsigned int opcode);
static unsigned int
PerformComparison(const unsigned int opcode);
unsigned int EmulateCPRT(const unsigned int opcode)
{
unsigned int nRc = 1;
//printk("EmulateCPRT(0x%08x)\n",opcode);
if (opcode & 0x800000)
{
/* This is some variant of a comparison (PerformComparison will
sort out which one). Since most of the other CPRT
instructions are oddball cases of some sort or other it makes
sense to pull this out into a fast path. */
return PerformComparison(opcode);
}
/* Hint to GCC that we'd like a jump table rather than a load of CMPs */
switch ((opcode & 0x700000) >> 20)
{
case FLT_CODE >> 20: nRc = PerformFLT(opcode); break;
case FIX_CODE >> 20: nRc = PerformFIX(opcode); break;
case WFS_CODE >> 20: writeFPSR(readRegister(getRd(opcode))); break;
case RFS_CODE >> 20: writeRegister(getRd(opcode),readFPSR()); break;
#if 0 /* We currently have no use for the FPCR, so there's no point
in emulating it. */
case WFC_CODE >> 20: writeFPCR(readRegister(getRd(opcode)));
case RFC_CODE >> 20: writeRegister(getRd(opcode),readFPCR()); break;
#endif
default: nRc = 0;
}
return nRc;
}
unsigned int PerformFLT(const unsigned int opcode)
{
FPA11 *fpa11 = GET_FPA11();
unsigned int nRc = 1;
SetRoundingMode(opcode);
switch (opcode & MASK_ROUNDING_PRECISION)
{
case ROUND_SINGLE:
{
fpa11->fType[getFn(opcode)] = typeSingle;
fpa11->fpreg[getFn(opcode)].fSingle =
int32_to_float32(readRegister(getRd(opcode)), &fpa11->fp_status);
}
break;
case ROUND_DOUBLE:
{
fpa11->fType[getFn(opcode)] = typeDouble;
fpa11->fpreg[getFn(opcode)].fDouble =
int32_to_float64(readRegister(getRd(opcode)), &fpa11->fp_status);
}
break;
case ROUND_EXTENDED:
{
fpa11->fType[getFn(opcode)] = typeExtended;
fpa11->fpreg[getFn(opcode)].fExtended =
int32_to_floatx80(readRegister(getRd(opcode)), &fpa11->fp_status);
}
break;
default: nRc = 0;
}
return nRc;
}
unsigned int PerformFIX(const unsigned int opcode)
{
FPA11 *fpa11 = GET_FPA11();
unsigned int nRc = 1;
unsigned int Fn = getFm(opcode);
SetRoundingMode(opcode);
switch (fpa11->fType[Fn])
{
case typeSingle:
{
writeRegister(getRd(opcode),
float32_to_int32(fpa11->fpreg[Fn].fSingle, &fpa11->fp_status));
}
break;
case typeDouble:
{
//printf("F%d is 0x%" PRIx64 "\n",Fn,fpa11->fpreg[Fn].fDouble);
writeRegister(getRd(opcode),
float64_to_int32(fpa11->fpreg[Fn].fDouble, &fpa11->fp_status));
}
break;
case typeExtended:
{
writeRegister(getRd(opcode),
floatx80_to_int32(fpa11->fpreg[Fn].fExtended, &fpa11->fp_status));
}
break;
default: nRc = 0;
}
return nRc;
}
static __inline unsigned int
PerformComparisonOperation(floatx80 Fn, floatx80 Fm)
{
FPA11 *fpa11 = GET_FPA11();
unsigned int flags = 0;
/* test for less than condition */
if (floatx80_lt(Fn,Fm, &fpa11->fp_status))
{
flags |= CC_NEGATIVE;
}
/* test for equal condition */
if (floatx80_eq_quiet(Fn,Fm, &fpa11->fp_status))
{
flags |= CC_ZERO;
}
/* test for greater than or equal condition */
if (floatx80_lt(Fm,Fn, &fpa11->fp_status))
{
flags |= CC_CARRY;
}
writeConditionCodes(flags);
return 1;
}
/* This instruction sets the flags N, Z, C, V in the FPSR. */
static unsigned int PerformComparison(const unsigned int opcode)
{
FPA11 *fpa11 = GET_FPA11();
unsigned int Fn, Fm;
floatx80 rFn, rFm;
int e_flag = opcode & 0x400000; /* 1 if CxFE */
int n_flag = opcode & 0x200000; /* 1 if CNxx */
unsigned int flags = 0;
//printk("PerformComparison(0x%08x)\n",opcode);
Fn = getFn(opcode);
Fm = getFm(opcode);
/* Check for unordered condition and convert all operands to 80-bit
format.
?? Might be some mileage in avoiding this conversion if possible.
Eg, if both operands are 32-bit, detect this and do a 32-bit
comparison (cheaper than an 80-bit one). */
switch (fpa11->fType[Fn])
{
case typeSingle:
//printk("single.\n");
if (float32_is_any_nan(fpa11->fpreg[Fn].fSingle))
goto unordered;
rFn = float32_to_floatx80(fpa11->fpreg[Fn].fSingle, &fpa11->fp_status);
break;
case typeDouble:
//printk("double.\n");
if (float64_is_any_nan(fpa11->fpreg[Fn].fDouble))
goto unordered;
rFn = float64_to_floatx80(fpa11->fpreg[Fn].fDouble, &fpa11->fp_status);
break;
case typeExtended:
//printk("extended.\n");
if (floatx80_is_any_nan(fpa11->fpreg[Fn].fExtended))
goto unordered;
rFn = fpa11->fpreg[Fn].fExtended;
break;
default: return 0;
}
if (CONSTANT_FM(opcode))
{
//printk("Fm is a constant: #%d.\n",Fm);
rFm = getExtendedConstant(Fm);
if (floatx80_is_any_nan(rFm))
goto unordered;
}
else
{
//printk("Fm = r%d which contains a ",Fm);
switch (fpa11->fType[Fm])
{
case typeSingle:
//printk("single.\n");
if (float32_is_any_nan(fpa11->fpreg[Fm].fSingle))
goto unordered;
rFm = float32_to_floatx80(fpa11->fpreg[Fm].fSingle, &fpa11->fp_status);
break;
case typeDouble:
//printk("double.\n");
if (float64_is_any_nan(fpa11->fpreg[Fm].fDouble))
goto unordered;
rFm = float64_to_floatx80(fpa11->fpreg[Fm].fDouble, &fpa11->fp_status);
break;
case typeExtended:
//printk("extended.\n");
if (floatx80_is_any_nan(fpa11->fpreg[Fm].fExtended))
goto unordered;
rFm = fpa11->fpreg[Fm].fExtended;
break;
default: return 0;
}
}
if (n_flag)
{
rFm.high ^= 0x8000;
}
return PerformComparisonOperation(rFn,rFm);
unordered:
/* ?? The FPA data sheet is pretty vague about this, in particular
about whether the non-E comparisons can ever raise exceptions.
This implementation is based on a combination of what it says in
the data sheet, observation of how the Acorn emulator actually
behaves (and how programs expect it to) and guesswork. */
flags |= CC_OVERFLOW;
flags &= ~(CC_ZERO | CC_NEGATIVE);
if (BIT_AC & readFPSR()) flags |= CC_CARRY;
if (e_flag) float_raise(float_flag_invalid, &fpa11->fp_status);
writeConditionCodes(flags);
return 1;
}
| gpl-2.0 |
dolorespark/android_kernel_hisense_m470bsa | kernel/events/ring_buffer.c | 436 | 7969 | /*
* Performance events ring-buffer code:
*
* Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
* Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
* Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
* Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
*
* For licensing details see kernel-base/COPYING
*/
#include <linux/perf_event.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include "internal.h"
static bool perf_output_space(struct ring_buffer *rb, unsigned long tail,
unsigned long offset, unsigned long head)
{
unsigned long mask;
if (!rb->writable)
return true;
mask = perf_data_size(rb) - 1;
offset = (offset - tail) & mask;
head = (head - tail) & mask;
if ((int)(head - offset) < 0)
return false;
return true;
}
static void perf_output_wakeup(struct perf_output_handle *handle)
{
atomic_set(&handle->rb->poll, POLL_IN);
handle->event->pending_wakeup = 1;
irq_work_queue(&handle->event->pending);
}
/*
* We need to ensure a later event_id doesn't publish a head when a former
* event isn't done writing. However since we need to deal with NMIs we
* cannot fully serialize things.
*
* We only publish the head (and generate a wakeup) when the outer-most
* event completes.
*/
static void perf_output_get_handle(struct perf_output_handle *handle)
{
struct ring_buffer *rb = handle->rb;
preempt_disable();
local_inc(&rb->nest);
handle->wakeup = local_read(&rb->wakeup);
}
static void perf_output_put_handle(struct perf_output_handle *handle)
{
struct ring_buffer *rb = handle->rb;
unsigned long head;
again:
head = local_read(&rb->head);
/*
* IRQ/NMI can happen here, which means we can miss a head update.
*/
if (!local_dec_and_test(&rb->nest))
goto out;
/*
* Publish the known good head. Rely on the full barrier implied
* by atomic_dec_and_test() order the rb->head read and this
* write.
*/
rb->user_page->data_head = head;
/*
* Now check if we missed an update, rely on the (compiler)
* barrier in atomic_dec_and_test() to re-read rb->head.
*/
if (unlikely(head != local_read(&rb->head))) {
local_inc(&rb->nest);
goto again;
}
if (handle->wakeup != local_read(&rb->wakeup))
perf_output_wakeup(handle);
out:
preempt_enable();
}
int perf_output_begin(struct perf_output_handle *handle,
struct perf_event *event, unsigned int size)
{
struct ring_buffer *rb;
unsigned long tail, offset, head;
int have_lost;
struct perf_sample_data sample_data;
struct {
struct perf_event_header header;
u64 id;
u64 lost;
} lost_event;
rcu_read_lock();
/*
* For inherited events we send all the output towards the parent.
*/
if (event->parent)
event = event->parent;
rb = rcu_dereference(event->rb);
if (!rb)
goto out;
handle->rb = rb;
handle->event = event;
if (!rb->nr_pages)
goto out;
have_lost = local_read(&rb->lost);
if (have_lost) {
lost_event.header.size = sizeof(lost_event);
perf_event_header__init_id(&lost_event.header, &sample_data,
event);
size += lost_event.header.size;
}
perf_output_get_handle(handle);
do {
/*
* Userspace could choose to issue a mb() before updating the
* tail pointer. So that all reads will be completed before the
* write is issued.
*/
tail = ACCESS_ONCE(rb->user_page->data_tail);
smp_rmb();
offset = head = local_read(&rb->head);
head += size;
if (unlikely(!perf_output_space(rb, tail, offset, head)))
goto fail;
} while (local_cmpxchg(&rb->head, offset, head) != offset);
if (head - local_read(&rb->wakeup) > rb->watermark)
local_add(rb->watermark, &rb->wakeup);
handle->page = offset >> (PAGE_SHIFT + page_order(rb));
handle->page &= rb->nr_pages - 1;
handle->size = offset & ((PAGE_SIZE << page_order(rb)) - 1);
handle->addr = rb->data_pages[handle->page];
handle->addr += handle->size;
handle->size = (PAGE_SIZE << page_order(rb)) - handle->size;
if (have_lost) {
lost_event.header.type = PERF_RECORD_LOST;
lost_event.header.misc = 0;
lost_event.id = event->id;
lost_event.lost = local_xchg(&rb->lost, 0);
perf_output_put(handle, lost_event);
perf_event__output_id_sample(event, handle, &sample_data);
}
return 0;
fail:
local_inc(&rb->lost);
perf_output_put_handle(handle);
out:
rcu_read_unlock();
return -ENOSPC;
}
void perf_output_copy(struct perf_output_handle *handle,
const void *buf, unsigned int len)
{
__output_copy(handle, buf, len);
}
void perf_output_end(struct perf_output_handle *handle)
{
perf_output_put_handle(handle);
rcu_read_unlock();
}
static void
ring_buffer_init(struct ring_buffer *rb, long watermark, int flags)
{
long max_size = perf_data_size(rb);
if (watermark)
rb->watermark = min(max_size, watermark);
if (!rb->watermark)
rb->watermark = max_size / 2;
if (flags & RING_BUFFER_WRITABLE)
rb->writable = 1;
atomic_set(&rb->refcount, 1);
}
#ifndef CONFIG_PERF_USE_VMALLOC
/*
* Back perf_mmap() with regular GFP_KERNEL-0 pages.
*/
struct page *
perf_mmap_to_page(struct ring_buffer *rb, unsigned long pgoff)
{
if (pgoff > rb->nr_pages)
return NULL;
if (pgoff == 0)
return virt_to_page(rb->user_page);
return virt_to_page(rb->data_pages[pgoff - 1]);
}
static void *perf_mmap_alloc_page(int cpu)
{
struct page *page;
int node;
node = (cpu == -1) ? cpu : cpu_to_node(cpu);
page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
if (!page)
return NULL;
return page_address(page);
}
struct ring_buffer *rb_alloc(int nr_pages, long watermark, int cpu, int flags)
{
struct ring_buffer *rb;
unsigned long size;
int i;
size = sizeof(struct ring_buffer);
size += nr_pages * sizeof(void *);
rb = kzalloc(size, GFP_KERNEL);
if (!rb)
goto fail;
rb->user_page = perf_mmap_alloc_page(cpu);
if (!rb->user_page)
goto fail_user_page;
for (i = 0; i < nr_pages; i++) {
rb->data_pages[i] = perf_mmap_alloc_page(cpu);
if (!rb->data_pages[i])
goto fail_data_pages;
}
rb->nr_pages = nr_pages;
ring_buffer_init(rb, watermark, flags);
return rb;
fail_data_pages:
for (i--; i >= 0; i--)
free_page((unsigned long)rb->data_pages[i]);
free_page((unsigned long)rb->user_page);
fail_user_page:
kfree(rb);
fail:
return NULL;
}
static void perf_mmap_free_page(unsigned long addr)
{
struct page *page = virt_to_page((void *)addr);
page->mapping = NULL;
__free_page(page);
}
void rb_free(struct ring_buffer *rb)
{
int i;
perf_mmap_free_page((unsigned long)rb->user_page);
for (i = 0; i < rb->nr_pages; i++)
perf_mmap_free_page((unsigned long)rb->data_pages[i]);
kfree(rb);
}
#else
struct page *
perf_mmap_to_page(struct ring_buffer *rb, unsigned long pgoff)
{
if (pgoff > (1UL << page_order(rb)))
return NULL;
return vmalloc_to_page((void *)rb->user_page + pgoff * PAGE_SIZE);
}
static void perf_mmap_unmark_page(void *addr)
{
struct page *page = vmalloc_to_page(addr);
page->mapping = NULL;
}
static void rb_free_work(struct work_struct *work)
{
struct ring_buffer *rb;
void *base;
int i, nr;
rb = container_of(work, struct ring_buffer, work);
nr = 1 << page_order(rb);
base = rb->user_page;
for (i = 0; i < nr + 1; i++)
perf_mmap_unmark_page(base + (i * PAGE_SIZE));
vfree(base);
kfree(rb);
}
void rb_free(struct ring_buffer *rb)
{
schedule_work(&rb->work);
}
struct ring_buffer *rb_alloc(int nr_pages, long watermark, int cpu, int flags)
{
struct ring_buffer *rb;
unsigned long size;
void *all_buf;
size = sizeof(struct ring_buffer);
size += sizeof(void *);
rb = kzalloc(size, GFP_KERNEL);
if (!rb)
goto fail;
INIT_WORK(&rb->work, rb_free_work);
all_buf = vmalloc_user((nr_pages + 1) * PAGE_SIZE);
if (!all_buf)
goto fail_all_buf;
rb->user_page = all_buf;
rb->data_pages[0] = all_buf + PAGE_SIZE;
rb->page_order = ilog2(nr_pages);
rb->nr_pages = 1;
ring_buffer_init(rb, watermark, flags);
return rb;
fail_all_buf:
kfree(rb);
fail:
return NULL;
}
#endif
| gpl-2.0 |
DerArtem/android_kernel_dell_streak7 | drivers/isdn/hardware/mISDN/hfcsusb.c | 1204 | 56209 | /* hfcsusb.c
* mISDN driver for Colognechip HFC-S USB chip
*
* Copyright 2001 by Peter Sprenger (sprenger@moving-bytes.de)
* Copyright 2008 by Martin Bachem (info@bachem-it.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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.
*
*
* module params
* debug=<n>, default=0, with n=0xHHHHGGGG
* H - l1 driver flags described in hfcsusb.h
* G - common mISDN debug flags described at mISDNhw.h
*
* poll=<n>, default 128
* n : burst size of PH_DATA_IND at transparent rx data
*
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/usb.h>
#include <linux/mISDNhw.h>
#include <linux/slab.h>
#include "hfcsusb.h"
static const char *hfcsusb_rev = "Revision: 0.3.3 (socket), 2008-11-05";
static unsigned int debug;
static int poll = DEFAULT_TRANSP_BURST_SZ;
static LIST_HEAD(HFClist);
static DEFINE_RWLOCK(HFClock);
MODULE_AUTHOR("Martin Bachem");
MODULE_LICENSE("GPL");
module_param(debug, uint, S_IRUGO | S_IWUSR);
module_param(poll, int, 0);
static int hfcsusb_cnt;
/* some function prototypes */
static void hfcsusb_ph_command(struct hfcsusb *hw, u_char command);
static void release_hw(struct hfcsusb *hw);
static void reset_hfcsusb(struct hfcsusb *hw);
static void setPortMode(struct hfcsusb *hw);
static void hfcsusb_start_endpoint(struct hfcsusb *hw, int channel);
static void hfcsusb_stop_endpoint(struct hfcsusb *hw, int channel);
static int hfcsusb_setup_bch(struct bchannel *bch, int protocol);
static void deactivate_bchannel(struct bchannel *bch);
static void hfcsusb_ph_info(struct hfcsusb *hw);
/* start next background transfer for control channel */
static void
ctrl_start_transfer(struct hfcsusb *hw)
{
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s\n", hw->name, __func__);
if (hw->ctrl_cnt) {
hw->ctrl_urb->pipe = hw->ctrl_out_pipe;
hw->ctrl_urb->setup_packet = (u_char *)&hw->ctrl_write;
hw->ctrl_urb->transfer_buffer = NULL;
hw->ctrl_urb->transfer_buffer_length = 0;
hw->ctrl_write.wIndex =
cpu_to_le16(hw->ctrl_buff[hw->ctrl_out_idx].hfcs_reg);
hw->ctrl_write.wValue =
cpu_to_le16(hw->ctrl_buff[hw->ctrl_out_idx].reg_val);
usb_submit_urb(hw->ctrl_urb, GFP_ATOMIC);
}
}
/*
* queue a control transfer request to write HFC-S USB
* chip register using CTRL resuest queue
*/
static int write_reg(struct hfcsusb *hw, __u8 reg, __u8 val)
{
struct ctrl_buf *buf;
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s reg(0x%02x) val(0x%02x)\n",
hw->name, __func__, reg, val);
spin_lock(&hw->ctrl_lock);
if (hw->ctrl_cnt >= HFC_CTRL_BUFSIZE) {
spin_unlock(&hw->ctrl_lock);
return 1;
}
buf = &hw->ctrl_buff[hw->ctrl_in_idx];
buf->hfcs_reg = reg;
buf->reg_val = val;
if (++hw->ctrl_in_idx >= HFC_CTRL_BUFSIZE)
hw->ctrl_in_idx = 0;
if (++hw->ctrl_cnt == 1)
ctrl_start_transfer(hw);
spin_unlock(&hw->ctrl_lock);
return 0;
}
/* control completion routine handling background control cmds */
static void
ctrl_complete(struct urb *urb)
{
struct hfcsusb *hw = (struct hfcsusb *) urb->context;
struct ctrl_buf *buf;
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s\n", hw->name, __func__);
urb->dev = hw->dev;
if (hw->ctrl_cnt) {
buf = &hw->ctrl_buff[hw->ctrl_out_idx];
hw->ctrl_cnt--; /* decrement actual count */
if (++hw->ctrl_out_idx >= HFC_CTRL_BUFSIZE)
hw->ctrl_out_idx = 0; /* pointer wrap */
ctrl_start_transfer(hw); /* start next transfer */
}
}
/* handle LED bits */
static void
set_led_bit(struct hfcsusb *hw, signed short led_bits, int set_on)
{
if (set_on) {
if (led_bits < 0)
hw->led_state &= ~abs(led_bits);
else
hw->led_state |= led_bits;
} else {
if (led_bits < 0)
hw->led_state |= abs(led_bits);
else
hw->led_state &= ~led_bits;
}
}
/* handle LED requests */
static void
handle_led(struct hfcsusb *hw, int event)
{
struct hfcsusb_vdata *driver_info = (struct hfcsusb_vdata *)
hfcsusb_idtab[hw->vend_idx].driver_info;
__u8 tmpled;
if (driver_info->led_scheme == LED_OFF)
return;
tmpled = hw->led_state;
switch (event) {
case LED_POWER_ON:
set_led_bit(hw, driver_info->led_bits[0], 1);
set_led_bit(hw, driver_info->led_bits[1], 0);
set_led_bit(hw, driver_info->led_bits[2], 0);
set_led_bit(hw, driver_info->led_bits[3], 0);
break;
case LED_POWER_OFF:
set_led_bit(hw, driver_info->led_bits[0], 0);
set_led_bit(hw, driver_info->led_bits[1], 0);
set_led_bit(hw, driver_info->led_bits[2], 0);
set_led_bit(hw, driver_info->led_bits[3], 0);
break;
case LED_S0_ON:
set_led_bit(hw, driver_info->led_bits[1], 1);
break;
case LED_S0_OFF:
set_led_bit(hw, driver_info->led_bits[1], 0);
break;
case LED_B1_ON:
set_led_bit(hw, driver_info->led_bits[2], 1);
break;
case LED_B1_OFF:
set_led_bit(hw, driver_info->led_bits[2], 0);
break;
case LED_B2_ON:
set_led_bit(hw, driver_info->led_bits[3], 1);
break;
case LED_B2_OFF:
set_led_bit(hw, driver_info->led_bits[3], 0);
break;
}
if (hw->led_state != tmpled) {
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s reg(0x%02x) val(x%02x)\n",
hw->name, __func__,
HFCUSB_P_DATA, hw->led_state);
write_reg(hw, HFCUSB_P_DATA, hw->led_state);
}
}
/*
* Layer2 -> Layer 1 Bchannel data
*/
static int
hfcusb_l2l1B(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct bchannel *bch = container_of(ch, struct bchannel, ch);
struct hfcsusb *hw = bch->hw;
int ret = -EINVAL;
struct mISDNhead *hh = mISDN_HEAD_P(skb);
u_long flags;
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s\n", hw->name, __func__);
switch (hh->prim) {
case PH_DATA_REQ:
spin_lock_irqsave(&hw->lock, flags);
ret = bchannel_senddata(bch, skb);
spin_unlock_irqrestore(&hw->lock, flags);
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s PH_DATA_REQ ret(%i)\n",
hw->name, __func__, ret);
if (ret > 0) {
/*
* other l1 drivers don't send early confirms on
* transp data, but hfcsusb does because tx_next
* skb is needed in tx_iso_complete()
*/
queue_ch_frame(ch, PH_DATA_CNF, hh->id, NULL);
ret = 0;
}
return ret;
case PH_ACTIVATE_REQ:
if (!test_and_set_bit(FLG_ACTIVE, &bch->Flags)) {
hfcsusb_start_endpoint(hw, bch->nr);
ret = hfcsusb_setup_bch(bch, ch->protocol);
} else
ret = 0;
if (!ret)
_queue_data(ch, PH_ACTIVATE_IND, MISDN_ID_ANY,
0, NULL, GFP_KERNEL);
break;
case PH_DEACTIVATE_REQ:
deactivate_bchannel(bch);
_queue_data(ch, PH_DEACTIVATE_IND, MISDN_ID_ANY,
0, NULL, GFP_KERNEL);
ret = 0;
break;
}
if (!ret)
dev_kfree_skb(skb);
return ret;
}
/*
* send full D/B channel status information
* as MPH_INFORMATION_IND
*/
static void
hfcsusb_ph_info(struct hfcsusb *hw)
{
struct ph_info *phi;
struct dchannel *dch = &hw->dch;
int i;
phi = kzalloc(sizeof(struct ph_info) +
dch->dev.nrbchan * sizeof(struct ph_info_ch), GFP_ATOMIC);
phi->dch.ch.protocol = hw->protocol;
phi->dch.ch.Flags = dch->Flags;
phi->dch.state = dch->state;
phi->dch.num_bch = dch->dev.nrbchan;
for (i = 0; i < dch->dev.nrbchan; i++) {
phi->bch[i].protocol = hw->bch[i].ch.protocol;
phi->bch[i].Flags = hw->bch[i].Flags;
}
_queue_data(&dch->dev.D, MPH_INFORMATION_IND, MISDN_ID_ANY,
sizeof(struct ph_info_dch) + dch->dev.nrbchan *
sizeof(struct ph_info_ch), phi, GFP_ATOMIC);
}
/*
* Layer2 -> Layer 1 Dchannel data
*/
static int
hfcusb_l2l1D(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct mISDNdevice *dev = container_of(ch, struct mISDNdevice, D);
struct dchannel *dch = container_of(dev, struct dchannel, dev);
struct mISDNhead *hh = mISDN_HEAD_P(skb);
struct hfcsusb *hw = dch->hw;
int ret = -EINVAL;
u_long flags;
switch (hh->prim) {
case PH_DATA_REQ:
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s: PH_DATA_REQ\n",
hw->name, __func__);
spin_lock_irqsave(&hw->lock, flags);
ret = dchannel_senddata(dch, skb);
spin_unlock_irqrestore(&hw->lock, flags);
if (ret > 0) {
ret = 0;
queue_ch_frame(ch, PH_DATA_CNF, hh->id, NULL);
}
break;
case PH_ACTIVATE_REQ:
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s: PH_ACTIVATE_REQ %s\n",
hw->name, __func__,
(hw->protocol == ISDN_P_NT_S0) ? "NT" : "TE");
if (hw->protocol == ISDN_P_NT_S0) {
ret = 0;
if (test_bit(FLG_ACTIVE, &dch->Flags)) {
_queue_data(&dch->dev.D,
PH_ACTIVATE_IND, MISDN_ID_ANY, 0,
NULL, GFP_ATOMIC);
} else {
hfcsusb_ph_command(hw,
HFC_L1_ACTIVATE_NT);
test_and_set_bit(FLG_L2_ACTIVATED,
&dch->Flags);
}
} else {
hfcsusb_ph_command(hw, HFC_L1_ACTIVATE_TE);
ret = l1_event(dch->l1, hh->prim);
}
break;
case PH_DEACTIVATE_REQ:
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s: PH_DEACTIVATE_REQ\n",
hw->name, __func__);
test_and_clear_bit(FLG_L2_ACTIVATED, &dch->Flags);
if (hw->protocol == ISDN_P_NT_S0) {
hfcsusb_ph_command(hw, HFC_L1_DEACTIVATE_NT);
spin_lock_irqsave(&hw->lock, flags);
skb_queue_purge(&dch->squeue);
if (dch->tx_skb) {
dev_kfree_skb(dch->tx_skb);
dch->tx_skb = NULL;
}
dch->tx_idx = 0;
if (dch->rx_skb) {
dev_kfree_skb(dch->rx_skb);
dch->rx_skb = NULL;
}
test_and_clear_bit(FLG_TX_BUSY, &dch->Flags);
spin_unlock_irqrestore(&hw->lock, flags);
#ifdef FIXME
if (test_and_clear_bit(FLG_L1_BUSY, &dch->Flags))
dchannel_sched_event(&hc->dch, D_CLEARBUSY);
#endif
ret = 0;
} else
ret = l1_event(dch->l1, hh->prim);
break;
case MPH_INFORMATION_REQ:
hfcsusb_ph_info(hw);
ret = 0;
break;
}
return ret;
}
/*
* Layer 1 callback function
*/
static int
hfc_l1callback(struct dchannel *dch, u_int cmd)
{
struct hfcsusb *hw = dch->hw;
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s cmd 0x%x\n",
hw->name, __func__, cmd);
switch (cmd) {
case INFO3_P8:
case INFO3_P10:
case HW_RESET_REQ:
case HW_POWERUP_REQ:
break;
case HW_DEACT_REQ:
skb_queue_purge(&dch->squeue);
if (dch->tx_skb) {
dev_kfree_skb(dch->tx_skb);
dch->tx_skb = NULL;
}
dch->tx_idx = 0;
if (dch->rx_skb) {
dev_kfree_skb(dch->rx_skb);
dch->rx_skb = NULL;
}
test_and_clear_bit(FLG_TX_BUSY, &dch->Flags);
break;
case PH_ACTIVATE_IND:
test_and_set_bit(FLG_ACTIVE, &dch->Flags);
_queue_data(&dch->dev.D, cmd, MISDN_ID_ANY, 0, NULL,
GFP_ATOMIC);
break;
case PH_DEACTIVATE_IND:
test_and_clear_bit(FLG_ACTIVE, &dch->Flags);
_queue_data(&dch->dev.D, cmd, MISDN_ID_ANY, 0, NULL,
GFP_ATOMIC);
break;
default:
if (dch->debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: unknown cmd %x\n",
hw->name, __func__, cmd);
return -1;
}
hfcsusb_ph_info(hw);
return 0;
}
static int
open_dchannel(struct hfcsusb *hw, struct mISDNchannel *ch,
struct channel_req *rq)
{
int err = 0;
if (debug & DEBUG_HW_OPEN)
printk(KERN_DEBUG "%s: %s: dev(%d) open addr(%i) from %p\n",
hw->name, __func__, hw->dch.dev.id, rq->adr.channel,
__builtin_return_address(0));
if (rq->protocol == ISDN_P_NONE)
return -EINVAL;
test_and_clear_bit(FLG_ACTIVE, &hw->dch.Flags);
test_and_clear_bit(FLG_ACTIVE, &hw->ech.Flags);
hfcsusb_start_endpoint(hw, HFC_CHAN_D);
/* E-Channel logging */
if (rq->adr.channel == 1) {
if (hw->fifos[HFCUSB_PCM_RX].pipe) {
hfcsusb_start_endpoint(hw, HFC_CHAN_E);
set_bit(FLG_ACTIVE, &hw->ech.Flags);
_queue_data(&hw->ech.dev.D, PH_ACTIVATE_IND,
MISDN_ID_ANY, 0, NULL, GFP_ATOMIC);
} else
return -EINVAL;
}
if (!hw->initdone) {
hw->protocol = rq->protocol;
if (rq->protocol == ISDN_P_TE_S0) {
err = create_l1(&hw->dch, hfc_l1callback);
if (err)
return err;
}
setPortMode(hw);
ch->protocol = rq->protocol;
hw->initdone = 1;
} else {
if (rq->protocol != ch->protocol)
return -EPROTONOSUPPORT;
}
if (((ch->protocol == ISDN_P_NT_S0) && (hw->dch.state == 3)) ||
((ch->protocol == ISDN_P_TE_S0) && (hw->dch.state == 7)))
_queue_data(ch, PH_ACTIVATE_IND, MISDN_ID_ANY,
0, NULL, GFP_KERNEL);
rq->ch = ch;
if (!try_module_get(THIS_MODULE))
printk(KERN_WARNING "%s: %s: cannot get module\n",
hw->name, __func__);
return 0;
}
static int
open_bchannel(struct hfcsusb *hw, struct channel_req *rq)
{
struct bchannel *bch;
if (rq->adr.channel > 2)
return -EINVAL;
if (rq->protocol == ISDN_P_NONE)
return -EINVAL;
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s B%i\n",
hw->name, __func__, rq->adr.channel);
bch = &hw->bch[rq->adr.channel - 1];
if (test_and_set_bit(FLG_OPEN, &bch->Flags))
return -EBUSY; /* b-channel can be only open once */
test_and_clear_bit(FLG_FILLEMPTY, &bch->Flags);
bch->ch.protocol = rq->protocol;
rq->ch = &bch->ch;
/* start USB endpoint for bchannel */
if (rq->adr.channel == 1)
hfcsusb_start_endpoint(hw, HFC_CHAN_B1);
else
hfcsusb_start_endpoint(hw, HFC_CHAN_B2);
if (!try_module_get(THIS_MODULE))
printk(KERN_WARNING "%s: %s:cannot get module\n",
hw->name, __func__);
return 0;
}
static int
channel_ctrl(struct hfcsusb *hw, struct mISDN_ctrl_req *cq)
{
int ret = 0;
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s op(0x%x) channel(0x%x)\n",
hw->name, __func__, (cq->op), (cq->channel));
switch (cq->op) {
case MISDN_CTRL_GETOP:
cq->op = MISDN_CTRL_LOOP | MISDN_CTRL_CONNECT |
MISDN_CTRL_DISCONNECT;
break;
default:
printk(KERN_WARNING "%s: %s: unknown Op %x\n",
hw->name, __func__, cq->op);
ret = -EINVAL;
break;
}
return ret;
}
/*
* device control function
*/
static int
hfc_dctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct mISDNdevice *dev = container_of(ch, struct mISDNdevice, D);
struct dchannel *dch = container_of(dev, struct dchannel, dev);
struct hfcsusb *hw = dch->hw;
struct channel_req *rq;
int err = 0;
if (dch->debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: cmd:%x %p\n",
hw->name, __func__, cmd, arg);
switch (cmd) {
case OPEN_CHANNEL:
rq = arg;
if ((rq->protocol == ISDN_P_TE_S0) ||
(rq->protocol == ISDN_P_NT_S0))
err = open_dchannel(hw, ch, rq);
else
err = open_bchannel(hw, rq);
if (!err)
hw->open++;
break;
case CLOSE_CHANNEL:
hw->open--;
if (debug & DEBUG_HW_OPEN)
printk(KERN_DEBUG
"%s: %s: dev(%d) close from %p (open %d)\n",
hw->name, __func__, hw->dch.dev.id,
__builtin_return_address(0), hw->open);
if (!hw->open) {
hfcsusb_stop_endpoint(hw, HFC_CHAN_D);
if (hw->fifos[HFCUSB_PCM_RX].pipe)
hfcsusb_stop_endpoint(hw, HFC_CHAN_E);
handle_led(hw, LED_POWER_ON);
}
module_put(THIS_MODULE);
break;
case CONTROL_CHANNEL:
err = channel_ctrl(hw, arg);
break;
default:
if (dch->debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: unknown command %x\n",
hw->name, __func__, cmd);
return -EINVAL;
}
return err;
}
/*
* S0 TE state change event handler
*/
static void
ph_state_te(struct dchannel *dch)
{
struct hfcsusb *hw = dch->hw;
if (debug & DEBUG_HW) {
if (dch->state <= HFC_MAX_TE_LAYER1_STATE)
printk(KERN_DEBUG "%s: %s: %s\n", hw->name, __func__,
HFC_TE_LAYER1_STATES[dch->state]);
else
printk(KERN_DEBUG "%s: %s: TE F%d\n",
hw->name, __func__, dch->state);
}
switch (dch->state) {
case 0:
l1_event(dch->l1, HW_RESET_IND);
break;
case 3:
l1_event(dch->l1, HW_DEACT_IND);
break;
case 5:
case 8:
l1_event(dch->l1, ANYSIGNAL);
break;
case 6:
l1_event(dch->l1, INFO2);
break;
case 7:
l1_event(dch->l1, INFO4_P8);
break;
}
if (dch->state == 7)
handle_led(hw, LED_S0_ON);
else
handle_led(hw, LED_S0_OFF);
}
/*
* S0 NT state change event handler
*/
static void
ph_state_nt(struct dchannel *dch)
{
struct hfcsusb *hw = dch->hw;
if (debug & DEBUG_HW) {
if (dch->state <= HFC_MAX_NT_LAYER1_STATE)
printk(KERN_DEBUG "%s: %s: %s\n",
hw->name, __func__,
HFC_NT_LAYER1_STATES[dch->state]);
else
printk(KERN_INFO DRIVER_NAME "%s: %s: NT G%d\n",
hw->name, __func__, dch->state);
}
switch (dch->state) {
case (1):
test_and_clear_bit(FLG_ACTIVE, &dch->Flags);
test_and_clear_bit(FLG_L2_ACTIVATED, &dch->Flags);
hw->nt_timer = 0;
hw->timers &= ~NT_ACTIVATION_TIMER;
handle_led(hw, LED_S0_OFF);
break;
case (2):
if (hw->nt_timer < 0) {
hw->nt_timer = 0;
hw->timers &= ~NT_ACTIVATION_TIMER;
hfcsusb_ph_command(dch->hw, HFC_L1_DEACTIVATE_NT);
} else {
hw->timers |= NT_ACTIVATION_TIMER;
hw->nt_timer = NT_T1_COUNT;
/* allow G2 -> G3 transition */
write_reg(hw, HFCUSB_STATES, 2 | HFCUSB_NT_G2_G3);
}
break;
case (3):
hw->nt_timer = 0;
hw->timers &= ~NT_ACTIVATION_TIMER;
test_and_set_bit(FLG_ACTIVE, &dch->Flags);
_queue_data(&dch->dev.D, PH_ACTIVATE_IND,
MISDN_ID_ANY, 0, NULL, GFP_ATOMIC);
handle_led(hw, LED_S0_ON);
break;
case (4):
hw->nt_timer = 0;
hw->timers &= ~NT_ACTIVATION_TIMER;
break;
default:
break;
}
hfcsusb_ph_info(hw);
}
static void
ph_state(struct dchannel *dch)
{
struct hfcsusb *hw = dch->hw;
if (hw->protocol == ISDN_P_NT_S0)
ph_state_nt(dch);
else if (hw->protocol == ISDN_P_TE_S0)
ph_state_te(dch);
}
/*
* disable/enable BChannel for desired protocoll
*/
static int
hfcsusb_setup_bch(struct bchannel *bch, int protocol)
{
struct hfcsusb *hw = bch->hw;
__u8 conhdlc, sctrl, sctrl_r;
if (debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: protocol %x-->%x B%d\n",
hw->name, __func__, bch->state, protocol,
bch->nr);
/* setup val for CON_HDLC */
conhdlc = 0;
if (protocol > ISDN_P_NONE)
conhdlc = 8; /* enable FIFO */
switch (protocol) {
case (-1): /* used for init */
bch->state = -1;
/* fall through */
case (ISDN_P_NONE):
if (bch->state == ISDN_P_NONE)
return 0; /* already in idle state */
bch->state = ISDN_P_NONE;
clear_bit(FLG_HDLC, &bch->Flags);
clear_bit(FLG_TRANSPARENT, &bch->Flags);
break;
case (ISDN_P_B_RAW):
conhdlc |= 2;
bch->state = protocol;
set_bit(FLG_TRANSPARENT, &bch->Flags);
break;
case (ISDN_P_B_HDLC):
bch->state = protocol;
set_bit(FLG_HDLC, &bch->Flags);
break;
default:
if (debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: prot not known %x\n",
hw->name, __func__, protocol);
return -ENOPROTOOPT;
}
if (protocol >= ISDN_P_NONE) {
write_reg(hw, HFCUSB_FIFO, (bch->nr == 1) ? 0 : 2);
write_reg(hw, HFCUSB_CON_HDLC, conhdlc);
write_reg(hw, HFCUSB_INC_RES_F, 2);
write_reg(hw, HFCUSB_FIFO, (bch->nr == 1) ? 1 : 3);
write_reg(hw, HFCUSB_CON_HDLC, conhdlc);
write_reg(hw, HFCUSB_INC_RES_F, 2);
sctrl = 0x40 + ((hw->protocol == ISDN_P_TE_S0) ? 0x00 : 0x04);
sctrl_r = 0x0;
if (test_bit(FLG_ACTIVE, &hw->bch[0].Flags)) {
sctrl |= 1;
sctrl_r |= 1;
}
if (test_bit(FLG_ACTIVE, &hw->bch[1].Flags)) {
sctrl |= 2;
sctrl_r |= 2;
}
write_reg(hw, HFCUSB_SCTRL, sctrl);
write_reg(hw, HFCUSB_SCTRL_R, sctrl_r);
if (protocol > ISDN_P_NONE)
handle_led(hw, (bch->nr == 1) ? LED_B1_ON : LED_B2_ON);
else
handle_led(hw, (bch->nr == 1) ? LED_B1_OFF :
LED_B2_OFF);
}
hfcsusb_ph_info(hw);
return 0;
}
static void
hfcsusb_ph_command(struct hfcsusb *hw, u_char command)
{
if (debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: %x\n",
hw->name, __func__, command);
switch (command) {
case HFC_L1_ACTIVATE_TE:
/* force sending sending INFO1 */
write_reg(hw, HFCUSB_STATES, 0x14);
/* start l1 activation */
write_reg(hw, HFCUSB_STATES, 0x04);
break;
case HFC_L1_FORCE_DEACTIVATE_TE:
write_reg(hw, HFCUSB_STATES, 0x10);
write_reg(hw, HFCUSB_STATES, 0x03);
break;
case HFC_L1_ACTIVATE_NT:
if (hw->dch.state == 3)
_queue_data(&hw->dch.dev.D, PH_ACTIVATE_IND,
MISDN_ID_ANY, 0, NULL, GFP_ATOMIC);
else
write_reg(hw, HFCUSB_STATES, HFCUSB_ACTIVATE |
HFCUSB_DO_ACTION | HFCUSB_NT_G2_G3);
break;
case HFC_L1_DEACTIVATE_NT:
write_reg(hw, HFCUSB_STATES,
HFCUSB_DO_ACTION);
break;
}
}
/*
* Layer 1 B-channel hardware access
*/
static int
channel_bctrl(struct bchannel *bch, struct mISDN_ctrl_req *cq)
{
int ret = 0;
switch (cq->op) {
case MISDN_CTRL_GETOP:
cq->op = MISDN_CTRL_FILL_EMPTY;
break;
case MISDN_CTRL_FILL_EMPTY: /* fill fifo, if empty */
test_and_set_bit(FLG_FILLEMPTY, &bch->Flags);
if (debug & DEBUG_HW_OPEN)
printk(KERN_DEBUG "%s: FILL_EMPTY request (nr=%d "
"off=%d)\n", __func__, bch->nr, !!cq->p1);
break;
default:
printk(KERN_WARNING "%s: unknown Op %x\n", __func__, cq->op);
ret = -EINVAL;
break;
}
return ret;
}
/* collect data from incoming interrupt or isochron USB data */
static void
hfcsusb_rx_frame(struct usb_fifo *fifo, __u8 *data, unsigned int len,
int finish)
{
struct hfcsusb *hw = fifo->hw;
struct sk_buff *rx_skb = NULL;
int maxlen = 0;
int fifon = fifo->fifonum;
int i;
int hdlc = 0;
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s: fifo(%i) len(%i) "
"dch(%p) bch(%p) ech(%p)\n",
hw->name, __func__, fifon, len,
fifo->dch, fifo->bch, fifo->ech);
if (!len)
return;
if ((!!fifo->dch + !!fifo->bch + !!fifo->ech) != 1) {
printk(KERN_DEBUG "%s: %s: undefined channel\n",
hw->name, __func__);
return;
}
spin_lock(&hw->lock);
if (fifo->dch) {
rx_skb = fifo->dch->rx_skb;
maxlen = fifo->dch->maxlen;
hdlc = 1;
}
if (fifo->bch) {
rx_skb = fifo->bch->rx_skb;
maxlen = fifo->bch->maxlen;
hdlc = test_bit(FLG_HDLC, &fifo->bch->Flags);
}
if (fifo->ech) {
rx_skb = fifo->ech->rx_skb;
maxlen = fifo->ech->maxlen;
hdlc = 1;
}
if (!rx_skb) {
rx_skb = mI_alloc_skb(maxlen, GFP_ATOMIC);
if (rx_skb) {
if (fifo->dch)
fifo->dch->rx_skb = rx_skb;
if (fifo->bch)
fifo->bch->rx_skb = rx_skb;
if (fifo->ech)
fifo->ech->rx_skb = rx_skb;
skb_trim(rx_skb, 0);
} else {
printk(KERN_DEBUG "%s: %s: No mem for rx_skb\n",
hw->name, __func__);
spin_unlock(&hw->lock);
return;
}
}
if (fifo->dch || fifo->ech) {
/* D/E-Channel SKB range check */
if ((rx_skb->len + len) >= MAX_DFRAME_LEN_L1) {
printk(KERN_DEBUG "%s: %s: sbk mem exceeded "
"for fifo(%d) HFCUSB_D_RX\n",
hw->name, __func__, fifon);
skb_trim(rx_skb, 0);
spin_unlock(&hw->lock);
return;
}
} else if (fifo->bch) {
/* B-Channel SKB range check */
if ((rx_skb->len + len) >= (MAX_BCH_SIZE + 3)) {
printk(KERN_DEBUG "%s: %s: sbk mem exceeded "
"for fifo(%d) HFCUSB_B_RX\n",
hw->name, __func__, fifon);
skb_trim(rx_skb, 0);
spin_unlock(&hw->lock);
return;
}
}
memcpy(skb_put(rx_skb, len), data, len);
if (hdlc) {
/* we have a complete hdlc packet */
if (finish) {
if ((rx_skb->len > 3) &&
(!(rx_skb->data[rx_skb->len - 1]))) {
if (debug & DBG_HFC_FIFO_VERBOSE) {
printk(KERN_DEBUG "%s: %s: fifon(%i)"
" new RX len(%i): ",
hw->name, __func__, fifon,
rx_skb->len);
i = 0;
while (i < rx_skb->len)
printk("%02x ",
rx_skb->data[i++]);
printk("\n");
}
/* remove CRC & status */
skb_trim(rx_skb, rx_skb->len - 3);
if (fifo->dch)
recv_Dchannel(fifo->dch);
if (fifo->bch)
recv_Bchannel(fifo->bch, MISDN_ID_ANY);
if (fifo->ech)
recv_Echannel(fifo->ech,
&hw->dch);
} else {
if (debug & DBG_HFC_FIFO_VERBOSE) {
printk(KERN_DEBUG
"%s: CRC or minlen ERROR fifon(%i) "
"RX len(%i): ",
hw->name, fifon, rx_skb->len);
i = 0;
while (i < rx_skb->len)
printk("%02x ",
rx_skb->data[i++]);
printk("\n");
}
skb_trim(rx_skb, 0);
}
}
} else {
/* deliver transparent data to layer2 */
if (rx_skb->len >= poll)
recv_Bchannel(fifo->bch, MISDN_ID_ANY);
}
spin_unlock(&hw->lock);
}
static void
fill_isoc_urb(struct urb *urb, struct usb_device *dev, unsigned int pipe,
void *buf, int num_packets, int packet_size, int interval,
usb_complete_t complete, void *context)
{
int k;
usb_fill_bulk_urb(urb, dev, pipe, buf, packet_size * num_packets,
complete, context);
urb->number_of_packets = num_packets;
urb->transfer_flags = URB_ISO_ASAP;
urb->actual_length = 0;
urb->interval = interval;
for (k = 0; k < num_packets; k++) {
urb->iso_frame_desc[k].offset = packet_size * k;
urb->iso_frame_desc[k].length = packet_size;
urb->iso_frame_desc[k].actual_length = 0;
}
}
/* receive completion routine for all ISO tx fifos */
static void
rx_iso_complete(struct urb *urb)
{
struct iso_urb *context_iso_urb = (struct iso_urb *) urb->context;
struct usb_fifo *fifo = context_iso_urb->owner_fifo;
struct hfcsusb *hw = fifo->hw;
int k, len, errcode, offset, num_isoc_packets, fifon, maxlen,
status, iso_status, i;
__u8 *buf;
static __u8 eof[8];
__u8 s0_state;
fifon = fifo->fifonum;
status = urb->status;
spin_lock(&hw->lock);
if (fifo->stop_gracefull) {
fifo->stop_gracefull = 0;
fifo->active = 0;
spin_unlock(&hw->lock);
return;
}
spin_unlock(&hw->lock);
/*
* ISO transfer only partially completed,
* look at individual frame status for details
*/
if (status == -EXDEV) {
if (debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: with -EXDEV "
"urb->status %d, fifonum %d\n",
hw->name, __func__, status, fifon);
/* clear status, so go on with ISO transfers */
status = 0;
}
s0_state = 0;
if (fifo->active && !status) {
num_isoc_packets = iso_packets[fifon];
maxlen = fifo->usb_packet_maxlen;
for (k = 0; k < num_isoc_packets; ++k) {
len = urb->iso_frame_desc[k].actual_length;
offset = urb->iso_frame_desc[k].offset;
buf = context_iso_urb->buffer + offset;
iso_status = urb->iso_frame_desc[k].status;
if (iso_status && (debug & DBG_HFC_FIFO_VERBOSE)) {
printk(KERN_DEBUG "%s: %s: "
"ISO packet %i, status: %i\n",
hw->name, __func__, k, iso_status);
}
/* USB data log for every D ISO in */
if ((fifon == HFCUSB_D_RX) &&
(debug & DBG_HFC_USB_VERBOSE)) {
printk(KERN_DEBUG
"%s: %s: %d (%d/%d) len(%d) ",
hw->name, __func__, urb->start_frame,
k, num_isoc_packets-1,
len);
for (i = 0; i < len; i++)
printk("%x ", buf[i]);
printk("\n");
}
if (!iso_status) {
if (fifo->last_urblen != maxlen) {
/*
* save fifo fill-level threshold bits
* to use them later in TX ISO URB
* completions
*/
hw->threshold_mask = buf[1];
if (fifon == HFCUSB_D_RX)
s0_state = (buf[0] >> 4);
eof[fifon] = buf[0] & 1;
if (len > 2)
hfcsusb_rx_frame(fifo, buf + 2,
len - 2, (len < maxlen)
? eof[fifon] : 0);
} else
hfcsusb_rx_frame(fifo, buf, len,
(len < maxlen) ?
eof[fifon] : 0);
fifo->last_urblen = len;
}
}
/* signal S0 layer1 state change */
if ((s0_state) && (hw->initdone) &&
(s0_state != hw->dch.state)) {
hw->dch.state = s0_state;
schedule_event(&hw->dch, FLG_PHCHANGE);
}
fill_isoc_urb(urb, fifo->hw->dev, fifo->pipe,
context_iso_urb->buffer, num_isoc_packets,
fifo->usb_packet_maxlen, fifo->intervall,
(usb_complete_t)rx_iso_complete, urb->context);
errcode = usb_submit_urb(urb, GFP_ATOMIC);
if (errcode < 0) {
if (debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: error submitting "
"ISO URB: %d\n",
hw->name, __func__, errcode);
}
} else {
if (status && (debug & DBG_HFC_URB_INFO))
printk(KERN_DEBUG "%s: %s: rx_iso_complete : "
"urb->status %d, fifonum %d\n",
hw->name, __func__, status, fifon);
}
}
/* receive completion routine for all interrupt rx fifos */
static void
rx_int_complete(struct urb *urb)
{
int len, status, i;
__u8 *buf, maxlen, fifon;
struct usb_fifo *fifo = (struct usb_fifo *) urb->context;
struct hfcsusb *hw = fifo->hw;
static __u8 eof[8];
spin_lock(&hw->lock);
if (fifo->stop_gracefull) {
fifo->stop_gracefull = 0;
fifo->active = 0;
spin_unlock(&hw->lock);
return;
}
spin_unlock(&hw->lock);
fifon = fifo->fifonum;
if ((!fifo->active) || (urb->status)) {
if (debug & DBG_HFC_URB_ERROR)
printk(KERN_DEBUG
"%s: %s: RX-Fifo %i is going down (%i)\n",
hw->name, __func__, fifon, urb->status);
fifo->urb->interval = 0; /* cancel automatic rescheduling */
return;
}
len = urb->actual_length;
buf = fifo->buffer;
maxlen = fifo->usb_packet_maxlen;
/* USB data log for every D INT in */
if ((fifon == HFCUSB_D_RX) && (debug & DBG_HFC_USB_VERBOSE)) {
printk(KERN_DEBUG "%s: %s: D RX INT len(%d) ",
hw->name, __func__, len);
for (i = 0; i < len; i++)
printk("%02x ", buf[i]);
printk("\n");
}
if (fifo->last_urblen != fifo->usb_packet_maxlen) {
/* the threshold mask is in the 2nd status byte */
hw->threshold_mask = buf[1];
/* signal S0 layer1 state change */
if (hw->initdone && ((buf[0] >> 4) != hw->dch.state)) {
hw->dch.state = (buf[0] >> 4);
schedule_event(&hw->dch, FLG_PHCHANGE);
}
eof[fifon] = buf[0] & 1;
/* if we have more than the 2 status bytes -> collect data */
if (len > 2)
hfcsusb_rx_frame(fifo, buf + 2,
urb->actual_length - 2,
(len < maxlen) ? eof[fifon] : 0);
} else {
hfcsusb_rx_frame(fifo, buf, urb->actual_length,
(len < maxlen) ? eof[fifon] : 0);
}
fifo->last_urblen = urb->actual_length;
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status) {
if (debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: error resubmitting USB\n",
hw->name, __func__);
}
}
/* transmit completion routine for all ISO tx fifos */
static void
tx_iso_complete(struct urb *urb)
{
struct iso_urb *context_iso_urb = (struct iso_urb *) urb->context;
struct usb_fifo *fifo = context_iso_urb->owner_fifo;
struct hfcsusb *hw = fifo->hw;
struct sk_buff *tx_skb;
int k, tx_offset, num_isoc_packets, sink, remain, current_len,
errcode, hdlc, i;
int *tx_idx;
int frame_complete, fifon, status;
__u8 threshbit;
spin_lock(&hw->lock);
if (fifo->stop_gracefull) {
fifo->stop_gracefull = 0;
fifo->active = 0;
spin_unlock(&hw->lock);
return;
}
if (fifo->dch) {
tx_skb = fifo->dch->tx_skb;
tx_idx = &fifo->dch->tx_idx;
hdlc = 1;
} else if (fifo->bch) {
tx_skb = fifo->bch->tx_skb;
tx_idx = &fifo->bch->tx_idx;
hdlc = test_bit(FLG_HDLC, &fifo->bch->Flags);
} else {
printk(KERN_DEBUG "%s: %s: neither BCH nor DCH\n",
hw->name, __func__);
spin_unlock(&hw->lock);
return;
}
fifon = fifo->fifonum;
status = urb->status;
tx_offset = 0;
/*
* ISO transfer only partially completed,
* look at individual frame status for details
*/
if (status == -EXDEV) {
if (debug & DBG_HFC_URB_ERROR)
printk(KERN_DEBUG "%s: %s: "
"-EXDEV (%i) fifon (%d)\n",
hw->name, __func__, status, fifon);
/* clear status, so go on with ISO transfers */
status = 0;
}
if (fifo->active && !status) {
/* is FifoFull-threshold set for our channel? */
threshbit = (hw->threshold_mask & (1 << fifon));
num_isoc_packets = iso_packets[fifon];
/* predict dataflow to avoid fifo overflow */
if (fifon >= HFCUSB_D_TX)
sink = (threshbit) ? SINK_DMIN : SINK_DMAX;
else
sink = (threshbit) ? SINK_MIN : SINK_MAX;
fill_isoc_urb(urb, fifo->hw->dev, fifo->pipe,
context_iso_urb->buffer, num_isoc_packets,
fifo->usb_packet_maxlen, fifo->intervall,
(usb_complete_t)tx_iso_complete, urb->context);
memset(context_iso_urb->buffer, 0,
sizeof(context_iso_urb->buffer));
frame_complete = 0;
for (k = 0; k < num_isoc_packets; ++k) {
/* analyze tx success of previous ISO packets */
if (debug & DBG_HFC_URB_ERROR) {
errcode = urb->iso_frame_desc[k].status;
if (errcode) {
printk(KERN_DEBUG "%s: %s: "
"ISO packet %i, status: %i\n",
hw->name, __func__, k, errcode);
}
}
/* Generate next ISO Packets */
if (tx_skb)
remain = tx_skb->len - *tx_idx;
else
remain = 0;
if (remain > 0) {
fifo->bit_line -= sink;
current_len = (0 - fifo->bit_line) / 8;
if (current_len > 14)
current_len = 14;
if (current_len < 0)
current_len = 0;
if (remain < current_len)
current_len = remain;
/* how much bit do we put on the line? */
fifo->bit_line += current_len * 8;
context_iso_urb->buffer[tx_offset] = 0;
if (current_len == remain) {
if (hdlc) {
/* signal frame completion */
context_iso_urb->
buffer[tx_offset] = 1;
/* add 2 byte flags and 16bit
* CRC at end of ISDN frame */
fifo->bit_line += 32;
}
frame_complete = 1;
}
/* copy tx data to iso-urb buffer */
memcpy(context_iso_urb->buffer + tx_offset + 1,
(tx_skb->data + *tx_idx), current_len);
*tx_idx += current_len;
urb->iso_frame_desc[k].offset = tx_offset;
urb->iso_frame_desc[k].length = current_len + 1;
/* USB data log for every D ISO out */
if ((fifon == HFCUSB_D_RX) &&
(debug & DBG_HFC_USB_VERBOSE)) {
printk(KERN_DEBUG
"%s: %s (%d/%d) offs(%d) len(%d) ",
hw->name, __func__,
k, num_isoc_packets-1,
urb->iso_frame_desc[k].offset,
urb->iso_frame_desc[k].length);
for (i = urb->iso_frame_desc[k].offset;
i < (urb->iso_frame_desc[k].offset
+ urb->iso_frame_desc[k].length);
i++)
printk("%x ",
context_iso_urb->buffer[i]);
printk(" skb->len(%i) tx-idx(%d)\n",
tx_skb->len, *tx_idx);
}
tx_offset += (current_len + 1);
} else {
urb->iso_frame_desc[k].offset = tx_offset++;
urb->iso_frame_desc[k].length = 1;
/* we lower data margin every msec */
fifo->bit_line -= sink;
if (fifo->bit_line < BITLINE_INF)
fifo->bit_line = BITLINE_INF;
}
if (frame_complete) {
frame_complete = 0;
if (debug & DBG_HFC_FIFO_VERBOSE) {
printk(KERN_DEBUG "%s: %s: "
"fifon(%i) new TX len(%i): ",
hw->name, __func__,
fifon, tx_skb->len);
i = 0;
while (i < tx_skb->len)
printk("%02x ",
tx_skb->data[i++]);
printk("\n");
}
dev_kfree_skb(tx_skb);
tx_skb = NULL;
if (fifo->dch && get_next_dframe(fifo->dch))
tx_skb = fifo->dch->tx_skb;
else if (fifo->bch &&
get_next_bframe(fifo->bch)) {
if (test_bit(FLG_TRANSPARENT,
&fifo->bch->Flags))
confirm_Bsend(fifo->bch);
tx_skb = fifo->bch->tx_skb;
}
}
}
errcode = usb_submit_urb(urb, GFP_ATOMIC);
if (errcode < 0) {
if (debug & DEBUG_HW)
printk(KERN_DEBUG
"%s: %s: error submitting ISO URB: %d \n",
hw->name, __func__, errcode);
}
/*
* abuse DChannel tx iso completion to trigger NT mode state
* changes tx_iso_complete is assumed to be called every
* fifo->intervall (ms)
*/
if ((fifon == HFCUSB_D_TX) && (hw->protocol == ISDN_P_NT_S0)
&& (hw->timers & NT_ACTIVATION_TIMER)) {
if ((--hw->nt_timer) < 0)
schedule_event(&hw->dch, FLG_PHCHANGE);
}
} else {
if (status && (debug & DBG_HFC_URB_ERROR))
printk(KERN_DEBUG "%s: %s: urb->status %s (%i)"
"fifonum=%d\n",
hw->name, __func__,
symbolic(urb_errlist, status), status, fifon);
}
spin_unlock(&hw->lock);
}
/*
* allocs urbs and start isoc transfer with two pending urbs to avoid
* gaps in the transfer chain
*/
static int
start_isoc_chain(struct usb_fifo *fifo, int num_packets_per_urb,
usb_complete_t complete, int packet_size)
{
struct hfcsusb *hw = fifo->hw;
int i, k, errcode;
if (debug)
printk(KERN_DEBUG "%s: %s: fifo %i\n",
hw->name, __func__, fifo->fifonum);
/* allocate Memory for Iso out Urbs */
for (i = 0; i < 2; i++) {
if (!(fifo->iso[i].urb)) {
fifo->iso[i].urb =
usb_alloc_urb(num_packets_per_urb, GFP_KERNEL);
if (!(fifo->iso[i].urb)) {
printk(KERN_DEBUG
"%s: %s: alloc urb for fifo %i failed",
hw->name, __func__, fifo->fifonum);
}
fifo->iso[i].owner_fifo = (struct usb_fifo *) fifo;
fifo->iso[i].indx = i;
/* Init the first iso */
if (ISO_BUFFER_SIZE >=
(fifo->usb_packet_maxlen *
num_packets_per_urb)) {
fill_isoc_urb(fifo->iso[i].urb,
fifo->hw->dev, fifo->pipe,
fifo->iso[i].buffer,
num_packets_per_urb,
fifo->usb_packet_maxlen,
fifo->intervall, complete,
&fifo->iso[i]);
memset(fifo->iso[i].buffer, 0,
sizeof(fifo->iso[i].buffer));
for (k = 0; k < num_packets_per_urb; k++) {
fifo->iso[i].urb->
iso_frame_desc[k].offset =
k * packet_size;
fifo->iso[i].urb->
iso_frame_desc[k].length =
packet_size;
}
} else {
printk(KERN_DEBUG
"%s: %s: ISO Buffer size to small!\n",
hw->name, __func__);
}
}
fifo->bit_line = BITLINE_INF;
errcode = usb_submit_urb(fifo->iso[i].urb, GFP_KERNEL);
fifo->active = (errcode >= 0) ? 1 : 0;
fifo->stop_gracefull = 0;
if (errcode < 0) {
printk(KERN_DEBUG "%s: %s: %s URB nr:%d\n",
hw->name, __func__,
symbolic(urb_errlist, errcode), i);
}
}
return fifo->active;
}
static void
stop_iso_gracefull(struct usb_fifo *fifo)
{
struct hfcsusb *hw = fifo->hw;
int i, timeout;
u_long flags;
for (i = 0; i < 2; i++) {
spin_lock_irqsave(&hw->lock, flags);
if (debug)
printk(KERN_DEBUG "%s: %s for fifo %i.%i\n",
hw->name, __func__, fifo->fifonum, i);
fifo->stop_gracefull = 1;
spin_unlock_irqrestore(&hw->lock, flags);
}
for (i = 0; i < 2; i++) {
timeout = 3;
while (fifo->stop_gracefull && timeout--)
schedule_timeout_interruptible((HZ/1000)*16);
if (debug && fifo->stop_gracefull)
printk(KERN_DEBUG "%s: ERROR %s for fifo %i.%i\n",
hw->name, __func__, fifo->fifonum, i);
}
}
static void
stop_int_gracefull(struct usb_fifo *fifo)
{
struct hfcsusb *hw = fifo->hw;
int timeout;
u_long flags;
spin_lock_irqsave(&hw->lock, flags);
if (debug)
printk(KERN_DEBUG "%s: %s for fifo %i\n",
hw->name, __func__, fifo->fifonum);
fifo->stop_gracefull = 1;
spin_unlock_irqrestore(&hw->lock, flags);
timeout = 3;
while (fifo->stop_gracefull && timeout--)
schedule_timeout_interruptible((HZ/1000)*3);
if (debug && fifo->stop_gracefull)
printk(KERN_DEBUG "%s: ERROR %s for fifo %i\n",
hw->name, __func__, fifo->fifonum);
}
/* start the interrupt transfer for the given fifo */
static void
start_int_fifo(struct usb_fifo *fifo)
{
struct hfcsusb *hw = fifo->hw;
int errcode;
if (debug)
printk(KERN_DEBUG "%s: %s: INT IN fifo:%d\n",
hw->name, __func__, fifo->fifonum);
if (!fifo->urb) {
fifo->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!fifo->urb)
return;
}
usb_fill_int_urb(fifo->urb, fifo->hw->dev, fifo->pipe,
fifo->buffer, fifo->usb_packet_maxlen,
(usb_complete_t)rx_int_complete, fifo, fifo->intervall);
fifo->active = 1;
fifo->stop_gracefull = 0;
errcode = usb_submit_urb(fifo->urb, GFP_KERNEL);
if (errcode) {
printk(KERN_DEBUG "%s: %s: submit URB: status:%i\n",
hw->name, __func__, errcode);
fifo->active = 0;
}
}
static void
setPortMode(struct hfcsusb *hw)
{
if (debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s %s\n", hw->name, __func__,
(hw->protocol == ISDN_P_TE_S0) ? "TE" : "NT");
if (hw->protocol == ISDN_P_TE_S0) {
write_reg(hw, HFCUSB_SCTRL, 0x40);
write_reg(hw, HFCUSB_SCTRL_E, 0x00);
write_reg(hw, HFCUSB_CLKDEL, CLKDEL_TE);
write_reg(hw, HFCUSB_STATES, 3 | 0x10);
write_reg(hw, HFCUSB_STATES, 3);
} else {
write_reg(hw, HFCUSB_SCTRL, 0x44);
write_reg(hw, HFCUSB_SCTRL_E, 0x09);
write_reg(hw, HFCUSB_CLKDEL, CLKDEL_NT);
write_reg(hw, HFCUSB_STATES, 1 | 0x10);
write_reg(hw, HFCUSB_STATES, 1);
}
}
static void
reset_hfcsusb(struct hfcsusb *hw)
{
struct usb_fifo *fifo;
int i;
if (debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s\n", hw->name, __func__);
/* do Chip reset */
write_reg(hw, HFCUSB_CIRM, 8);
/* aux = output, reset off */
write_reg(hw, HFCUSB_CIRM, 0x10);
/* set USB_SIZE to match the wMaxPacketSize for INT or BULK transfers */
write_reg(hw, HFCUSB_USB_SIZE, (hw->packet_size / 8) |
((hw->packet_size / 8) << 4));
/* set USB_SIZE_I to match the the wMaxPacketSize for ISO transfers */
write_reg(hw, HFCUSB_USB_SIZE_I, hw->iso_packet_size);
/* enable PCM/GCI master mode */
write_reg(hw, HFCUSB_MST_MODE1, 0); /* set default values */
write_reg(hw, HFCUSB_MST_MODE0, 1); /* enable master mode */
/* init the fifos */
write_reg(hw, HFCUSB_F_THRES,
(HFCUSB_TX_THRESHOLD / 8) | ((HFCUSB_RX_THRESHOLD / 8) << 4));
fifo = hw->fifos;
for (i = 0; i < HFCUSB_NUM_FIFOS; i++) {
write_reg(hw, HFCUSB_FIFO, i); /* select the desired fifo */
fifo[i].max_size =
(i <= HFCUSB_B2_RX) ? MAX_BCH_SIZE : MAX_DFRAME_LEN;
fifo[i].last_urblen = 0;
/* set 2 bit for D- & E-channel */
write_reg(hw, HFCUSB_HDLC_PAR, ((i <= HFCUSB_B2_RX) ? 0 : 2));
/* enable all fifos */
if (i == HFCUSB_D_TX)
write_reg(hw, HFCUSB_CON_HDLC,
(hw->protocol == ISDN_P_NT_S0) ? 0x08 : 0x09);
else
write_reg(hw, HFCUSB_CON_HDLC, 0x08);
write_reg(hw, HFCUSB_INC_RES_F, 2); /* reset the fifo */
}
write_reg(hw, HFCUSB_SCTRL_R, 0); /* disable both B receivers */
handle_led(hw, LED_POWER_ON);
}
/* start USB data pipes dependand on device's endpoint configuration */
static void
hfcsusb_start_endpoint(struct hfcsusb *hw, int channel)
{
/* quick check if endpoint already running */
if ((channel == HFC_CHAN_D) && (hw->fifos[HFCUSB_D_RX].active))
return;
if ((channel == HFC_CHAN_B1) && (hw->fifos[HFCUSB_B1_RX].active))
return;
if ((channel == HFC_CHAN_B2) && (hw->fifos[HFCUSB_B2_RX].active))
return;
if ((channel == HFC_CHAN_E) && (hw->fifos[HFCUSB_PCM_RX].active))
return;
/* start rx endpoints using USB INT IN method */
if (hw->cfg_used == CNF_3INT3ISO || hw->cfg_used == CNF_4INT3ISO)
start_int_fifo(hw->fifos + channel*2 + 1);
/* start rx endpoints using USB ISO IN method */
if (hw->cfg_used == CNF_3ISO3ISO || hw->cfg_used == CNF_4ISO3ISO) {
switch (channel) {
case HFC_CHAN_D:
start_isoc_chain(hw->fifos + HFCUSB_D_RX,
ISOC_PACKETS_D,
(usb_complete_t)rx_iso_complete,
16);
break;
case HFC_CHAN_E:
start_isoc_chain(hw->fifos + HFCUSB_PCM_RX,
ISOC_PACKETS_D,
(usb_complete_t)rx_iso_complete,
16);
break;
case HFC_CHAN_B1:
start_isoc_chain(hw->fifos + HFCUSB_B1_RX,
ISOC_PACKETS_B,
(usb_complete_t)rx_iso_complete,
16);
break;
case HFC_CHAN_B2:
start_isoc_chain(hw->fifos + HFCUSB_B2_RX,
ISOC_PACKETS_B,
(usb_complete_t)rx_iso_complete,
16);
break;
}
}
/* start tx endpoints using USB ISO OUT method */
switch (channel) {
case HFC_CHAN_D:
start_isoc_chain(hw->fifos + HFCUSB_D_TX,
ISOC_PACKETS_B,
(usb_complete_t)tx_iso_complete, 1);
break;
case HFC_CHAN_B1:
start_isoc_chain(hw->fifos + HFCUSB_B1_TX,
ISOC_PACKETS_D,
(usb_complete_t)tx_iso_complete, 1);
break;
case HFC_CHAN_B2:
start_isoc_chain(hw->fifos + HFCUSB_B2_TX,
ISOC_PACKETS_B,
(usb_complete_t)tx_iso_complete, 1);
break;
}
}
/* stop USB data pipes dependand on device's endpoint configuration */
static void
hfcsusb_stop_endpoint(struct hfcsusb *hw, int channel)
{
/* quick check if endpoint currently running */
if ((channel == HFC_CHAN_D) && (!hw->fifos[HFCUSB_D_RX].active))
return;
if ((channel == HFC_CHAN_B1) && (!hw->fifos[HFCUSB_B1_RX].active))
return;
if ((channel == HFC_CHAN_B2) && (!hw->fifos[HFCUSB_B2_RX].active))
return;
if ((channel == HFC_CHAN_E) && (!hw->fifos[HFCUSB_PCM_RX].active))
return;
/* rx endpoints using USB INT IN method */
if (hw->cfg_used == CNF_3INT3ISO || hw->cfg_used == CNF_4INT3ISO)
stop_int_gracefull(hw->fifos + channel*2 + 1);
/* rx endpoints using USB ISO IN method */
if (hw->cfg_used == CNF_3ISO3ISO || hw->cfg_used == CNF_4ISO3ISO)
stop_iso_gracefull(hw->fifos + channel*2 + 1);
/* tx endpoints using USB ISO OUT method */
if (channel != HFC_CHAN_E)
stop_iso_gracefull(hw->fifos + channel*2);
}
/* Hardware Initialization */
static int
setup_hfcsusb(struct hfcsusb *hw)
{
int err;
u_char b;
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s\n", hw->name, __func__);
/* check the chip id */
if (read_reg_atomic(hw, HFCUSB_CHIP_ID, &b) != 1) {
printk(KERN_DEBUG "%s: %s: cannot read chip id\n",
hw->name, __func__);
return 1;
}
if (b != HFCUSB_CHIPID) {
printk(KERN_DEBUG "%s: %s: Invalid chip id 0x%02x\n",
hw->name, __func__, b);
return 1;
}
/* first set the needed config, interface and alternate */
err = usb_set_interface(hw->dev, hw->if_used, hw->alt_used);
hw->led_state = 0;
/* init the background machinery for control requests */
hw->ctrl_read.bRequestType = 0xc0;
hw->ctrl_read.bRequest = 1;
hw->ctrl_read.wLength = cpu_to_le16(1);
hw->ctrl_write.bRequestType = 0x40;
hw->ctrl_write.bRequest = 0;
hw->ctrl_write.wLength = 0;
usb_fill_control_urb(hw->ctrl_urb, hw->dev, hw->ctrl_out_pipe,
(u_char *)&hw->ctrl_write, NULL, 0,
(usb_complete_t)ctrl_complete, hw);
reset_hfcsusb(hw);
return 0;
}
static void
release_hw(struct hfcsusb *hw)
{
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s\n", hw->name, __func__);
/*
* stop all endpoints gracefully
* TODO: mISDN_core should generate CLOSE_CHANNEL
* signals after calling mISDN_unregister_device()
*/
hfcsusb_stop_endpoint(hw, HFC_CHAN_D);
hfcsusb_stop_endpoint(hw, HFC_CHAN_B1);
hfcsusb_stop_endpoint(hw, HFC_CHAN_B2);
if (hw->fifos[HFCUSB_PCM_RX].pipe)
hfcsusb_stop_endpoint(hw, HFC_CHAN_E);
if (hw->protocol == ISDN_P_TE_S0)
l1_event(hw->dch.l1, CLOSE_CHANNEL);
mISDN_unregister_device(&hw->dch.dev);
mISDN_freebchannel(&hw->bch[1]);
mISDN_freebchannel(&hw->bch[0]);
mISDN_freedchannel(&hw->dch);
if (hw->ctrl_urb) {
usb_kill_urb(hw->ctrl_urb);
usb_free_urb(hw->ctrl_urb);
hw->ctrl_urb = NULL;
}
if (hw->intf)
usb_set_intfdata(hw->intf, NULL);
list_del(&hw->list);
kfree(hw);
hw = NULL;
}
static void
deactivate_bchannel(struct bchannel *bch)
{
struct hfcsusb *hw = bch->hw;
u_long flags;
if (bch->debug & DEBUG_HW)
printk(KERN_DEBUG "%s: %s: bch->nr(%i)\n",
hw->name, __func__, bch->nr);
spin_lock_irqsave(&hw->lock, flags);
mISDN_clear_bchannel(bch);
spin_unlock_irqrestore(&hw->lock, flags);
hfcsusb_setup_bch(bch, ISDN_P_NONE);
hfcsusb_stop_endpoint(hw, bch->nr);
}
/*
* Layer 1 B-channel hardware access
*/
static int
hfc_bctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct bchannel *bch = container_of(ch, struct bchannel, ch);
int ret = -EINVAL;
if (bch->debug & DEBUG_HW)
printk(KERN_DEBUG "%s: cmd:%x %p\n", __func__, cmd, arg);
switch (cmd) {
case HW_TESTRX_RAW:
case HW_TESTRX_HDLC:
case HW_TESTRX_OFF:
ret = -EINVAL;
break;
case CLOSE_CHANNEL:
test_and_clear_bit(FLG_OPEN, &bch->Flags);
if (test_bit(FLG_ACTIVE, &bch->Flags))
deactivate_bchannel(bch);
ch->protocol = ISDN_P_NONE;
ch->peer = NULL;
module_put(THIS_MODULE);
ret = 0;
break;
case CONTROL_CHANNEL:
ret = channel_bctrl(bch, arg);
break;
default:
printk(KERN_WARNING "%s: unknown prim(%x)\n",
__func__, cmd);
}
return ret;
}
static int
setup_instance(struct hfcsusb *hw, struct device *parent)
{
u_long flags;
int err, i;
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_DEBUG "%s: %s\n", hw->name, __func__);
spin_lock_init(&hw->ctrl_lock);
spin_lock_init(&hw->lock);
mISDN_initdchannel(&hw->dch, MAX_DFRAME_LEN_L1, ph_state);
hw->dch.debug = debug & 0xFFFF;
hw->dch.hw = hw;
hw->dch.dev.Dprotocols = (1 << ISDN_P_TE_S0) | (1 << ISDN_P_NT_S0);
hw->dch.dev.D.send = hfcusb_l2l1D;
hw->dch.dev.D.ctrl = hfc_dctrl;
/* enable E-Channel logging */
if (hw->fifos[HFCUSB_PCM_RX].pipe)
mISDN_initdchannel(&hw->ech, MAX_DFRAME_LEN_L1, NULL);
hw->dch.dev.Bprotocols = (1 << (ISDN_P_B_RAW & ISDN_P_B_MASK)) |
(1 << (ISDN_P_B_HDLC & ISDN_P_B_MASK));
hw->dch.dev.nrbchan = 2;
for (i = 0; i < 2; i++) {
hw->bch[i].nr = i + 1;
set_channelmap(i + 1, hw->dch.dev.channelmap);
hw->bch[i].debug = debug;
mISDN_initbchannel(&hw->bch[i], MAX_DATA_MEM);
hw->bch[i].hw = hw;
hw->bch[i].ch.send = hfcusb_l2l1B;
hw->bch[i].ch.ctrl = hfc_bctrl;
hw->bch[i].ch.nr = i + 1;
list_add(&hw->bch[i].ch.list, &hw->dch.dev.bchannels);
}
hw->fifos[HFCUSB_B1_TX].bch = &hw->bch[0];
hw->fifos[HFCUSB_B1_RX].bch = &hw->bch[0];
hw->fifos[HFCUSB_B2_TX].bch = &hw->bch[1];
hw->fifos[HFCUSB_B2_RX].bch = &hw->bch[1];
hw->fifos[HFCUSB_D_TX].dch = &hw->dch;
hw->fifos[HFCUSB_D_RX].dch = &hw->dch;
hw->fifos[HFCUSB_PCM_RX].ech = &hw->ech;
hw->fifos[HFCUSB_PCM_TX].ech = &hw->ech;
err = setup_hfcsusb(hw);
if (err)
goto out;
snprintf(hw->name, MISDN_MAX_IDLEN - 1, "%s.%d", DRIVER_NAME,
hfcsusb_cnt + 1);
printk(KERN_INFO "%s: registered as '%s'\n",
DRIVER_NAME, hw->name);
err = mISDN_register_device(&hw->dch.dev, parent, hw->name);
if (err)
goto out;
hfcsusb_cnt++;
write_lock_irqsave(&HFClock, flags);
list_add_tail(&hw->list, &HFClist);
write_unlock_irqrestore(&HFClock, flags);
return 0;
out:
mISDN_freebchannel(&hw->bch[1]);
mISDN_freebchannel(&hw->bch[0]);
mISDN_freedchannel(&hw->dch);
kfree(hw);
return err;
}
static int
hfcsusb_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct hfcsusb *hw;
struct usb_device *dev = interface_to_usbdev(intf);
struct usb_host_interface *iface = intf->cur_altsetting;
struct usb_host_interface *iface_used = NULL;
struct usb_host_endpoint *ep;
struct hfcsusb_vdata *driver_info;
int ifnum = iface->desc.bInterfaceNumber, i, idx, alt_idx,
probe_alt_setting, vend_idx, cfg_used, *vcf, attr, cfg_found,
ep_addr, cmptbl[16], small_match, iso_packet_size, packet_size,
alt_used = 0;
vend_idx = 0xffff;
for (i = 0; hfcsusb_idtab[i].idVendor; i++) {
if ((le16_to_cpu(dev->descriptor.idVendor)
== hfcsusb_idtab[i].idVendor) &&
(le16_to_cpu(dev->descriptor.idProduct)
== hfcsusb_idtab[i].idProduct)) {
vend_idx = i;
continue;
}
}
printk(KERN_DEBUG
"%s: interface(%d) actalt(%d) minor(%d) vend_idx(%d)\n",
__func__, ifnum, iface->desc.bAlternateSetting,
intf->minor, vend_idx);
if (vend_idx == 0xffff) {
printk(KERN_WARNING
"%s: no valid vendor found in USB descriptor\n",
__func__);
return -EIO;
}
/* if vendor and product ID is OK, start probing alternate settings */
alt_idx = 0;
small_match = -1;
/* default settings */
iso_packet_size = 16;
packet_size = 64;
while (alt_idx < intf->num_altsetting) {
iface = intf->altsetting + alt_idx;
probe_alt_setting = iface->desc.bAlternateSetting;
cfg_used = 0;
while (validconf[cfg_used][0]) {
cfg_found = 1;
vcf = validconf[cfg_used];
ep = iface->endpoint;
memcpy(cmptbl, vcf, 16 * sizeof(int));
/* check for all endpoints in this alternate setting */
for (i = 0; i < iface->desc.bNumEndpoints; i++) {
ep_addr = ep->desc.bEndpointAddress;
/* get endpoint base */
idx = ((ep_addr & 0x7f) - 1) * 2;
if (ep_addr & 0x80)
idx++;
attr = ep->desc.bmAttributes;
if (cmptbl[idx] != EP_NOP) {
if (cmptbl[idx] == EP_NUL)
cfg_found = 0;
if (attr == USB_ENDPOINT_XFER_INT
&& cmptbl[idx] == EP_INT)
cmptbl[idx] = EP_NUL;
if (attr == USB_ENDPOINT_XFER_BULK
&& cmptbl[idx] == EP_BLK)
cmptbl[idx] = EP_NUL;
if (attr == USB_ENDPOINT_XFER_ISOC
&& cmptbl[idx] == EP_ISO)
cmptbl[idx] = EP_NUL;
if (attr == USB_ENDPOINT_XFER_INT &&
ep->desc.bInterval < vcf[17]) {
cfg_found = 0;
}
}
ep++;
}
for (i = 0; i < 16; i++)
if (cmptbl[i] != EP_NOP && cmptbl[i] != EP_NUL)
cfg_found = 0;
if (cfg_found) {
if (small_match < cfg_used) {
small_match = cfg_used;
alt_used = probe_alt_setting;
iface_used = iface;
}
}
cfg_used++;
}
alt_idx++;
} /* (alt_idx < intf->num_altsetting) */
/* not found a valid USB Ta Endpoint config */
if (small_match == -1)
return -EIO;
iface = iface_used;
hw = kzalloc(sizeof(struct hfcsusb), GFP_KERNEL);
if (!hw)
return -ENOMEM; /* got no mem */
snprintf(hw->name, MISDN_MAX_IDLEN - 1, "%s", DRIVER_NAME);
ep = iface->endpoint;
vcf = validconf[small_match];
for (i = 0; i < iface->desc.bNumEndpoints; i++) {
struct usb_fifo *f;
ep_addr = ep->desc.bEndpointAddress;
/* get endpoint base */
idx = ((ep_addr & 0x7f) - 1) * 2;
if (ep_addr & 0x80)
idx++;
f = &hw->fifos[idx & 7];
/* init Endpoints */
if (vcf[idx] == EP_NOP || vcf[idx] == EP_NUL) {
ep++;
continue;
}
switch (ep->desc.bmAttributes) {
case USB_ENDPOINT_XFER_INT:
f->pipe = usb_rcvintpipe(dev,
ep->desc.bEndpointAddress);
f->usb_transfer_mode = USB_INT;
packet_size = le16_to_cpu(ep->desc.wMaxPacketSize);
break;
case USB_ENDPOINT_XFER_BULK:
if (ep_addr & 0x80)
f->pipe = usb_rcvbulkpipe(dev,
ep->desc.bEndpointAddress);
else
f->pipe = usb_sndbulkpipe(dev,
ep->desc.bEndpointAddress);
f->usb_transfer_mode = USB_BULK;
packet_size = le16_to_cpu(ep->desc.wMaxPacketSize);
break;
case USB_ENDPOINT_XFER_ISOC:
if (ep_addr & 0x80)
f->pipe = usb_rcvisocpipe(dev,
ep->desc.bEndpointAddress);
else
f->pipe = usb_sndisocpipe(dev,
ep->desc.bEndpointAddress);
f->usb_transfer_mode = USB_ISOC;
iso_packet_size = le16_to_cpu(ep->desc.wMaxPacketSize);
break;
default:
f->pipe = 0;
}
if (f->pipe) {
f->fifonum = idx & 7;
f->hw = hw;
f->usb_packet_maxlen =
le16_to_cpu(ep->desc.wMaxPacketSize);
f->intervall = ep->desc.bInterval;
}
ep++;
}
hw->dev = dev; /* save device */
hw->if_used = ifnum; /* save used interface */
hw->alt_used = alt_used; /* and alternate config */
hw->ctrl_paksize = dev->descriptor.bMaxPacketSize0; /* control size */
hw->cfg_used = vcf[16]; /* store used config */
hw->vend_idx = vend_idx; /* store found vendor */
hw->packet_size = packet_size;
hw->iso_packet_size = iso_packet_size;
/* create the control pipes needed for register access */
hw->ctrl_in_pipe = usb_rcvctrlpipe(hw->dev, 0);
hw->ctrl_out_pipe = usb_sndctrlpipe(hw->dev, 0);
hw->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
driver_info =
(struct hfcsusb_vdata *)hfcsusb_idtab[vend_idx].driver_info;
printk(KERN_DEBUG "%s: %s: detected \"%s\" (%s, if=%d alt=%d)\n",
hw->name, __func__, driver_info->vend_name,
conf_str[small_match], ifnum, alt_used);
if (setup_instance(hw, dev->dev.parent))
return -EIO;
hw->intf = intf;
usb_set_intfdata(hw->intf, hw);
return 0;
}
/* function called when an active device is removed */
static void
hfcsusb_disconnect(struct usb_interface *intf)
{
struct hfcsusb *hw = usb_get_intfdata(intf);
struct hfcsusb *next;
int cnt = 0;
printk(KERN_INFO "%s: device disconnected\n", hw->name);
handle_led(hw, LED_POWER_OFF);
release_hw(hw);
list_for_each_entry_safe(hw, next, &HFClist, list)
cnt++;
if (!cnt)
hfcsusb_cnt = 0;
usb_set_intfdata(intf, NULL);
}
static struct usb_driver hfcsusb_drv = {
.name = DRIVER_NAME,
.id_table = hfcsusb_idtab,
.probe = hfcsusb_probe,
.disconnect = hfcsusb_disconnect,
};
static int __init
hfcsusb_init(void)
{
printk(KERN_INFO DRIVER_NAME " driver Rev. %s debug(0x%x) poll(%i)\n",
hfcsusb_rev, debug, poll);
if (usb_register(&hfcsusb_drv)) {
printk(KERN_INFO DRIVER_NAME
": Unable to register hfcsusb module at usb stack\n");
return -ENODEV;
}
return 0;
}
static void __exit
hfcsusb_cleanup(void)
{
if (debug & DBG_HFC_CALL_TRACE)
printk(KERN_INFO DRIVER_NAME ": %s\n", __func__);
/* unregister Hardware */
usb_deregister(&hfcsusb_drv); /* release our driver */
}
module_init(hfcsusb_init);
module_exit(hfcsusb_cleanup);
| gpl-2.0 |
NovaFusion/twrp_kernel | drivers/char/ttyprintk.c | 1972 | 5337 | /*
* linux/drivers/char/ttyprintk.c
*
* Copyright (C) 2010 Samo Pogacnik
*
* This program is free software; you can redistribute it and/or modify
* it under the smems of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*/
/*
* This pseudo device allows user to make printk messages. It is possible
* to store "console" messages inline with kernel messages for better analyses
* of the boot process, for example.
*/
#include <linux/device.h>
#include <linux/serial.h>
#include <linux/tty.h>
struct ttyprintk_port {
struct tty_port port;
struct mutex port_write_mutex;
};
static struct ttyprintk_port tpk_port;
/*
* Our simple preformatting supports transparent output of (time-stamped)
* printk messages (also suitable for logging service):
* - any cr is replaced by nl
* - adds a ttyprintk source tag in front of each line
* - too long message is fragmeted, with '\'nl between fragments
* - TPK_STR_SIZE isn't really the write_room limiting factor, bcause
* it is emptied on the fly during preformatting.
*/
#define TPK_STR_SIZE 508 /* should be bigger then max expected line length */
#define TPK_MAX_ROOM 4096 /* we could assume 4K for instance */
static const char *tpk_tag = "[U] "; /* U for User */
static int tpk_curr;
static int tpk_printk(const unsigned char *buf, int count)
{
static char tmp[TPK_STR_SIZE + 4];
int i = tpk_curr;
if (buf == NULL) {
/* flush tmp[] */
if (tpk_curr > 0) {
/* non nl or cr terminated message - add nl */
tmp[tpk_curr + 0] = '\n';
tmp[tpk_curr + 1] = '\0';
printk(KERN_INFO "%s%s", tpk_tag, tmp);
tpk_curr = 0;
}
return i;
}
for (i = 0; i < count; i++) {
tmp[tpk_curr] = buf[i];
if (tpk_curr < TPK_STR_SIZE) {
switch (buf[i]) {
case '\r':
/* replace cr with nl */
tmp[tpk_curr + 0] = '\n';
tmp[tpk_curr + 1] = '\0';
printk(KERN_INFO "%s%s", tpk_tag, tmp);
tpk_curr = 0;
if (buf[i + 1] == '\n')
i++;
break;
case '\n':
tmp[tpk_curr + 1] = '\0';
printk(KERN_INFO "%s%s", tpk_tag, tmp);
tpk_curr = 0;
break;
default:
tpk_curr++;
}
} else {
/* end of tmp buffer reached: cut the message in two */
tmp[tpk_curr + 1] = '\\';
tmp[tpk_curr + 2] = '\n';
tmp[tpk_curr + 3] = '\0';
printk(KERN_INFO "%s%s", tpk_tag, tmp);
tpk_curr = 0;
}
}
return count;
}
/*
* TTY operations open function.
*/
static int tpk_open(struct tty_struct *tty, struct file *filp)
{
tty->driver_data = &tpk_port;
return tty_port_open(&tpk_port.port, tty, filp);
}
/*
* TTY operations close function.
*/
static void tpk_close(struct tty_struct *tty, struct file *filp)
{
struct ttyprintk_port *tpkp = tty->driver_data;
mutex_lock(&tpkp->port_write_mutex);
/* flush tpk_printk buffer */
tpk_printk(NULL, 0);
mutex_unlock(&tpkp->port_write_mutex);
tty_port_close(&tpkp->port, tty, filp);
}
/*
* TTY operations write function.
*/
static int tpk_write(struct tty_struct *tty,
const unsigned char *buf, int count)
{
struct ttyprintk_port *tpkp = tty->driver_data;
int ret;
/* exclusive use of tpk_printk within this tty */
mutex_lock(&tpkp->port_write_mutex);
ret = tpk_printk(buf, count);
mutex_unlock(&tpkp->port_write_mutex);
return ret;
}
/*
* TTY operations write_room function.
*/
static int tpk_write_room(struct tty_struct *tty)
{
return TPK_MAX_ROOM;
}
/*
* TTY operations ioctl function.
*/
static int tpk_ioctl(struct tty_struct *tty,
unsigned int cmd, unsigned long arg)
{
struct ttyprintk_port *tpkp = tty->driver_data;
if (!tpkp)
return -EINVAL;
switch (cmd) {
/* Stop TIOCCONS */
case TIOCCONS:
return -EOPNOTSUPP;
default:
return -ENOIOCTLCMD;
}
return 0;
}
static const struct tty_operations ttyprintk_ops = {
.open = tpk_open,
.close = tpk_close,
.write = tpk_write,
.write_room = tpk_write_room,
.ioctl = tpk_ioctl,
};
struct tty_port_operations null_ops = { };
static struct tty_driver *ttyprintk_driver;
static int __init ttyprintk_init(void)
{
int ret = -ENOMEM;
void *rp;
ttyprintk_driver = alloc_tty_driver(1);
if (!ttyprintk_driver)
return ret;
ttyprintk_driver->owner = THIS_MODULE;
ttyprintk_driver->driver_name = "ttyprintk";
ttyprintk_driver->name = "ttyprintk";
ttyprintk_driver->major = TTYAUX_MAJOR;
ttyprintk_driver->minor_start = 3;
ttyprintk_driver->num = 1;
ttyprintk_driver->type = TTY_DRIVER_TYPE_CONSOLE;
ttyprintk_driver->init_termios = tty_std_termios;
ttyprintk_driver->init_termios.c_oflag = OPOST | OCRNL | ONOCR | ONLRET;
ttyprintk_driver->flags = TTY_DRIVER_RESET_TERMIOS |
TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
tty_set_operations(ttyprintk_driver, &ttyprintk_ops);
ret = tty_register_driver(ttyprintk_driver);
if (ret < 0) {
printk(KERN_ERR "Couldn't register ttyprintk driver\n");
goto error;
}
/* create our unnumbered device */
rp = device_create(tty_class, NULL, MKDEV(TTYAUX_MAJOR, 3), NULL,
ttyprintk_driver->name);
if (IS_ERR(rp)) {
printk(KERN_ERR "Couldn't create ttyprintk device\n");
ret = PTR_ERR(rp);
goto error;
}
tty_port_init(&tpk_port.port);
tpk_port.port.ops = &null_ops;
mutex_init(&tpk_port.port_write_mutex);
return 0;
error:
put_tty_driver(ttyprintk_driver);
ttyprintk_driver = NULL;
return ret;
}
module_init(ttyprintk_init);
| gpl-2.0 |
thanhphat11/android_kernel_xiaomi_msm8996 | drivers/misc/sgi-xp/xpc_channel.c | 2228 | 28334 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (c) 2004-2009 Silicon Graphics, Inc. All Rights Reserved.
*/
/*
* Cross Partition Communication (XPC) channel support.
*
* This is the part of XPC that manages the channels and
* sends/receives messages across them to/from other partitions.
*
*/
#include <linux/device.h>
#include "xpc.h"
/*
* Process a connect message from a remote partition.
*
* Note: xpc_process_connect() is expecting to be called with the
* spin_lock_irqsave held and will leave it locked upon return.
*/
static void
xpc_process_connect(struct xpc_channel *ch, unsigned long *irq_flags)
{
enum xp_retval ret;
DBUG_ON(!spin_is_locked(&ch->lock));
if (!(ch->flags & XPC_C_OPENREQUEST) ||
!(ch->flags & XPC_C_ROPENREQUEST)) {
/* nothing more to do for now */
return;
}
DBUG_ON(!(ch->flags & XPC_C_CONNECTING));
if (!(ch->flags & XPC_C_SETUP)) {
spin_unlock_irqrestore(&ch->lock, *irq_flags);
ret = xpc_arch_ops.setup_msg_structures(ch);
spin_lock_irqsave(&ch->lock, *irq_flags);
if (ret != xpSuccess)
XPC_DISCONNECT_CHANNEL(ch, ret, irq_flags);
else
ch->flags |= XPC_C_SETUP;
if (ch->flags & XPC_C_DISCONNECTING)
return;
}
if (!(ch->flags & XPC_C_OPENREPLY)) {
ch->flags |= XPC_C_OPENREPLY;
xpc_arch_ops.send_chctl_openreply(ch, irq_flags);
}
if (!(ch->flags & XPC_C_ROPENREPLY))
return;
if (!(ch->flags & XPC_C_OPENCOMPLETE)) {
ch->flags |= (XPC_C_OPENCOMPLETE | XPC_C_CONNECTED);
xpc_arch_ops.send_chctl_opencomplete(ch, irq_flags);
}
if (!(ch->flags & XPC_C_ROPENCOMPLETE))
return;
dev_info(xpc_chan, "channel %d to partition %d connected\n",
ch->number, ch->partid);
ch->flags = (XPC_C_CONNECTED | XPC_C_SETUP); /* clear all else */
}
/*
* spin_lock_irqsave() is expected to be held on entry.
*/
static void
xpc_process_disconnect(struct xpc_channel *ch, unsigned long *irq_flags)
{
struct xpc_partition *part = &xpc_partitions[ch->partid];
u32 channel_was_connected = (ch->flags & XPC_C_WASCONNECTED);
DBUG_ON(!spin_is_locked(&ch->lock));
if (!(ch->flags & XPC_C_DISCONNECTING))
return;
DBUG_ON(!(ch->flags & XPC_C_CLOSEREQUEST));
/* make sure all activity has settled down first */
if (atomic_read(&ch->kthreads_assigned) > 0 ||
atomic_read(&ch->references) > 0) {
return;
}
DBUG_ON((ch->flags & XPC_C_CONNECTEDCALLOUT_MADE) &&
!(ch->flags & XPC_C_DISCONNECTINGCALLOUT_MADE));
if (part->act_state == XPC_P_AS_DEACTIVATING) {
/* can't proceed until the other side disengages from us */
if (xpc_arch_ops.partition_engaged(ch->partid))
return;
} else {
/* as long as the other side is up do the full protocol */
if (!(ch->flags & XPC_C_RCLOSEREQUEST))
return;
if (!(ch->flags & XPC_C_CLOSEREPLY)) {
ch->flags |= XPC_C_CLOSEREPLY;
xpc_arch_ops.send_chctl_closereply(ch, irq_flags);
}
if (!(ch->flags & XPC_C_RCLOSEREPLY))
return;
}
/* wake those waiting for notify completion */
if (atomic_read(&ch->n_to_notify) > 0) {
/* we do callout while holding ch->lock, callout can't block */
xpc_arch_ops.notify_senders_of_disconnect(ch);
}
/* both sides are disconnected now */
if (ch->flags & XPC_C_DISCONNECTINGCALLOUT_MADE) {
spin_unlock_irqrestore(&ch->lock, *irq_flags);
xpc_disconnect_callout(ch, xpDisconnected);
spin_lock_irqsave(&ch->lock, *irq_flags);
}
DBUG_ON(atomic_read(&ch->n_to_notify) != 0);
/* it's now safe to free the channel's message queues */
xpc_arch_ops.teardown_msg_structures(ch);
ch->func = NULL;
ch->key = NULL;
ch->entry_size = 0;
ch->local_nentries = 0;
ch->remote_nentries = 0;
ch->kthreads_assigned_limit = 0;
ch->kthreads_idle_limit = 0;
/*
* Mark the channel disconnected and clear all other flags, including
* XPC_C_SETUP (because of call to
* xpc_arch_ops.teardown_msg_structures()) but not including
* XPC_C_WDISCONNECT (if it was set).
*/
ch->flags = (XPC_C_DISCONNECTED | (ch->flags & XPC_C_WDISCONNECT));
atomic_dec(&part->nchannels_active);
if (channel_was_connected) {
dev_info(xpc_chan, "channel %d to partition %d disconnected, "
"reason=%d\n", ch->number, ch->partid, ch->reason);
}
if (ch->flags & XPC_C_WDISCONNECT) {
/* we won't lose the CPU since we're holding ch->lock */
complete(&ch->wdisconnect_wait);
} else if (ch->delayed_chctl_flags) {
if (part->act_state != XPC_P_AS_DEACTIVATING) {
/* time to take action on any delayed chctl flags */
spin_lock(&part->chctl_lock);
part->chctl.flags[ch->number] |=
ch->delayed_chctl_flags;
spin_unlock(&part->chctl_lock);
}
ch->delayed_chctl_flags = 0;
}
}
/*
* Process a change in the channel's remote connection state.
*/
static void
xpc_process_openclose_chctl_flags(struct xpc_partition *part, int ch_number,
u8 chctl_flags)
{
unsigned long irq_flags;
struct xpc_openclose_args *args =
&part->remote_openclose_args[ch_number];
struct xpc_channel *ch = &part->channels[ch_number];
enum xp_retval reason;
enum xp_retval ret;
int create_kthread = 0;
spin_lock_irqsave(&ch->lock, irq_flags);
again:
if ((ch->flags & XPC_C_DISCONNECTED) &&
(ch->flags & XPC_C_WDISCONNECT)) {
/*
* Delay processing chctl flags until thread waiting disconnect
* has had a chance to see that the channel is disconnected.
*/
ch->delayed_chctl_flags |= chctl_flags;
goto out;
}
if (chctl_flags & XPC_CHCTL_CLOSEREQUEST) {
dev_dbg(xpc_chan, "XPC_CHCTL_CLOSEREQUEST (reason=%d) received "
"from partid=%d, channel=%d\n", args->reason,
ch->partid, ch->number);
/*
* If RCLOSEREQUEST is set, we're probably waiting for
* RCLOSEREPLY. We should find it and a ROPENREQUEST packed
* with this RCLOSEREQUEST in the chctl_flags.
*/
if (ch->flags & XPC_C_RCLOSEREQUEST) {
DBUG_ON(!(ch->flags & XPC_C_DISCONNECTING));
DBUG_ON(!(ch->flags & XPC_C_CLOSEREQUEST));
DBUG_ON(!(ch->flags & XPC_C_CLOSEREPLY));
DBUG_ON(ch->flags & XPC_C_RCLOSEREPLY);
DBUG_ON(!(chctl_flags & XPC_CHCTL_CLOSEREPLY));
chctl_flags &= ~XPC_CHCTL_CLOSEREPLY;
ch->flags |= XPC_C_RCLOSEREPLY;
/* both sides have finished disconnecting */
xpc_process_disconnect(ch, &irq_flags);
DBUG_ON(!(ch->flags & XPC_C_DISCONNECTED));
goto again;
}
if (ch->flags & XPC_C_DISCONNECTED) {
if (!(chctl_flags & XPC_CHCTL_OPENREQUEST)) {
if (part->chctl.flags[ch_number] &
XPC_CHCTL_OPENREQUEST) {
DBUG_ON(ch->delayed_chctl_flags != 0);
spin_lock(&part->chctl_lock);
part->chctl.flags[ch_number] |=
XPC_CHCTL_CLOSEREQUEST;
spin_unlock(&part->chctl_lock);
}
goto out;
}
XPC_SET_REASON(ch, 0, 0);
ch->flags &= ~XPC_C_DISCONNECTED;
atomic_inc(&part->nchannels_active);
ch->flags |= (XPC_C_CONNECTING | XPC_C_ROPENREQUEST);
}
chctl_flags &= ~(XPC_CHCTL_OPENREQUEST | XPC_CHCTL_OPENREPLY |
XPC_CHCTL_OPENCOMPLETE);
/*
* The meaningful CLOSEREQUEST connection state fields are:
* reason = reason connection is to be closed
*/
ch->flags |= XPC_C_RCLOSEREQUEST;
if (!(ch->flags & XPC_C_DISCONNECTING)) {
reason = args->reason;
if (reason <= xpSuccess || reason > xpUnknownReason)
reason = xpUnknownReason;
else if (reason == xpUnregistering)
reason = xpOtherUnregistering;
XPC_DISCONNECT_CHANNEL(ch, reason, &irq_flags);
DBUG_ON(chctl_flags & XPC_CHCTL_CLOSEREPLY);
goto out;
}
xpc_process_disconnect(ch, &irq_flags);
}
if (chctl_flags & XPC_CHCTL_CLOSEREPLY) {
dev_dbg(xpc_chan, "XPC_CHCTL_CLOSEREPLY received from partid="
"%d, channel=%d\n", ch->partid, ch->number);
if (ch->flags & XPC_C_DISCONNECTED) {
DBUG_ON(part->act_state != XPC_P_AS_DEACTIVATING);
goto out;
}
DBUG_ON(!(ch->flags & XPC_C_CLOSEREQUEST));
if (!(ch->flags & XPC_C_RCLOSEREQUEST)) {
if (part->chctl.flags[ch_number] &
XPC_CHCTL_CLOSEREQUEST) {
DBUG_ON(ch->delayed_chctl_flags != 0);
spin_lock(&part->chctl_lock);
part->chctl.flags[ch_number] |=
XPC_CHCTL_CLOSEREPLY;
spin_unlock(&part->chctl_lock);
}
goto out;
}
ch->flags |= XPC_C_RCLOSEREPLY;
if (ch->flags & XPC_C_CLOSEREPLY) {
/* both sides have finished disconnecting */
xpc_process_disconnect(ch, &irq_flags);
}
}
if (chctl_flags & XPC_CHCTL_OPENREQUEST) {
dev_dbg(xpc_chan, "XPC_CHCTL_OPENREQUEST (entry_size=%d, "
"local_nentries=%d) received from partid=%d, "
"channel=%d\n", args->entry_size, args->local_nentries,
ch->partid, ch->number);
if (part->act_state == XPC_P_AS_DEACTIVATING ||
(ch->flags & XPC_C_ROPENREQUEST)) {
goto out;
}
if (ch->flags & (XPC_C_DISCONNECTING | XPC_C_WDISCONNECT)) {
ch->delayed_chctl_flags |= XPC_CHCTL_OPENREQUEST;
goto out;
}
DBUG_ON(!(ch->flags & (XPC_C_DISCONNECTED |
XPC_C_OPENREQUEST)));
DBUG_ON(ch->flags & (XPC_C_ROPENREQUEST | XPC_C_ROPENREPLY |
XPC_C_OPENREPLY | XPC_C_CONNECTED));
/*
* The meaningful OPENREQUEST connection state fields are:
* entry_size = size of channel's messages in bytes
* local_nentries = remote partition's local_nentries
*/
if (args->entry_size == 0 || args->local_nentries == 0) {
/* assume OPENREQUEST was delayed by mistake */
goto out;
}
ch->flags |= (XPC_C_ROPENREQUEST | XPC_C_CONNECTING);
ch->remote_nentries = args->local_nentries;
if (ch->flags & XPC_C_OPENREQUEST) {
if (args->entry_size != ch->entry_size) {
XPC_DISCONNECT_CHANNEL(ch, xpUnequalMsgSizes,
&irq_flags);
goto out;
}
} else {
ch->entry_size = args->entry_size;
XPC_SET_REASON(ch, 0, 0);
ch->flags &= ~XPC_C_DISCONNECTED;
atomic_inc(&part->nchannels_active);
}
xpc_process_connect(ch, &irq_flags);
}
if (chctl_flags & XPC_CHCTL_OPENREPLY) {
dev_dbg(xpc_chan, "XPC_CHCTL_OPENREPLY (local_msgqueue_pa="
"0x%lx, local_nentries=%d, remote_nentries=%d) "
"received from partid=%d, channel=%d\n",
args->local_msgqueue_pa, args->local_nentries,
args->remote_nentries, ch->partid, ch->number);
if (ch->flags & (XPC_C_DISCONNECTING | XPC_C_DISCONNECTED))
goto out;
if (!(ch->flags & XPC_C_OPENREQUEST)) {
XPC_DISCONNECT_CHANNEL(ch, xpOpenCloseError,
&irq_flags);
goto out;
}
DBUG_ON(!(ch->flags & XPC_C_ROPENREQUEST));
DBUG_ON(ch->flags & XPC_C_CONNECTED);
/*
* The meaningful OPENREPLY connection state fields are:
* local_msgqueue_pa = physical address of remote
* partition's local_msgqueue
* local_nentries = remote partition's local_nentries
* remote_nentries = remote partition's remote_nentries
*/
DBUG_ON(args->local_msgqueue_pa == 0);
DBUG_ON(args->local_nentries == 0);
DBUG_ON(args->remote_nentries == 0);
ret = xpc_arch_ops.save_remote_msgqueue_pa(ch,
args->local_msgqueue_pa);
if (ret != xpSuccess) {
XPC_DISCONNECT_CHANNEL(ch, ret, &irq_flags);
goto out;
}
ch->flags |= XPC_C_ROPENREPLY;
if (args->local_nentries < ch->remote_nentries) {
dev_dbg(xpc_chan, "XPC_CHCTL_OPENREPLY: new "
"remote_nentries=%d, old remote_nentries=%d, "
"partid=%d, channel=%d\n",
args->local_nentries, ch->remote_nentries,
ch->partid, ch->number);
ch->remote_nentries = args->local_nentries;
}
if (args->remote_nentries < ch->local_nentries) {
dev_dbg(xpc_chan, "XPC_CHCTL_OPENREPLY: new "
"local_nentries=%d, old local_nentries=%d, "
"partid=%d, channel=%d\n",
args->remote_nentries, ch->local_nentries,
ch->partid, ch->number);
ch->local_nentries = args->remote_nentries;
}
xpc_process_connect(ch, &irq_flags);
}
if (chctl_flags & XPC_CHCTL_OPENCOMPLETE) {
dev_dbg(xpc_chan, "XPC_CHCTL_OPENCOMPLETE received from "
"partid=%d, channel=%d\n", ch->partid, ch->number);
if (ch->flags & (XPC_C_DISCONNECTING | XPC_C_DISCONNECTED))
goto out;
if (!(ch->flags & XPC_C_OPENREQUEST) ||
!(ch->flags & XPC_C_OPENREPLY)) {
XPC_DISCONNECT_CHANNEL(ch, xpOpenCloseError,
&irq_flags);
goto out;
}
DBUG_ON(!(ch->flags & XPC_C_ROPENREQUEST));
DBUG_ON(!(ch->flags & XPC_C_ROPENREPLY));
DBUG_ON(!(ch->flags & XPC_C_CONNECTED));
ch->flags |= XPC_C_ROPENCOMPLETE;
xpc_process_connect(ch, &irq_flags);
create_kthread = 1;
}
out:
spin_unlock_irqrestore(&ch->lock, irq_flags);
if (create_kthread)
xpc_create_kthreads(ch, 1, 0);
}
/*
* Attempt to establish a channel connection to a remote partition.
*/
static enum xp_retval
xpc_connect_channel(struct xpc_channel *ch)
{
unsigned long irq_flags;
struct xpc_registration *registration = &xpc_registrations[ch->number];
if (mutex_trylock(®istration->mutex) == 0)
return xpRetry;
if (!XPC_CHANNEL_REGISTERED(ch->number)) {
mutex_unlock(®istration->mutex);
return xpUnregistered;
}
spin_lock_irqsave(&ch->lock, irq_flags);
DBUG_ON(ch->flags & XPC_C_CONNECTED);
DBUG_ON(ch->flags & XPC_C_OPENREQUEST);
if (ch->flags & XPC_C_DISCONNECTING) {
spin_unlock_irqrestore(&ch->lock, irq_flags);
mutex_unlock(®istration->mutex);
return ch->reason;
}
/* add info from the channel connect registration to the channel */
ch->kthreads_assigned_limit = registration->assigned_limit;
ch->kthreads_idle_limit = registration->idle_limit;
DBUG_ON(atomic_read(&ch->kthreads_assigned) != 0);
DBUG_ON(atomic_read(&ch->kthreads_idle) != 0);
DBUG_ON(atomic_read(&ch->kthreads_active) != 0);
ch->func = registration->func;
DBUG_ON(registration->func == NULL);
ch->key = registration->key;
ch->local_nentries = registration->nentries;
if (ch->flags & XPC_C_ROPENREQUEST) {
if (registration->entry_size != ch->entry_size) {
/* the local and remote sides aren't the same */
/*
* Because XPC_DISCONNECT_CHANNEL() can block we're
* forced to up the registration sema before we unlock
* the channel lock. But that's okay here because we're
* done with the part that required the registration
* sema. XPC_DISCONNECT_CHANNEL() requires that the
* channel lock be locked and will unlock and relock
* the channel lock as needed.
*/
mutex_unlock(®istration->mutex);
XPC_DISCONNECT_CHANNEL(ch, xpUnequalMsgSizes,
&irq_flags);
spin_unlock_irqrestore(&ch->lock, irq_flags);
return xpUnequalMsgSizes;
}
} else {
ch->entry_size = registration->entry_size;
XPC_SET_REASON(ch, 0, 0);
ch->flags &= ~XPC_C_DISCONNECTED;
atomic_inc(&xpc_partitions[ch->partid].nchannels_active);
}
mutex_unlock(®istration->mutex);
/* initiate the connection */
ch->flags |= (XPC_C_OPENREQUEST | XPC_C_CONNECTING);
xpc_arch_ops.send_chctl_openrequest(ch, &irq_flags);
xpc_process_connect(ch, &irq_flags);
spin_unlock_irqrestore(&ch->lock, irq_flags);
return xpSuccess;
}
void
xpc_process_sent_chctl_flags(struct xpc_partition *part)
{
unsigned long irq_flags;
union xpc_channel_ctl_flags chctl;
struct xpc_channel *ch;
int ch_number;
u32 ch_flags;
chctl.all_flags = xpc_arch_ops.get_chctl_all_flags(part);
/*
* Initiate channel connections for registered channels.
*
* For each connected channel that has pending messages activate idle
* kthreads and/or create new kthreads as needed.
*/
for (ch_number = 0; ch_number < part->nchannels; ch_number++) {
ch = &part->channels[ch_number];
/*
* Process any open or close related chctl flags, and then deal
* with connecting or disconnecting the channel as required.
*/
if (chctl.flags[ch_number] & XPC_OPENCLOSE_CHCTL_FLAGS) {
xpc_process_openclose_chctl_flags(part, ch_number,
chctl.flags[ch_number]);
}
ch_flags = ch->flags; /* need an atomic snapshot of flags */
if (ch_flags & XPC_C_DISCONNECTING) {
spin_lock_irqsave(&ch->lock, irq_flags);
xpc_process_disconnect(ch, &irq_flags);
spin_unlock_irqrestore(&ch->lock, irq_flags);
continue;
}
if (part->act_state == XPC_P_AS_DEACTIVATING)
continue;
if (!(ch_flags & XPC_C_CONNECTED)) {
if (!(ch_flags & XPC_C_OPENREQUEST)) {
DBUG_ON(ch_flags & XPC_C_SETUP);
(void)xpc_connect_channel(ch);
}
continue;
}
/*
* Process any message related chctl flags, this may involve
* the activation of kthreads to deliver any pending messages
* sent from the other partition.
*/
if (chctl.flags[ch_number] & XPC_MSG_CHCTL_FLAGS)
xpc_arch_ops.process_msg_chctl_flags(part, ch_number);
}
}
/*
* XPC's heartbeat code calls this function to inform XPC that a partition is
* going down. XPC responds by tearing down the XPartition Communication
* infrastructure used for the just downed partition.
*
* XPC's heartbeat code will never call this function and xpc_partition_up()
* at the same time. Nor will it ever make multiple calls to either function
* at the same time.
*/
void
xpc_partition_going_down(struct xpc_partition *part, enum xp_retval reason)
{
unsigned long irq_flags;
int ch_number;
struct xpc_channel *ch;
dev_dbg(xpc_chan, "deactivating partition %d, reason=%d\n",
XPC_PARTID(part), reason);
if (!xpc_part_ref(part)) {
/* infrastructure for this partition isn't currently set up */
return;
}
/* disconnect channels associated with the partition going down */
for (ch_number = 0; ch_number < part->nchannels; ch_number++) {
ch = &part->channels[ch_number];
xpc_msgqueue_ref(ch);
spin_lock_irqsave(&ch->lock, irq_flags);
XPC_DISCONNECT_CHANNEL(ch, reason, &irq_flags);
spin_unlock_irqrestore(&ch->lock, irq_flags);
xpc_msgqueue_deref(ch);
}
xpc_wakeup_channel_mgr(part);
xpc_part_deref(part);
}
/*
* Called by XP at the time of channel connection registration to cause
* XPC to establish connections to all currently active partitions.
*/
void
xpc_initiate_connect(int ch_number)
{
short partid;
struct xpc_partition *part;
struct xpc_channel *ch;
DBUG_ON(ch_number < 0 || ch_number >= XPC_MAX_NCHANNELS);
for (partid = 0; partid < xp_max_npartitions; partid++) {
part = &xpc_partitions[partid];
if (xpc_part_ref(part)) {
ch = &part->channels[ch_number];
/*
* Initiate the establishment of a connection on the
* newly registered channel to the remote partition.
*/
xpc_wakeup_channel_mgr(part);
xpc_part_deref(part);
}
}
}
void
xpc_connected_callout(struct xpc_channel *ch)
{
/* let the registerer know that a connection has been established */
if (ch->func != NULL) {
dev_dbg(xpc_chan, "ch->func() called, reason=xpConnected, "
"partid=%d, channel=%d\n", ch->partid, ch->number);
ch->func(xpConnected, ch->partid, ch->number,
(void *)(u64)ch->local_nentries, ch->key);
dev_dbg(xpc_chan, "ch->func() returned, reason=xpConnected, "
"partid=%d, channel=%d\n", ch->partid, ch->number);
}
}
/*
* Called by XP at the time of channel connection unregistration to cause
* XPC to teardown all current connections for the specified channel.
*
* Before returning xpc_initiate_disconnect() will wait until all connections
* on the specified channel have been closed/torndown. So the caller can be
* assured that they will not be receiving any more callouts from XPC to the
* function they registered via xpc_connect().
*
* Arguments:
*
* ch_number - channel # to unregister.
*/
void
xpc_initiate_disconnect(int ch_number)
{
unsigned long irq_flags;
short partid;
struct xpc_partition *part;
struct xpc_channel *ch;
DBUG_ON(ch_number < 0 || ch_number >= XPC_MAX_NCHANNELS);
/* initiate the channel disconnect for every active partition */
for (partid = 0; partid < xp_max_npartitions; partid++) {
part = &xpc_partitions[partid];
if (xpc_part_ref(part)) {
ch = &part->channels[ch_number];
xpc_msgqueue_ref(ch);
spin_lock_irqsave(&ch->lock, irq_flags);
if (!(ch->flags & XPC_C_DISCONNECTED)) {
ch->flags |= XPC_C_WDISCONNECT;
XPC_DISCONNECT_CHANNEL(ch, xpUnregistering,
&irq_flags);
}
spin_unlock_irqrestore(&ch->lock, irq_flags);
xpc_msgqueue_deref(ch);
xpc_part_deref(part);
}
}
xpc_disconnect_wait(ch_number);
}
/*
* To disconnect a channel, and reflect it back to all who may be waiting.
*
* An OPEN is not allowed until XPC_C_DISCONNECTING is cleared by
* xpc_process_disconnect(), and if set, XPC_C_WDISCONNECT is cleared by
* xpc_disconnect_wait().
*
* THE CHANNEL IS TO BE LOCKED BY THE CALLER AND WILL REMAIN LOCKED UPON RETURN.
*/
void
xpc_disconnect_channel(const int line, struct xpc_channel *ch,
enum xp_retval reason, unsigned long *irq_flags)
{
u32 channel_was_connected = (ch->flags & XPC_C_CONNECTED);
DBUG_ON(!spin_is_locked(&ch->lock));
if (ch->flags & (XPC_C_DISCONNECTING | XPC_C_DISCONNECTED))
return;
DBUG_ON(!(ch->flags & (XPC_C_CONNECTING | XPC_C_CONNECTED)));
dev_dbg(xpc_chan, "reason=%d, line=%d, partid=%d, channel=%d\n",
reason, line, ch->partid, ch->number);
XPC_SET_REASON(ch, reason, line);
ch->flags |= (XPC_C_CLOSEREQUEST | XPC_C_DISCONNECTING);
/* some of these may not have been set */
ch->flags &= ~(XPC_C_OPENREQUEST | XPC_C_OPENREPLY |
XPC_C_ROPENREQUEST | XPC_C_ROPENREPLY |
XPC_C_CONNECTING | XPC_C_CONNECTED);
xpc_arch_ops.send_chctl_closerequest(ch, irq_flags);
if (channel_was_connected)
ch->flags |= XPC_C_WASCONNECTED;
spin_unlock_irqrestore(&ch->lock, *irq_flags);
/* wake all idle kthreads so they can exit */
if (atomic_read(&ch->kthreads_idle) > 0) {
wake_up_all(&ch->idle_wq);
} else if ((ch->flags & XPC_C_CONNECTEDCALLOUT_MADE) &&
!(ch->flags & XPC_C_DISCONNECTINGCALLOUT)) {
/* start a kthread that will do the xpDisconnecting callout */
xpc_create_kthreads(ch, 1, 1);
}
/* wake those waiting to allocate an entry from the local msg queue */
if (atomic_read(&ch->n_on_msg_allocate_wq) > 0)
wake_up(&ch->msg_allocate_wq);
spin_lock_irqsave(&ch->lock, *irq_flags);
}
void
xpc_disconnect_callout(struct xpc_channel *ch, enum xp_retval reason)
{
/*
* Let the channel's registerer know that the channel is being
* disconnected. We don't want to do this if the registerer was never
* informed of a connection being made.
*/
if (ch->func != NULL) {
dev_dbg(xpc_chan, "ch->func() called, reason=%d, partid=%d, "
"channel=%d\n", reason, ch->partid, ch->number);
ch->func(reason, ch->partid, ch->number, NULL, ch->key);
dev_dbg(xpc_chan, "ch->func() returned, reason=%d, partid=%d, "
"channel=%d\n", reason, ch->partid, ch->number);
}
}
/*
* Wait for a message entry to become available for the specified channel,
* but don't wait any longer than 1 jiffy.
*/
enum xp_retval
xpc_allocate_msg_wait(struct xpc_channel *ch)
{
enum xp_retval ret;
DEFINE_WAIT(wait);
if (ch->flags & XPC_C_DISCONNECTING) {
DBUG_ON(ch->reason == xpInterrupted);
return ch->reason;
}
atomic_inc(&ch->n_on_msg_allocate_wq);
prepare_to_wait(&ch->msg_allocate_wq, &wait, TASK_INTERRUPTIBLE);
ret = schedule_timeout(1);
finish_wait(&ch->msg_allocate_wq, &wait);
atomic_dec(&ch->n_on_msg_allocate_wq);
if (ch->flags & XPC_C_DISCONNECTING) {
ret = ch->reason;
DBUG_ON(ch->reason == xpInterrupted);
} else if (ret == 0) {
ret = xpTimeout;
} else {
ret = xpInterrupted;
}
return ret;
}
/*
* Send a message that contains the user's payload on the specified channel
* connected to the specified partition.
*
* NOTE that this routine can sleep waiting for a message entry to become
* available. To not sleep, pass in the XPC_NOWAIT flag.
*
* Once sent, this routine will not wait for the message to be received, nor
* will notification be given when it does happen.
*
* Arguments:
*
* partid - ID of partition to which the channel is connected.
* ch_number - channel # to send message on.
* flags - see xp.h for valid flags.
* payload - pointer to the payload which is to be sent.
* payload_size - size of the payload in bytes.
*/
enum xp_retval
xpc_initiate_send(short partid, int ch_number, u32 flags, void *payload,
u16 payload_size)
{
struct xpc_partition *part = &xpc_partitions[partid];
enum xp_retval ret = xpUnknownReason;
dev_dbg(xpc_chan, "payload=0x%p, partid=%d, channel=%d\n", payload,
partid, ch_number);
DBUG_ON(partid < 0 || partid >= xp_max_npartitions);
DBUG_ON(ch_number < 0 || ch_number >= part->nchannels);
DBUG_ON(payload == NULL);
if (xpc_part_ref(part)) {
ret = xpc_arch_ops.send_payload(&part->channels[ch_number],
flags, payload, payload_size, 0, NULL, NULL);
xpc_part_deref(part);
}
return ret;
}
/*
* Send a message that contains the user's payload on the specified channel
* connected to the specified partition.
*
* NOTE that this routine can sleep waiting for a message entry to become
* available. To not sleep, pass in the XPC_NOWAIT flag.
*
* This routine will not wait for the message to be sent or received.
*
* Once the remote end of the channel has received the message, the function
* passed as an argument to xpc_initiate_send_notify() will be called. This
* allows the sender to free up or re-use any buffers referenced by the
* message, but does NOT mean the message has been processed at the remote
* end by a receiver.
*
* If this routine returns an error, the caller's function will NOT be called.
*
* Arguments:
*
* partid - ID of partition to which the channel is connected.
* ch_number - channel # to send message on.
* flags - see xp.h for valid flags.
* payload - pointer to the payload which is to be sent.
* payload_size - size of the payload in bytes.
* func - function to call with asynchronous notification of message
* receipt. THIS FUNCTION MUST BE NON-BLOCKING.
* key - user-defined key to be passed to the function when it's called.
*/
enum xp_retval
xpc_initiate_send_notify(short partid, int ch_number, u32 flags, void *payload,
u16 payload_size, xpc_notify_func func, void *key)
{
struct xpc_partition *part = &xpc_partitions[partid];
enum xp_retval ret = xpUnknownReason;
dev_dbg(xpc_chan, "payload=0x%p, partid=%d, channel=%d\n", payload,
partid, ch_number);
DBUG_ON(partid < 0 || partid >= xp_max_npartitions);
DBUG_ON(ch_number < 0 || ch_number >= part->nchannels);
DBUG_ON(payload == NULL);
DBUG_ON(func == NULL);
if (xpc_part_ref(part)) {
ret = xpc_arch_ops.send_payload(&part->channels[ch_number],
flags, payload, payload_size, XPC_N_CALL, func, key);
xpc_part_deref(part);
}
return ret;
}
/*
* Deliver a message's payload to its intended recipient.
*/
void
xpc_deliver_payload(struct xpc_channel *ch)
{
void *payload;
payload = xpc_arch_ops.get_deliverable_payload(ch);
if (payload != NULL) {
/*
* This ref is taken to protect the payload itself from being
* freed before the user is finished with it, which the user
* indicates by calling xpc_initiate_received().
*/
xpc_msgqueue_ref(ch);
atomic_inc(&ch->kthreads_active);
if (ch->func != NULL) {
dev_dbg(xpc_chan, "ch->func() called, payload=0x%p "
"partid=%d channel=%d\n", payload, ch->partid,
ch->number);
/* deliver the message to its intended recipient */
ch->func(xpMsgReceived, ch->partid, ch->number, payload,
ch->key);
dev_dbg(xpc_chan, "ch->func() returned, payload=0x%p "
"partid=%d channel=%d\n", payload, ch->partid,
ch->number);
}
atomic_dec(&ch->kthreads_active);
}
}
/*
* Acknowledge receipt of a delivered message's payload.
*
* This function, although called by users, does not call xpc_part_ref() to
* ensure that the partition infrastructure is in place. It relies on the
* fact that we called xpc_msgqueue_ref() in xpc_deliver_payload().
*
* Arguments:
*
* partid - ID of partition to which the channel is connected.
* ch_number - channel # message received on.
* payload - pointer to the payload area allocated via
* xpc_initiate_send() or xpc_initiate_send_notify().
*/
void
xpc_initiate_received(short partid, int ch_number, void *payload)
{
struct xpc_partition *part = &xpc_partitions[partid];
struct xpc_channel *ch;
DBUG_ON(partid < 0 || partid >= xp_max_npartitions);
DBUG_ON(ch_number < 0 || ch_number >= part->nchannels);
ch = &part->channels[ch_number];
xpc_arch_ops.received_payload(ch, payload);
/* the call to xpc_msgqueue_ref() was done by xpc_deliver_payload() */
xpc_msgqueue_deref(ch);
}
| gpl-2.0 |
lanniaoershi/android_kernel_oneplus_msm8994 | drivers/char/agp/ali-agp.c | 2484 | 10332 | /*
* ALi AGPGART routines.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/agp_backend.h>
#include <asm/page.h> /* PAGE_SIZE */
#include "agp.h"
#define ALI_AGPCTRL 0xb8
#define ALI_ATTBASE 0xbc
#define ALI_TLBCTRL 0xc0
#define ALI_TAGCTRL 0xc4
#define ALI_CACHE_FLUSH_CTRL 0xD0
#define ALI_CACHE_FLUSH_ADDR_MASK 0xFFFFF000
#define ALI_CACHE_FLUSH_EN 0x100
static int ali_fetch_size(void)
{
int i;
u32 temp;
struct aper_size_info_32 *values;
pci_read_config_dword(agp_bridge->dev, ALI_ATTBASE, &temp);
temp &= ~(0xfffffff0);
values = A_SIZE_32(agp_bridge->driver->aperture_sizes);
for (i = 0; i < agp_bridge->driver->num_aperture_sizes; i++) {
if (temp == values[i].size_value) {
agp_bridge->previous_size =
agp_bridge->current_size = (void *) (values + i);
agp_bridge->aperture_size_idx = i;
return values[i].size;
}
}
return 0;
}
static void ali_tlbflush(struct agp_memory *mem)
{
u32 temp;
pci_read_config_dword(agp_bridge->dev, ALI_TLBCTRL, &temp);
temp &= 0xfffffff0;
temp |= (1<<0 | 1<<1);
pci_write_config_dword(agp_bridge->dev, ALI_TAGCTRL, temp);
}
static void ali_cleanup(void)
{
struct aper_size_info_32 *previous_size;
u32 temp;
previous_size = A_SIZE_32(agp_bridge->previous_size);
pci_read_config_dword(agp_bridge->dev, ALI_TLBCTRL, &temp);
// clear tag
pci_write_config_dword(agp_bridge->dev, ALI_TAGCTRL,
((temp & 0xffffff00) | 0x00000001|0x00000002));
pci_read_config_dword(agp_bridge->dev, ALI_ATTBASE, &temp);
pci_write_config_dword(agp_bridge->dev, ALI_ATTBASE,
((temp & 0x00000ff0) | previous_size->size_value));
}
static int ali_configure(void)
{
u32 temp;
struct aper_size_info_32 *current_size;
current_size = A_SIZE_32(agp_bridge->current_size);
/* aperture size and gatt addr */
pci_read_config_dword(agp_bridge->dev, ALI_ATTBASE, &temp);
temp = (((temp & 0x00000ff0) | (agp_bridge->gatt_bus_addr & 0xfffff000))
| (current_size->size_value & 0xf));
pci_write_config_dword(agp_bridge->dev, ALI_ATTBASE, temp);
/* tlb control */
pci_read_config_dword(agp_bridge->dev, ALI_TLBCTRL, &temp);
pci_write_config_dword(agp_bridge->dev, ALI_TLBCTRL, ((temp & 0xffffff00) | 0x00000010));
/* address to map to */
pci_read_config_dword(agp_bridge->dev, AGP_APBASE, &temp);
agp_bridge->gart_bus_addr = (temp & PCI_BASE_ADDRESS_MEM_MASK);
#if 0
if (agp_bridge->type == ALI_M1541) {
u32 nlvm_addr = 0;
switch (current_size->size_value) {
case 0: break;
case 1: nlvm_addr = 0x100000;break;
case 2: nlvm_addr = 0x200000;break;
case 3: nlvm_addr = 0x400000;break;
case 4: nlvm_addr = 0x800000;break;
case 6: nlvm_addr = 0x1000000;break;
case 7: nlvm_addr = 0x2000000;break;
case 8: nlvm_addr = 0x4000000;break;
case 9: nlvm_addr = 0x8000000;break;
case 10: nlvm_addr = 0x10000000;break;
default: break;
}
nlvm_addr--;
nlvm_addr&=0xfff00000;
nlvm_addr+= agp_bridge->gart_bus_addr;
nlvm_addr|=(agp_bridge->gart_bus_addr>>12);
dev_info(&agp_bridge->dev->dev, "nlvm top &base = %8x\n",
nlvm_addr);
}
#endif
pci_read_config_dword(agp_bridge->dev, ALI_TLBCTRL, &temp);
temp &= 0xffffff7f; //enable TLB
pci_write_config_dword(agp_bridge->dev, ALI_TLBCTRL, temp);
return 0;
}
static void m1541_cache_flush(void)
{
int i, page_count;
u32 temp;
global_cache_flush();
page_count = 1 << A_SIZE_32(agp_bridge->current_size)->page_order;
for (i = 0; i < PAGE_SIZE * page_count; i += PAGE_SIZE) {
pci_read_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
&temp);
pci_write_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
(((temp & ALI_CACHE_FLUSH_ADDR_MASK) |
(agp_bridge->gatt_bus_addr + i)) |
ALI_CACHE_FLUSH_EN));
}
}
static struct page *m1541_alloc_page(struct agp_bridge_data *bridge)
{
struct page *page = agp_generic_alloc_page(agp_bridge);
u32 temp;
if (!page)
return NULL;
pci_read_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL, &temp);
pci_write_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
(((temp & ALI_CACHE_FLUSH_ADDR_MASK) |
page_to_phys(page)) | ALI_CACHE_FLUSH_EN ));
return page;
}
static void ali_destroy_page(struct page *page, int flags)
{
if (page) {
if (flags & AGP_PAGE_DESTROY_UNMAP) {
global_cache_flush(); /* is this really needed? --hch */
agp_generic_destroy_page(page, flags);
} else
agp_generic_destroy_page(page, flags);
}
}
static void m1541_destroy_page(struct page *page, int flags)
{
u32 temp;
if (page == NULL)
return;
if (flags & AGP_PAGE_DESTROY_UNMAP) {
global_cache_flush();
pci_read_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL, &temp);
pci_write_config_dword(agp_bridge->dev, ALI_CACHE_FLUSH_CTRL,
(((temp & ALI_CACHE_FLUSH_ADDR_MASK) |
page_to_phys(page)) | ALI_CACHE_FLUSH_EN));
}
agp_generic_destroy_page(page, flags);
}
/* Setup function */
static const struct aper_size_info_32 ali_generic_sizes[7] =
{
{256, 65536, 6, 10},
{128, 32768, 5, 9},
{64, 16384, 4, 8},
{32, 8192, 3, 7},
{16, 4096, 2, 6},
{8, 2048, 1, 4},
{4, 1024, 0, 3}
};
static const struct agp_bridge_driver ali_generic_bridge = {
.owner = THIS_MODULE,
.aperture_sizes = ali_generic_sizes,
.size_type = U32_APER_SIZE,
.num_aperture_sizes = 7,
.needs_scratch_page = true,
.configure = ali_configure,
.fetch_size = ali_fetch_size,
.cleanup = ali_cleanup,
.tlb_flush = ali_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = NULL,
.agp_enable = agp_generic_enable,
.cache_flush = global_cache_flush,
.create_gatt_table = agp_generic_create_gatt_table,
.free_gatt_table = agp_generic_free_gatt_table,
.insert_memory = agp_generic_insert_memory,
.remove_memory = agp_generic_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = agp_generic_alloc_page,
.agp_destroy_page = ali_destroy_page,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
};
static const struct agp_bridge_driver ali_m1541_bridge = {
.owner = THIS_MODULE,
.aperture_sizes = ali_generic_sizes,
.size_type = U32_APER_SIZE,
.num_aperture_sizes = 7,
.configure = ali_configure,
.fetch_size = ali_fetch_size,
.cleanup = ali_cleanup,
.tlb_flush = ali_tlbflush,
.mask_memory = agp_generic_mask_memory,
.masks = NULL,
.agp_enable = agp_generic_enable,
.cache_flush = m1541_cache_flush,
.create_gatt_table = agp_generic_create_gatt_table,
.free_gatt_table = agp_generic_free_gatt_table,
.insert_memory = agp_generic_insert_memory,
.remove_memory = agp_generic_remove_memory,
.alloc_by_type = agp_generic_alloc_by_type,
.free_by_type = agp_generic_free_by_type,
.agp_alloc_page = m1541_alloc_page,
.agp_destroy_page = m1541_destroy_page,
.agp_type_to_mask_type = agp_generic_type_to_mask_type,
};
static struct agp_device_ids ali_agp_device_ids[] =
{
{
.device_id = PCI_DEVICE_ID_AL_M1541,
.chipset_name = "M1541",
},
{
.device_id = PCI_DEVICE_ID_AL_M1621,
.chipset_name = "M1621",
},
{
.device_id = PCI_DEVICE_ID_AL_M1631,
.chipset_name = "M1631",
},
{
.device_id = PCI_DEVICE_ID_AL_M1632,
.chipset_name = "M1632",
},
{
.device_id = PCI_DEVICE_ID_AL_M1641,
.chipset_name = "M1641",
},
{
.device_id = PCI_DEVICE_ID_AL_M1644,
.chipset_name = "M1644",
},
{
.device_id = PCI_DEVICE_ID_AL_M1647,
.chipset_name = "M1647",
},
{
.device_id = PCI_DEVICE_ID_AL_M1651,
.chipset_name = "M1651",
},
{
.device_id = PCI_DEVICE_ID_AL_M1671,
.chipset_name = "M1671",
},
{
.device_id = PCI_DEVICE_ID_AL_M1681,
.chipset_name = "M1681",
},
{
.device_id = PCI_DEVICE_ID_AL_M1683,
.chipset_name = "M1683",
},
{ }, /* dummy final entry, always present */
};
static int agp_ali_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct agp_device_ids *devs = ali_agp_device_ids;
struct agp_bridge_data *bridge;
u8 hidden_1621_id, cap_ptr;
int j;
cap_ptr = pci_find_capability(pdev, PCI_CAP_ID_AGP);
if (!cap_ptr)
return -ENODEV;
/* probe for known chipsets */
for (j = 0; devs[j].chipset_name; j++) {
if (pdev->device == devs[j].device_id)
goto found;
}
dev_err(&pdev->dev, "unsupported ALi chipset [%04x/%04x])\n",
pdev->vendor, pdev->device);
return -ENODEV;
found:
bridge = agp_alloc_bridge();
if (!bridge)
return -ENOMEM;
bridge->dev = pdev;
bridge->capndx = cap_ptr;
switch (pdev->device) {
case PCI_DEVICE_ID_AL_M1541:
bridge->driver = &ali_m1541_bridge;
break;
case PCI_DEVICE_ID_AL_M1621:
pci_read_config_byte(pdev, 0xFB, &hidden_1621_id);
switch (hidden_1621_id) {
case 0x31:
devs[j].chipset_name = "M1631";
break;
case 0x32:
devs[j].chipset_name = "M1632";
break;
case 0x41:
devs[j].chipset_name = "M1641";
break;
case 0x43:
devs[j].chipset_name = "M1621";
break;
case 0x47:
devs[j].chipset_name = "M1647";
break;
case 0x51:
devs[j].chipset_name = "M1651";
break;
default:
break;
}
/*FALLTHROUGH*/
default:
bridge->driver = &ali_generic_bridge;
}
dev_info(&pdev->dev, "ALi %s chipset\n", devs[j].chipset_name);
/* Fill in the mode register */
pci_read_config_dword(pdev,
bridge->capndx+PCI_AGP_STATUS,
&bridge->mode);
pci_set_drvdata(pdev, bridge);
return agp_add_bridge(bridge);
}
static void agp_ali_remove(struct pci_dev *pdev)
{
struct agp_bridge_data *bridge = pci_get_drvdata(pdev);
agp_remove_bridge(bridge);
agp_put_bridge(bridge);
}
static struct pci_device_id agp_ali_pci_table[] = {
{
.class = (PCI_CLASS_BRIDGE_HOST << 8),
.class_mask = ~0,
.vendor = PCI_VENDOR_ID_AL,
.device = PCI_ANY_ID,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ }
};
MODULE_DEVICE_TABLE(pci, agp_ali_pci_table);
static struct pci_driver agp_ali_pci_driver = {
.name = "agpgart-ali",
.id_table = agp_ali_pci_table,
.probe = agp_ali_probe,
.remove = agp_ali_remove,
};
static int __init agp_ali_init(void)
{
if (agp_off)
return -EINVAL;
return pci_register_driver(&agp_ali_pci_driver);
}
static void __exit agp_ali_cleanup(void)
{
pci_unregister_driver(&agp_ali_pci_driver);
}
module_init(agp_ali_init);
module_exit(agp_ali_cleanup);
MODULE_AUTHOR("Dave Jones <davej@redhat.com>");
MODULE_LICENSE("GPL and additional rights");
| gpl-2.0 |
CobraDroid/android_kernel_goldfish | drivers/acpi/processor_throttling.c | 4276 | 32294 | /*
* processor_throttling.c - Throttling submodule of the ACPI processor driver
*
* Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com>
* Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
* Copyright (C) 2004 Dominik Brodowski <linux@brodo.de>
* Copyright (C) 2004 Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>
* - Added processor hotplug support
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/cpufreq.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#include <acpi/processor.h>
#define PREFIX "ACPI: "
#define ACPI_PROCESSOR_CLASS "processor"
#define _COMPONENT ACPI_PROCESSOR_COMPONENT
ACPI_MODULE_NAME("processor_throttling");
/* ignore_tpc:
* 0 -> acpi processor driver doesn't ignore _TPC values
* 1 -> acpi processor driver ignores _TPC values
*/
static int ignore_tpc;
module_param(ignore_tpc, int, 0644);
MODULE_PARM_DESC(ignore_tpc, "Disable broken BIOS _TPC throttling support");
struct throttling_tstate {
unsigned int cpu; /* cpu nr */
int target_state; /* target T-state */
};
#define THROTTLING_PRECHANGE (1)
#define THROTTLING_POSTCHANGE (2)
static int acpi_processor_get_throttling(struct acpi_processor *pr);
int acpi_processor_set_throttling(struct acpi_processor *pr,
int state, bool force);
static int acpi_processor_update_tsd_coord(void)
{
int count, count_target;
int retval = 0;
unsigned int i, j;
cpumask_var_t covered_cpus;
struct acpi_processor *pr, *match_pr;
struct acpi_tsd_package *pdomain, *match_pdomain;
struct acpi_processor_throttling *pthrottling, *match_pthrottling;
if (!zalloc_cpumask_var(&covered_cpus, GFP_KERNEL))
return -ENOMEM;
/*
* Now that we have _TSD data from all CPUs, lets setup T-state
* coordination between all CPUs.
*/
for_each_possible_cpu(i) {
pr = per_cpu(processors, i);
if (!pr)
continue;
/* Basic validity check for domain info */
pthrottling = &(pr->throttling);
/*
* If tsd package for one cpu is invalid, the coordination
* among all CPUs is thought as invalid.
* Maybe it is ugly.
*/
if (!pthrottling->tsd_valid_flag) {
retval = -EINVAL;
break;
}
}
if (retval)
goto err_ret;
for_each_possible_cpu(i) {
pr = per_cpu(processors, i);
if (!pr)
continue;
if (cpumask_test_cpu(i, covered_cpus))
continue;
pthrottling = &pr->throttling;
pdomain = &(pthrottling->domain_info);
cpumask_set_cpu(i, pthrottling->shared_cpu_map);
cpumask_set_cpu(i, covered_cpus);
/*
* If the number of processor in the TSD domain is 1, it is
* unnecessary to parse the coordination for this CPU.
*/
if (pdomain->num_processors <= 1)
continue;
/* Validate the Domain info */
count_target = pdomain->num_processors;
count = 1;
for_each_possible_cpu(j) {
if (i == j)
continue;
match_pr = per_cpu(processors, j);
if (!match_pr)
continue;
match_pthrottling = &(match_pr->throttling);
match_pdomain = &(match_pthrottling->domain_info);
if (match_pdomain->domain != pdomain->domain)
continue;
/* Here i and j are in the same domain.
* If two TSD packages have the same domain, they
* should have the same num_porcessors and
* coordination type. Otherwise it will be regarded
* as illegal.
*/
if (match_pdomain->num_processors != count_target) {
retval = -EINVAL;
goto err_ret;
}
if (pdomain->coord_type != match_pdomain->coord_type) {
retval = -EINVAL;
goto err_ret;
}
cpumask_set_cpu(j, covered_cpus);
cpumask_set_cpu(j, pthrottling->shared_cpu_map);
count++;
}
for_each_possible_cpu(j) {
if (i == j)
continue;
match_pr = per_cpu(processors, j);
if (!match_pr)
continue;
match_pthrottling = &(match_pr->throttling);
match_pdomain = &(match_pthrottling->domain_info);
if (match_pdomain->domain != pdomain->domain)
continue;
/*
* If some CPUS have the same domain, they
* will have the same shared_cpu_map.
*/
cpumask_copy(match_pthrottling->shared_cpu_map,
pthrottling->shared_cpu_map);
}
}
err_ret:
free_cpumask_var(covered_cpus);
for_each_possible_cpu(i) {
pr = per_cpu(processors, i);
if (!pr)
continue;
/*
* Assume no coordination on any error parsing domain info.
* The coordination type will be forced as SW_ALL.
*/
if (retval) {
pthrottling = &(pr->throttling);
cpumask_clear(pthrottling->shared_cpu_map);
cpumask_set_cpu(i, pthrottling->shared_cpu_map);
pthrottling->shared_type = DOMAIN_COORD_TYPE_SW_ALL;
}
}
return retval;
}
/*
* Update the T-state coordination after the _TSD
* data for all cpus is obtained.
*/
void acpi_processor_throttling_init(void)
{
if (acpi_processor_update_tsd_coord())
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Assume no T-state coordination\n"));
return;
}
static int acpi_processor_throttling_notifier(unsigned long event, void *data)
{
struct throttling_tstate *p_tstate = data;
struct acpi_processor *pr;
unsigned int cpu ;
int target_state;
struct acpi_processor_limit *p_limit;
struct acpi_processor_throttling *p_throttling;
cpu = p_tstate->cpu;
pr = per_cpu(processors, cpu);
if (!pr) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Invalid pr pointer\n"));
return 0;
}
if (!pr->flags.throttling) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Throttling control is "
"unsupported on CPU %d\n", cpu));
return 0;
}
target_state = p_tstate->target_state;
p_throttling = &(pr->throttling);
switch (event) {
case THROTTLING_PRECHANGE:
/*
* Prechange event is used to choose one proper t-state,
* which meets the limits of thermal, user and _TPC.
*/
p_limit = &pr->limit;
if (p_limit->thermal.tx > target_state)
target_state = p_limit->thermal.tx;
if (p_limit->user.tx > target_state)
target_state = p_limit->user.tx;
if (pr->throttling_platform_limit > target_state)
target_state = pr->throttling_platform_limit;
if (target_state >= p_throttling->state_count) {
printk(KERN_WARNING
"Exceed the limit of T-state \n");
target_state = p_throttling->state_count - 1;
}
p_tstate->target_state = target_state;
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "PreChange Event:"
"target T-state of CPU %d is T%d\n",
cpu, target_state));
break;
case THROTTLING_POSTCHANGE:
/*
* Postchange event is only used to update the
* T-state flag of acpi_processor_throttling.
*/
p_throttling->state = target_state;
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "PostChange Event:"
"CPU %d is switched to T%d\n",
cpu, target_state));
break;
default:
printk(KERN_WARNING
"Unsupported Throttling notifier event\n");
break;
}
return 0;
}
/*
* _TPC - Throttling Present Capabilities
*/
static int acpi_processor_get_platform_limit(struct acpi_processor *pr)
{
acpi_status status = 0;
unsigned long long tpc = 0;
if (!pr)
return -EINVAL;
if (ignore_tpc)
goto end;
status = acpi_evaluate_integer(pr->handle, "_TPC", NULL, &tpc);
if (ACPI_FAILURE(status)) {
if (status != AE_NOT_FOUND) {
ACPI_EXCEPTION((AE_INFO, status, "Evaluating _TPC"));
}
return -ENODEV;
}
end:
pr->throttling_platform_limit = (int)tpc;
return 0;
}
int acpi_processor_tstate_has_changed(struct acpi_processor *pr)
{
int result = 0;
int throttling_limit;
int current_state;
struct acpi_processor_limit *limit;
int target_state;
if (ignore_tpc)
return 0;
result = acpi_processor_get_platform_limit(pr);
if (result) {
/* Throttling Limit is unsupported */
return result;
}
throttling_limit = pr->throttling_platform_limit;
if (throttling_limit >= pr->throttling.state_count) {
/* Uncorrect Throttling Limit */
return -EINVAL;
}
current_state = pr->throttling.state;
if (current_state > throttling_limit) {
/*
* The current state can meet the requirement of
* _TPC limit. But it is reasonable that OSPM changes
* t-states from high to low for better performance.
* Of course the limit condition of thermal
* and user should be considered.
*/
limit = &pr->limit;
target_state = throttling_limit;
if (limit->thermal.tx > target_state)
target_state = limit->thermal.tx;
if (limit->user.tx > target_state)
target_state = limit->user.tx;
} else if (current_state == throttling_limit) {
/*
* Unnecessary to change the throttling state
*/
return 0;
} else {
/*
* If the current state is lower than the limit of _TPC, it
* will be forced to switch to the throttling state defined
* by throttling_platfor_limit.
* Because the previous state meets with the limit condition
* of thermal and user, it is unnecessary to check it again.
*/
target_state = throttling_limit;
}
return acpi_processor_set_throttling(pr, target_state, false);
}
/*
* This function is used to reevaluate whether the T-state is valid
* after one CPU is onlined/offlined.
* It is noted that it won't reevaluate the following properties for
* the T-state.
* 1. Control method.
* 2. the number of supported T-state
* 3. TSD domain
*/
void acpi_processor_reevaluate_tstate(struct acpi_processor *pr,
unsigned long action)
{
int result = 0;
if (action == CPU_DEAD) {
/* When one CPU is offline, the T-state throttling
* will be invalidated.
*/
pr->flags.throttling = 0;
return;
}
/* the following is to recheck whether the T-state is valid for
* the online CPU
*/
if (!pr->throttling.state_count) {
/* If the number of T-state is invalid, it is
* invalidated.
*/
pr->flags.throttling = 0;
return;
}
pr->flags.throttling = 1;
/* Disable throttling (if enabled). We'll let subsequent
* policy (e.g.thermal) decide to lower performance if it
* so chooses, but for now we'll crank up the speed.
*/
result = acpi_processor_get_throttling(pr);
if (result)
goto end;
if (pr->throttling.state) {
result = acpi_processor_set_throttling(pr, 0, false);
if (result)
goto end;
}
end:
if (result)
pr->flags.throttling = 0;
}
/*
* _PTC - Processor Throttling Control (and status) register location
*/
static int acpi_processor_get_throttling_control(struct acpi_processor *pr)
{
int result = 0;
acpi_status status = 0;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
union acpi_object *ptc = NULL;
union acpi_object obj = { 0 };
struct acpi_processor_throttling *throttling;
status = acpi_evaluate_object(pr->handle, "_PTC", NULL, &buffer);
if (ACPI_FAILURE(status)) {
if (status != AE_NOT_FOUND) {
ACPI_EXCEPTION((AE_INFO, status, "Evaluating _PTC"));
}
return -ENODEV;
}
ptc = (union acpi_object *)buffer.pointer;
if (!ptc || (ptc->type != ACPI_TYPE_PACKAGE)
|| (ptc->package.count != 2)) {
printk(KERN_ERR PREFIX "Invalid _PTC data\n");
result = -EFAULT;
goto end;
}
/*
* control_register
*/
obj = ptc->package.elements[0];
if ((obj.type != ACPI_TYPE_BUFFER)
|| (obj.buffer.length < sizeof(struct acpi_ptc_register))
|| (obj.buffer.pointer == NULL)) {
printk(KERN_ERR PREFIX
"Invalid _PTC data (control_register)\n");
result = -EFAULT;
goto end;
}
memcpy(&pr->throttling.control_register, obj.buffer.pointer,
sizeof(struct acpi_ptc_register));
/*
* status_register
*/
obj = ptc->package.elements[1];
if ((obj.type != ACPI_TYPE_BUFFER)
|| (obj.buffer.length < sizeof(struct acpi_ptc_register))
|| (obj.buffer.pointer == NULL)) {
printk(KERN_ERR PREFIX "Invalid _PTC data (status_register)\n");
result = -EFAULT;
goto end;
}
memcpy(&pr->throttling.status_register, obj.buffer.pointer,
sizeof(struct acpi_ptc_register));
throttling = &pr->throttling;
if ((throttling->control_register.bit_width +
throttling->control_register.bit_offset) > 32) {
printk(KERN_ERR PREFIX "Invalid _PTC control register\n");
result = -EFAULT;
goto end;
}
if ((throttling->status_register.bit_width +
throttling->status_register.bit_offset) > 32) {
printk(KERN_ERR PREFIX "Invalid _PTC status register\n");
result = -EFAULT;
goto end;
}
end:
kfree(buffer.pointer);
return result;
}
/*
* _TSS - Throttling Supported States
*/
static int acpi_processor_get_throttling_states(struct acpi_processor *pr)
{
int result = 0;
acpi_status status = AE_OK;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
struct acpi_buffer format = { sizeof("NNNNN"), "NNNNN" };
struct acpi_buffer state = { 0, NULL };
union acpi_object *tss = NULL;
int i;
status = acpi_evaluate_object(pr->handle, "_TSS", NULL, &buffer);
if (ACPI_FAILURE(status)) {
if (status != AE_NOT_FOUND) {
ACPI_EXCEPTION((AE_INFO, status, "Evaluating _TSS"));
}
return -ENODEV;
}
tss = buffer.pointer;
if (!tss || (tss->type != ACPI_TYPE_PACKAGE)) {
printk(KERN_ERR PREFIX "Invalid _TSS data\n");
result = -EFAULT;
goto end;
}
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Found %d throttling states\n",
tss->package.count));
pr->throttling.state_count = tss->package.count;
pr->throttling.states_tss =
kmalloc(sizeof(struct acpi_processor_tx_tss) * tss->package.count,
GFP_KERNEL);
if (!pr->throttling.states_tss) {
result = -ENOMEM;
goto end;
}
for (i = 0; i < pr->throttling.state_count; i++) {
struct acpi_processor_tx_tss *tx =
(struct acpi_processor_tx_tss *)&(pr->throttling.
states_tss[i]);
state.length = sizeof(struct acpi_processor_tx_tss);
state.pointer = tx;
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Extracting state %d\n", i));
status = acpi_extract_package(&(tss->package.elements[i]),
&format, &state);
if (ACPI_FAILURE(status)) {
ACPI_EXCEPTION((AE_INFO, status, "Invalid _TSS data"));
result = -EFAULT;
kfree(pr->throttling.states_tss);
goto end;
}
if (!tx->freqpercentage) {
printk(KERN_ERR PREFIX
"Invalid _TSS data: freq is zero\n");
result = -EFAULT;
kfree(pr->throttling.states_tss);
goto end;
}
}
end:
kfree(buffer.pointer);
return result;
}
/*
* _TSD - T-State Dependencies
*/
static int acpi_processor_get_tsd(struct acpi_processor *pr)
{
int result = 0;
acpi_status status = AE_OK;
struct acpi_buffer buffer = { ACPI_ALLOCATE_BUFFER, NULL };
struct acpi_buffer format = { sizeof("NNNNN"), "NNNNN" };
struct acpi_buffer state = { 0, NULL };
union acpi_object *tsd = NULL;
struct acpi_tsd_package *pdomain;
struct acpi_processor_throttling *pthrottling;
pthrottling = &pr->throttling;
pthrottling->tsd_valid_flag = 0;
status = acpi_evaluate_object(pr->handle, "_TSD", NULL, &buffer);
if (ACPI_FAILURE(status)) {
if (status != AE_NOT_FOUND) {
ACPI_EXCEPTION((AE_INFO, status, "Evaluating _TSD"));
}
return -ENODEV;
}
tsd = buffer.pointer;
if (!tsd || (tsd->type != ACPI_TYPE_PACKAGE)) {
printk(KERN_ERR PREFIX "Invalid _TSD data\n");
result = -EFAULT;
goto end;
}
if (tsd->package.count != 1) {
printk(KERN_ERR PREFIX "Invalid _TSD data\n");
result = -EFAULT;
goto end;
}
pdomain = &(pr->throttling.domain_info);
state.length = sizeof(struct acpi_tsd_package);
state.pointer = pdomain;
status = acpi_extract_package(&(tsd->package.elements[0]),
&format, &state);
if (ACPI_FAILURE(status)) {
printk(KERN_ERR PREFIX "Invalid _TSD data\n");
result = -EFAULT;
goto end;
}
if (pdomain->num_entries != ACPI_TSD_REV0_ENTRIES) {
printk(KERN_ERR PREFIX "Unknown _TSD:num_entries\n");
result = -EFAULT;
goto end;
}
if (pdomain->revision != ACPI_TSD_REV0_REVISION) {
printk(KERN_ERR PREFIX "Unknown _TSD:revision\n");
result = -EFAULT;
goto end;
}
pthrottling = &pr->throttling;
pthrottling->tsd_valid_flag = 1;
pthrottling->shared_type = pdomain->coord_type;
cpumask_set_cpu(pr->id, pthrottling->shared_cpu_map);
/*
* If the coordination type is not defined in ACPI spec,
* the tsd_valid_flag will be clear and coordination type
* will be forecd as DOMAIN_COORD_TYPE_SW_ALL.
*/
if (pdomain->coord_type != DOMAIN_COORD_TYPE_SW_ALL &&
pdomain->coord_type != DOMAIN_COORD_TYPE_SW_ANY &&
pdomain->coord_type != DOMAIN_COORD_TYPE_HW_ALL) {
pthrottling->tsd_valid_flag = 0;
pthrottling->shared_type = DOMAIN_COORD_TYPE_SW_ALL;
}
end:
kfree(buffer.pointer);
return result;
}
/* --------------------------------------------------------------------------
Throttling Control
-------------------------------------------------------------------------- */
static int acpi_processor_get_throttling_fadt(struct acpi_processor *pr)
{
int state = 0;
u32 value = 0;
u32 duty_mask = 0;
u32 duty_value = 0;
if (!pr)
return -EINVAL;
if (!pr->flags.throttling)
return -ENODEV;
pr->throttling.state = 0;
duty_mask = pr->throttling.state_count - 1;
duty_mask <<= pr->throttling.duty_offset;
local_irq_disable();
value = inl(pr->throttling.address);
/*
* Compute the current throttling state when throttling is enabled
* (bit 4 is on).
*/
if (value & 0x10) {
duty_value = value & duty_mask;
duty_value >>= pr->throttling.duty_offset;
if (duty_value)
state = pr->throttling.state_count - duty_value;
}
pr->throttling.state = state;
local_irq_enable();
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Throttling state is T%d (%d%% throttling applied)\n",
state, pr->throttling.states[state].performance));
return 0;
}
#ifdef CONFIG_X86
static int acpi_throttling_rdmsr(u64 *value)
{
u64 msr_high, msr_low;
u64 msr = 0;
int ret = -1;
if ((this_cpu_read(cpu_info.x86_vendor) != X86_VENDOR_INTEL) ||
!this_cpu_has(X86_FEATURE_ACPI)) {
printk(KERN_ERR PREFIX
"HARDWARE addr space,NOT supported yet\n");
} else {
msr_low = 0;
msr_high = 0;
rdmsr_safe(MSR_IA32_THERM_CONTROL,
(u32 *)&msr_low , (u32 *) &msr_high);
msr = (msr_high << 32) | msr_low;
*value = (u64) msr;
ret = 0;
}
return ret;
}
static int acpi_throttling_wrmsr(u64 value)
{
int ret = -1;
u64 msr;
if ((this_cpu_read(cpu_info.x86_vendor) != X86_VENDOR_INTEL) ||
!this_cpu_has(X86_FEATURE_ACPI)) {
printk(KERN_ERR PREFIX
"HARDWARE addr space,NOT supported yet\n");
} else {
msr = value;
wrmsr_safe(MSR_IA32_THERM_CONTROL,
msr & 0xffffffff, msr >> 32);
ret = 0;
}
return ret;
}
#else
static int acpi_throttling_rdmsr(u64 *value)
{
printk(KERN_ERR PREFIX
"HARDWARE addr space,NOT supported yet\n");
return -1;
}
static int acpi_throttling_wrmsr(u64 value)
{
printk(KERN_ERR PREFIX
"HARDWARE addr space,NOT supported yet\n");
return -1;
}
#endif
static int acpi_read_throttling_status(struct acpi_processor *pr,
u64 *value)
{
u32 bit_width, bit_offset;
u32 ptc_value;
u64 ptc_mask;
struct acpi_processor_throttling *throttling;
int ret = -1;
throttling = &pr->throttling;
switch (throttling->status_register.space_id) {
case ACPI_ADR_SPACE_SYSTEM_IO:
bit_width = throttling->status_register.bit_width;
bit_offset = throttling->status_register.bit_offset;
acpi_os_read_port((acpi_io_address) throttling->status_register.
address, &ptc_value,
(u32) (bit_width + bit_offset));
ptc_mask = (1 << bit_width) - 1;
*value = (u64) ((ptc_value >> bit_offset) & ptc_mask);
ret = 0;
break;
case ACPI_ADR_SPACE_FIXED_HARDWARE:
ret = acpi_throttling_rdmsr(value);
break;
default:
printk(KERN_ERR PREFIX "Unknown addr space %d\n",
(u32) (throttling->status_register.space_id));
}
return ret;
}
static int acpi_write_throttling_state(struct acpi_processor *pr,
u64 value)
{
u32 bit_width, bit_offset;
u64 ptc_value;
u64 ptc_mask;
struct acpi_processor_throttling *throttling;
int ret = -1;
throttling = &pr->throttling;
switch (throttling->control_register.space_id) {
case ACPI_ADR_SPACE_SYSTEM_IO:
bit_width = throttling->control_register.bit_width;
bit_offset = throttling->control_register.bit_offset;
ptc_mask = (1 << bit_width) - 1;
ptc_value = value & ptc_mask;
acpi_os_write_port((acpi_io_address) throttling->
control_register.address,
(u32) (ptc_value << bit_offset),
(u32) (bit_width + bit_offset));
ret = 0;
break;
case ACPI_ADR_SPACE_FIXED_HARDWARE:
ret = acpi_throttling_wrmsr(value);
break;
default:
printk(KERN_ERR PREFIX "Unknown addr space %d\n",
(u32) (throttling->control_register.space_id));
}
return ret;
}
static int acpi_get_throttling_state(struct acpi_processor *pr,
u64 value)
{
int i;
for (i = 0; i < pr->throttling.state_count; i++) {
struct acpi_processor_tx_tss *tx =
(struct acpi_processor_tx_tss *)&(pr->throttling.
states_tss[i]);
if (tx->control == value)
return i;
}
return -1;
}
static int acpi_get_throttling_value(struct acpi_processor *pr,
int state, u64 *value)
{
int ret = -1;
if (state >= 0 && state <= pr->throttling.state_count) {
struct acpi_processor_tx_tss *tx =
(struct acpi_processor_tx_tss *)&(pr->throttling.
states_tss[state]);
*value = tx->control;
ret = 0;
}
return ret;
}
static int acpi_processor_get_throttling_ptc(struct acpi_processor *pr)
{
int state = 0;
int ret;
u64 value;
if (!pr)
return -EINVAL;
if (!pr->flags.throttling)
return -ENODEV;
pr->throttling.state = 0;
value = 0;
ret = acpi_read_throttling_status(pr, &value);
if (ret >= 0) {
state = acpi_get_throttling_state(pr, value);
if (state == -1) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Invalid throttling state, reset\n"));
state = 0;
ret = acpi_processor_set_throttling(pr, state, true);
if (ret)
return ret;
}
pr->throttling.state = state;
}
return 0;
}
static int acpi_processor_get_throttling(struct acpi_processor *pr)
{
cpumask_var_t saved_mask;
int ret;
if (!pr)
return -EINVAL;
if (!pr->flags.throttling)
return -ENODEV;
if (!alloc_cpumask_var(&saved_mask, GFP_KERNEL))
return -ENOMEM;
/*
* Migrate task to the cpu pointed by pr.
*/
cpumask_copy(saved_mask, ¤t->cpus_allowed);
/* FIXME: use work_on_cpu() */
if (set_cpus_allowed_ptr(current, cpumask_of(pr->id))) {
/* Can't migrate to the target pr->id CPU. Exit */
free_cpumask_var(saved_mask);
return -ENODEV;
}
ret = pr->throttling.acpi_processor_get_throttling(pr);
/* restore the previous state */
set_cpus_allowed_ptr(current, saved_mask);
free_cpumask_var(saved_mask);
return ret;
}
static int acpi_processor_get_fadt_info(struct acpi_processor *pr)
{
int i, step;
if (!pr->throttling.address) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "No throttling register\n"));
return -EINVAL;
} else if (!pr->throttling.duty_width) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "No throttling states\n"));
return -EINVAL;
}
/* TBD: Support duty_cycle values that span bit 4. */
else if ((pr->throttling.duty_offset + pr->throttling.duty_width) > 4) {
printk(KERN_WARNING PREFIX "duty_cycle spans bit 4\n");
return -EINVAL;
}
pr->throttling.state_count = 1 << acpi_gbl_FADT.duty_width;
/*
* Compute state values. Note that throttling displays a linear power
* performance relationship (at 50% performance the CPU will consume
* 50% power). Values are in 1/10th of a percent to preserve accuracy.
*/
step = (1000 / pr->throttling.state_count);
for (i = 0; i < pr->throttling.state_count; i++) {
pr->throttling.states[i].performance = 1000 - step * i;
pr->throttling.states[i].power = 1000 - step * i;
}
return 0;
}
static int acpi_processor_set_throttling_fadt(struct acpi_processor *pr,
int state, bool force)
{
u32 value = 0;
u32 duty_mask = 0;
u32 duty_value = 0;
if (!pr)
return -EINVAL;
if ((state < 0) || (state > (pr->throttling.state_count - 1)))
return -EINVAL;
if (!pr->flags.throttling)
return -ENODEV;
if (!force && (state == pr->throttling.state))
return 0;
if (state < pr->throttling_platform_limit)
return -EPERM;
/*
* Calculate the duty_value and duty_mask.
*/
if (state) {
duty_value = pr->throttling.state_count - state;
duty_value <<= pr->throttling.duty_offset;
/* Used to clear all duty_value bits */
duty_mask = pr->throttling.state_count - 1;
duty_mask <<= acpi_gbl_FADT.duty_offset;
duty_mask = ~duty_mask;
}
local_irq_disable();
/*
* Disable throttling by writing a 0 to bit 4. Note that we must
* turn it off before you can change the duty_value.
*/
value = inl(pr->throttling.address);
if (value & 0x10) {
value &= 0xFFFFFFEF;
outl(value, pr->throttling.address);
}
/*
* Write the new duty_value and then enable throttling. Note
* that a state value of 0 leaves throttling disabled.
*/
if (state) {
value &= duty_mask;
value |= duty_value;
outl(value, pr->throttling.address);
value |= 0x00000010;
outl(value, pr->throttling.address);
}
pr->throttling.state = state;
local_irq_enable();
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Throttling state set to T%d (%d%%)\n", state,
(pr->throttling.states[state].performance ? pr->
throttling.states[state].performance / 10 : 0)));
return 0;
}
static int acpi_processor_set_throttling_ptc(struct acpi_processor *pr,
int state, bool force)
{
int ret;
u64 value;
if (!pr)
return -EINVAL;
if ((state < 0) || (state > (pr->throttling.state_count - 1)))
return -EINVAL;
if (!pr->flags.throttling)
return -ENODEV;
if (!force && (state == pr->throttling.state))
return 0;
if (state < pr->throttling_platform_limit)
return -EPERM;
value = 0;
ret = acpi_get_throttling_value(pr, state, &value);
if (ret >= 0) {
acpi_write_throttling_state(pr, value);
pr->throttling.state = state;
}
return 0;
}
int acpi_processor_set_throttling(struct acpi_processor *pr,
int state, bool force)
{
cpumask_var_t saved_mask;
int ret = 0;
unsigned int i;
struct acpi_processor *match_pr;
struct acpi_processor_throttling *p_throttling;
struct throttling_tstate t_state;
cpumask_var_t online_throttling_cpus;
if (!pr)
return -EINVAL;
if (!pr->flags.throttling)
return -ENODEV;
if ((state < 0) || (state > (pr->throttling.state_count - 1)))
return -EINVAL;
if (!alloc_cpumask_var(&saved_mask, GFP_KERNEL))
return -ENOMEM;
if (!alloc_cpumask_var(&online_throttling_cpus, GFP_KERNEL)) {
free_cpumask_var(saved_mask);
return -ENOMEM;
}
if (cpu_is_offline(pr->id)) {
/*
* the cpu pointed by pr->id is offline. Unnecessary to change
* the throttling state any more.
*/
return -ENODEV;
}
cpumask_copy(saved_mask, ¤t->cpus_allowed);
t_state.target_state = state;
p_throttling = &(pr->throttling);
cpumask_and(online_throttling_cpus, cpu_online_mask,
p_throttling->shared_cpu_map);
/*
* The throttling notifier will be called for every
* affected cpu in order to get one proper T-state.
* The notifier event is THROTTLING_PRECHANGE.
*/
for_each_cpu(i, online_throttling_cpus) {
t_state.cpu = i;
acpi_processor_throttling_notifier(THROTTLING_PRECHANGE,
&t_state);
}
/*
* The function of acpi_processor_set_throttling will be called
* to switch T-state. If the coordination type is SW_ALL or HW_ALL,
* it is necessary to call it for every affected cpu. Otherwise
* it can be called only for the cpu pointed by pr.
*/
if (p_throttling->shared_type == DOMAIN_COORD_TYPE_SW_ANY) {
/* FIXME: use work_on_cpu() */
if (set_cpus_allowed_ptr(current, cpumask_of(pr->id))) {
/* Can't migrate to the pr->id CPU. Exit */
ret = -ENODEV;
goto exit;
}
ret = p_throttling->acpi_processor_set_throttling(pr,
t_state.target_state, force);
} else {
/*
* When the T-state coordination is SW_ALL or HW_ALL,
* it is necessary to set T-state for every affected
* cpus.
*/
for_each_cpu(i, online_throttling_cpus) {
match_pr = per_cpu(processors, i);
/*
* If the pointer is invalid, we will report the
* error message and continue.
*/
if (!match_pr) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Invalid Pointer for CPU %d\n", i));
continue;
}
/*
* If the throttling control is unsupported on CPU i,
* we will report the error message and continue.
*/
if (!match_pr->flags.throttling) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Throttling Control is unsupported "
"on CPU %d\n", i));
continue;
}
t_state.cpu = i;
/* FIXME: use work_on_cpu() */
if (set_cpus_allowed_ptr(current, cpumask_of(i)))
continue;
ret = match_pr->throttling.
acpi_processor_set_throttling(
match_pr, t_state.target_state, force);
}
}
/*
* After the set_throttling is called, the
* throttling notifier is called for every
* affected cpu to update the T-states.
* The notifier event is THROTTLING_POSTCHANGE
*/
for_each_cpu(i, online_throttling_cpus) {
t_state.cpu = i;
acpi_processor_throttling_notifier(THROTTLING_POSTCHANGE,
&t_state);
}
/* restore the previous state */
/* FIXME: use work_on_cpu() */
set_cpus_allowed_ptr(current, saved_mask);
exit:
free_cpumask_var(online_throttling_cpus);
free_cpumask_var(saved_mask);
return ret;
}
int acpi_processor_get_throttling_info(struct acpi_processor *pr)
{
int result = 0;
struct acpi_processor_throttling *pthrottling;
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"pblk_address[0x%08x] duty_offset[%d] duty_width[%d]\n",
pr->throttling.address,
pr->throttling.duty_offset,
pr->throttling.duty_width));
/*
* Evaluate _PTC, _TSS and _TPC
* They must all be present or none of them can be used.
*/
if (acpi_processor_get_throttling_control(pr) ||
acpi_processor_get_throttling_states(pr) ||
acpi_processor_get_platform_limit(pr))
{
pr->throttling.acpi_processor_get_throttling =
&acpi_processor_get_throttling_fadt;
pr->throttling.acpi_processor_set_throttling =
&acpi_processor_set_throttling_fadt;
if (acpi_processor_get_fadt_info(pr))
return 0;
} else {
pr->throttling.acpi_processor_get_throttling =
&acpi_processor_get_throttling_ptc;
pr->throttling.acpi_processor_set_throttling =
&acpi_processor_set_throttling_ptc;
}
/*
* If TSD package for one CPU can't be parsed successfully, it means
* that this CPU will have no coordination with other CPUs.
*/
if (acpi_processor_get_tsd(pr)) {
pthrottling = &pr->throttling;
pthrottling->tsd_valid_flag = 0;
cpumask_set_cpu(pr->id, pthrottling->shared_cpu_map);
pthrottling->shared_type = DOMAIN_COORD_TYPE_SW_ALL;
}
/*
* PIIX4 Errata: We don't support throttling on the original PIIX4.
* This shouldn't be an issue as few (if any) mobile systems ever
* used this part.
*/
if (errata.piix4.throttle) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Throttling not supported on PIIX4 A- or B-step\n"));
return 0;
}
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Found %d throttling states\n",
pr->throttling.state_count));
pr->flags.throttling = 1;
/*
* Disable throttling (if enabled). We'll let subsequent policy (e.g.
* thermal) decide to lower performance if it so chooses, but for now
* we'll crank up the speed.
*/
result = acpi_processor_get_throttling(pr);
if (result)
goto end;
if (pr->throttling.state) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Disabling throttling (was T%d)\n",
pr->throttling.state));
result = acpi_processor_set_throttling(pr, 0, false);
if (result)
goto end;
}
end:
if (result)
pr->flags.throttling = 0;
return result;
}
| gpl-2.0 |
defreez/thesis-ics-kernel | drivers/input/input-compat.c | 4788 | 3294 | /*
* 32bit compatibility wrappers for the input subsystem.
*
* Very heavily based on evdev.c - Copyright (c) 1999-2002 Vojtech Pavlik
*
* 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 <asm/uaccess.h>
#include "input-compat.h"
#ifdef CONFIG_COMPAT
int input_event_from_user(const char __user *buffer,
struct input_event *event)
{
if (INPUT_COMPAT_TEST) {
struct input_event_compat compat_event;
if (copy_from_user(&compat_event, buffer,
sizeof(struct input_event_compat)))
return -EFAULT;
event->time.tv_sec = compat_event.time.tv_sec;
event->time.tv_usec = compat_event.time.tv_usec;
event->type = compat_event.type;
event->code = compat_event.code;
event->value = compat_event.value;
} else {
if (copy_from_user(event, buffer, sizeof(struct input_event)))
return -EFAULT;
}
return 0;
}
int input_event_to_user(char __user *buffer,
const struct input_event *event)
{
if (INPUT_COMPAT_TEST) {
struct input_event_compat compat_event;
compat_event.time.tv_sec = event->time.tv_sec;
compat_event.time.tv_usec = event->time.tv_usec;
compat_event.type = event->type;
compat_event.code = event->code;
compat_event.value = event->value;
if (copy_to_user(buffer, &compat_event,
sizeof(struct input_event_compat)))
return -EFAULT;
} else {
if (copy_to_user(buffer, event, sizeof(struct input_event)))
return -EFAULT;
}
return 0;
}
int input_ff_effect_from_user(const char __user *buffer, size_t size,
struct ff_effect *effect)
{
if (INPUT_COMPAT_TEST) {
struct ff_effect_compat *compat_effect;
if (size != sizeof(struct ff_effect_compat))
return -EINVAL;
/*
* It so happens that the pointer which needs to be changed
* is the last field in the structure, so we can retrieve the
* whole thing and replace just the pointer.
*/
compat_effect = (struct ff_effect_compat *)effect;
if (copy_from_user(compat_effect, buffer,
sizeof(struct ff_effect_compat)))
return -EFAULT;
if (compat_effect->type == FF_PERIODIC &&
compat_effect->u.periodic.waveform == FF_CUSTOM)
effect->u.periodic.custom_data =
compat_ptr(compat_effect->u.periodic.custom_data);
} else {
if (size != sizeof(struct ff_effect))
return -EINVAL;
if (copy_from_user(effect, buffer, sizeof(struct ff_effect)))
return -EFAULT;
}
return 0;
}
#else
int input_event_from_user(const char __user *buffer,
struct input_event *event)
{
if (copy_from_user(event, buffer, sizeof(struct input_event)))
return -EFAULT;
return 0;
}
int input_event_to_user(char __user *buffer,
const struct input_event *event)
{
if (copy_to_user(buffer, event, sizeof(struct input_event)))
return -EFAULT;
return 0;
}
int input_ff_effect_from_user(const char __user *buffer, size_t size,
struct ff_effect *effect)
{
if (size != sizeof(struct ff_effect))
return -EINVAL;
if (copy_from_user(effect, buffer, sizeof(struct ff_effect)))
return -EFAULT;
return 0;
}
#endif /* CONFIG_COMPAT */
EXPORT_SYMBOL_GPL(input_event_from_user);
EXPORT_SYMBOL_GPL(input_event_to_user);
EXPORT_SYMBOL_GPL(input_ff_effect_from_user);
| gpl-2.0 |
Android4Lumia/kernel_nokia_msm8x27 | arch/arm/mach-omap2/cm44xx.c | 7604 | 1317 | /*
* OMAP4 CM1, CM2 module low-level functions
*
* Copyright (C) 2010 Nokia Corporation
* Paul Walmsley
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* These functions are intended to be used only by the cminst44xx.c file.
* XXX Perhaps we should just move them there and make them static.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/io.h>
#include "iomap.h"
#include "common.h"
#include "cm.h"
#include "cm1_44xx.h"
#include "cm2_44xx.h"
#include "cm-regbits-44xx.h"
/* CM1 hardware module low-level functions */
/* Read a register in CM1 */
u32 omap4_cm1_read_inst_reg(s16 inst, u16 reg)
{
return __raw_readl(OMAP44XX_CM1_REGADDR(inst, reg));
}
/* Write into a register in CM1 */
void omap4_cm1_write_inst_reg(u32 val, s16 inst, u16 reg)
{
__raw_writel(val, OMAP44XX_CM1_REGADDR(inst, reg));
}
/* Read a register in CM2 */
u32 omap4_cm2_read_inst_reg(s16 inst, u16 reg)
{
return __raw_readl(OMAP44XX_CM2_REGADDR(inst, reg));
}
/* Write into a register in CM2 */
void omap4_cm2_write_inst_reg(u32 val, s16 inst, u16 reg)
{
__raw_writel(val, OMAP44XX_CM2_REGADDR(inst, reg));
}
| gpl-2.0 |
SlimLPXperia/android_kernel_sony_u8500 | fs/gfs2/dentry.c | 8116 | 2926 | /*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/gfs2_ondisk.h>
#include <linux/namei.h>
#include <linux/crc32.h>
#include "gfs2.h"
#include "incore.h"
#include "dir.h"
#include "glock.h"
#include "super.h"
#include "util.h"
#include "inode.h"
/**
* gfs2_drevalidate - Check directory lookup consistency
* @dentry: the mapping to check
* @nd:
*
* Check to make sure the lookup necessary to arrive at this inode from its
* parent is still good.
*
* Returns: 1 if the dentry is ok, 0 if it isn't
*/
static int gfs2_drevalidate(struct dentry *dentry, struct nameidata *nd)
{
struct dentry *parent;
struct gfs2_sbd *sdp;
struct gfs2_inode *dip;
struct inode *inode;
struct gfs2_holder d_gh;
struct gfs2_inode *ip = NULL;
int error;
int had_lock = 0;
if (nd && nd->flags & LOOKUP_RCU)
return -ECHILD;
parent = dget_parent(dentry);
sdp = GFS2_SB(parent->d_inode);
dip = GFS2_I(parent->d_inode);
inode = dentry->d_inode;
if (inode) {
if (is_bad_inode(inode))
goto invalid;
ip = GFS2_I(inode);
}
if (sdp->sd_lockstruct.ls_ops->lm_mount == NULL)
goto valid;
had_lock = (gfs2_glock_is_locked_by_me(dip->i_gl) != NULL);
if (!had_lock) {
error = gfs2_glock_nq_init(dip->i_gl, LM_ST_SHARED, 0, &d_gh);
if (error)
goto fail;
}
error = gfs2_dir_check(parent->d_inode, &dentry->d_name, ip);
switch (error) {
case 0:
if (!inode)
goto invalid_gunlock;
break;
case -ENOENT:
if (!inode)
goto valid_gunlock;
goto invalid_gunlock;
default:
goto fail_gunlock;
}
valid_gunlock:
if (!had_lock)
gfs2_glock_dq_uninit(&d_gh);
valid:
dput(parent);
return 1;
invalid_gunlock:
if (!had_lock)
gfs2_glock_dq_uninit(&d_gh);
invalid:
if (inode && S_ISDIR(inode->i_mode)) {
if (have_submounts(dentry))
goto valid;
shrink_dcache_parent(dentry);
}
d_drop(dentry);
dput(parent);
return 0;
fail_gunlock:
gfs2_glock_dq_uninit(&d_gh);
fail:
dput(parent);
return 0;
}
static int gfs2_dhash(const struct dentry *dentry, const struct inode *inode,
struct qstr *str)
{
str->hash = gfs2_disk_hash(str->name, str->len);
return 0;
}
static int gfs2_dentry_delete(const struct dentry *dentry)
{
struct gfs2_inode *ginode;
if (!dentry->d_inode)
return 0;
ginode = GFS2_I(dentry->d_inode);
if (!ginode->i_iopen_gh.gh_gl)
return 0;
if (test_bit(GLF_DEMOTE, &ginode->i_iopen_gh.gh_gl->gl_flags))
return 1;
return 0;
}
const struct dentry_operations gfs2_dops = {
.d_revalidate = gfs2_drevalidate,
.d_hash = gfs2_dhash,
.d_delete = gfs2_dentry_delete,
};
| gpl-2.0 |
sgp-blackphone/Blackphone-BP2-Kernel | drivers/video/nvidia/nv_hw.c | 12468 | 51720 | /***************************************************************************\
|* *|
|* Copyright 1993-2003 NVIDIA, Corporation. All rights reserved. *|
|* *|
|* NOTICE TO USER: The source code is copyrighted under U.S. and *|
|* international laws. Users and possessors of this source code are *|
|* hereby granted a nonexclusive, royalty-free copyright license to *|
|* use this code in individual and commercial software. *|
|* *|
|* Any use of this source code must include, in the user documenta- *|
|* tion and internal comments to the code, notices to the end user *|
|* as follows: *|
|* *|
|* Copyright 1993-2003 NVIDIA, Corporation. All rights reserved. *|
|* *|
|* NVIDIA, CORPORATION MAKES NO REPRESENTATION ABOUT THE SUITABILITY *|
|* OF THIS SOURCE CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" *|
|* WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. NVIDIA, CORPOR- *|
|* ATION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOURCE CODE, *|
|* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGE- *|
|* MENT, AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL *|
|* NVIDIA, CORPORATION BE LIABLE FOR ANY SPECIAL, INDIRECT, INCI- *|
|* DENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RE- *|
|* SULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION *|
|* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF *|
|* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOURCE CODE. *|
|* *|
|* U.S. Government End Users. This source code is a "commercial *|
|* item," as that term is defined at 48 C.F.R. 2.101 (OCT 1995), *|
|* consisting of "commercial computer software" and "commercial *|
|* computer software documentation," as such terms are used in *|
|* 48 C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Govern- *|
|* ment only as a commercial end item. Consistent with 48 C.F.R. *|
|* 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), *|
|* all U.S. Government End Users acquire the source code with only *|
|* those rights set forth herein. *|
|* *|
\***************************************************************************/
/*
* GPL Licensing Note - According to Mark Vojkovich, author of the Xorg/
* XFree86 'nv' driver, this source code is provided under MIT-style licensing
* where the source code is provided "as is" without warranty of any kind.
* The only usage restriction is for the copyright notices to be retained
* whenever code is used.
*
* Antonino Daplas <adaplas@pol.net> 2005-03-11
*/
/* $XFree86: xc/programs/Xserver/hw/xfree86/drivers/nv/nv_hw.c,v 1.4 2003/11/03 05:11:25 tsi Exp $ */
#include <linux/pci.h>
#include "nv_type.h"
#include "nv_local.h"
#include "nv_proto.h"
void NVLockUnlock(struct nvidia_par *par, int Lock)
{
u8 cr11;
VGA_WR08(par->PCIO, 0x3D4, 0x1F);
VGA_WR08(par->PCIO, 0x3D5, Lock ? 0x99 : 0x57);
VGA_WR08(par->PCIO, 0x3D4, 0x11);
cr11 = VGA_RD08(par->PCIO, 0x3D5);
if (Lock)
cr11 |= 0x80;
else
cr11 &= ~0x80;
VGA_WR08(par->PCIO, 0x3D5, cr11);
}
int NVShowHideCursor(struct nvidia_par *par, int ShowHide)
{
int cur = par->CurrentState->cursor1;
par->CurrentState->cursor1 = (par->CurrentState->cursor1 & 0xFE) |
(ShowHide & 0x01);
VGA_WR08(par->PCIO, 0x3D4, 0x31);
VGA_WR08(par->PCIO, 0x3D5, par->CurrentState->cursor1);
if (par->Architecture == NV_ARCH_40)
NV_WR32(par->PRAMDAC, 0x0300, NV_RD32(par->PRAMDAC, 0x0300));
return (cur & 0x01);
}
/****************************************************************************\
* *
* The video arbitration routines calculate some "magic" numbers. Fixes *
* the snow seen when accessing the framebuffer without it. *
* It just works (I hope). *
* *
\****************************************************************************/
typedef struct {
int graphics_lwm;
int video_lwm;
int graphics_burst_size;
int video_burst_size;
int valid;
} nv4_fifo_info;
typedef struct {
int pclk_khz;
int mclk_khz;
int nvclk_khz;
char mem_page_miss;
char mem_latency;
int memory_width;
char enable_video;
char gr_during_vid;
char pix_bpp;
char mem_aligned;
char enable_mp;
} nv4_sim_state;
typedef struct {
int graphics_lwm;
int video_lwm;
int graphics_burst_size;
int video_burst_size;
int valid;
} nv10_fifo_info;
typedef struct {
int pclk_khz;
int mclk_khz;
int nvclk_khz;
char mem_page_miss;
char mem_latency;
u32 memory_type;
int memory_width;
char enable_video;
char gr_during_vid;
char pix_bpp;
char mem_aligned;
char enable_mp;
} nv10_sim_state;
static void nvGetClocks(struct nvidia_par *par, unsigned int *MClk,
unsigned int *NVClk)
{
unsigned int pll, N, M, MB, NB, P;
if (par->Architecture >= NV_ARCH_40) {
pll = NV_RD32(par->PMC, 0x4020);
P = (pll >> 16) & 0x07;
pll = NV_RD32(par->PMC, 0x4024);
M = pll & 0xFF;
N = (pll >> 8) & 0xFF;
if (((par->Chipset & 0xfff0) == 0x0290) ||
((par->Chipset & 0xfff0) == 0x0390)) {
MB = 1;
NB = 1;
} else {
MB = (pll >> 16) & 0xFF;
NB = (pll >> 24) & 0xFF;
}
*MClk = ((N * NB * par->CrystalFreqKHz) / (M * MB)) >> P;
pll = NV_RD32(par->PMC, 0x4000);
P = (pll >> 16) & 0x07;
pll = NV_RD32(par->PMC, 0x4004);
M = pll & 0xFF;
N = (pll >> 8) & 0xFF;
MB = (pll >> 16) & 0xFF;
NB = (pll >> 24) & 0xFF;
*NVClk = ((N * NB * par->CrystalFreqKHz) / (M * MB)) >> P;
} else if (par->twoStagePLL) {
pll = NV_RD32(par->PRAMDAC0, 0x0504);
M = pll & 0xFF;
N = (pll >> 8) & 0xFF;
P = (pll >> 16) & 0x0F;
pll = NV_RD32(par->PRAMDAC0, 0x0574);
if (pll & 0x80000000) {
MB = pll & 0xFF;
NB = (pll >> 8) & 0xFF;
} else {
MB = 1;
NB = 1;
}
*MClk = ((N * NB * par->CrystalFreqKHz) / (M * MB)) >> P;
pll = NV_RD32(par->PRAMDAC0, 0x0500);
M = pll & 0xFF;
N = (pll >> 8) & 0xFF;
P = (pll >> 16) & 0x0F;
pll = NV_RD32(par->PRAMDAC0, 0x0570);
if (pll & 0x80000000) {
MB = pll & 0xFF;
NB = (pll >> 8) & 0xFF;
} else {
MB = 1;
NB = 1;
}
*NVClk = ((N * NB * par->CrystalFreqKHz) / (M * MB)) >> P;
} else
if (((par->Chipset & 0x0ff0) == 0x0300) ||
((par->Chipset & 0x0ff0) == 0x0330)) {
pll = NV_RD32(par->PRAMDAC0, 0x0504);
M = pll & 0x0F;
N = (pll >> 8) & 0xFF;
P = (pll >> 16) & 0x07;
if (pll & 0x00000080) {
MB = (pll >> 4) & 0x07;
NB = (pll >> 19) & 0x1f;
} else {
MB = 1;
NB = 1;
}
*MClk = ((N * NB * par->CrystalFreqKHz) / (M * MB)) >> P;
pll = NV_RD32(par->PRAMDAC0, 0x0500);
M = pll & 0x0F;
N = (pll >> 8) & 0xFF;
P = (pll >> 16) & 0x07;
if (pll & 0x00000080) {
MB = (pll >> 4) & 0x07;
NB = (pll >> 19) & 0x1f;
} else {
MB = 1;
NB = 1;
}
*NVClk = ((N * NB * par->CrystalFreqKHz) / (M * MB)) >> P;
} else {
pll = NV_RD32(par->PRAMDAC0, 0x0504);
M = pll & 0xFF;
N = (pll >> 8) & 0xFF;
P = (pll >> 16) & 0x0F;
*MClk = (N * par->CrystalFreqKHz / M) >> P;
pll = NV_RD32(par->PRAMDAC0, 0x0500);
M = pll & 0xFF;
N = (pll >> 8) & 0xFF;
P = (pll >> 16) & 0x0F;
*NVClk = (N * par->CrystalFreqKHz / M) >> P;
}
}
static void nv4CalcArbitration(nv4_fifo_info * fifo, nv4_sim_state * arb)
{
int data, pagemiss, cas, width, video_enable, bpp;
int nvclks, mclks, pclks, vpagemiss, crtpagemiss, vbs;
int found, mclk_extra, mclk_loop, cbs, m1, p1;
int mclk_freq, pclk_freq, nvclk_freq, mp_enable;
int us_m, us_n, us_p, video_drain_rate, crtc_drain_rate;
int vpm_us, us_video, vlwm, video_fill_us, cpm_us, us_crt, clwm;
fifo->valid = 1;
pclk_freq = arb->pclk_khz;
mclk_freq = arb->mclk_khz;
nvclk_freq = arb->nvclk_khz;
pagemiss = arb->mem_page_miss;
cas = arb->mem_latency;
width = arb->memory_width >> 6;
video_enable = arb->enable_video;
bpp = arb->pix_bpp;
mp_enable = arb->enable_mp;
clwm = 0;
vlwm = 0;
cbs = 128;
pclks = 2;
nvclks = 2;
nvclks += 2;
nvclks += 1;
mclks = 5;
mclks += 3;
mclks += 1;
mclks += cas;
mclks += 1;
mclks += 1;
mclks += 1;
mclks += 1;
mclk_extra = 3;
nvclks += 2;
nvclks += 1;
nvclks += 1;
nvclks += 1;
if (mp_enable)
mclks += 4;
nvclks += 0;
pclks += 0;
found = 0;
vbs = 0;
while (found != 1) {
fifo->valid = 1;
found = 1;
mclk_loop = mclks + mclk_extra;
us_m = mclk_loop * 1000 * 1000 / mclk_freq;
us_n = nvclks * 1000 * 1000 / nvclk_freq;
us_p = nvclks * 1000 * 1000 / pclk_freq;
if (video_enable) {
video_drain_rate = pclk_freq * 2;
crtc_drain_rate = pclk_freq * bpp / 8;
vpagemiss = 2;
vpagemiss += 1;
crtpagemiss = 2;
vpm_us =
(vpagemiss * pagemiss) * 1000 * 1000 / mclk_freq;
if (nvclk_freq * 2 > mclk_freq * width)
video_fill_us =
cbs * 1000 * 1000 / 16 / nvclk_freq;
else
video_fill_us =
cbs * 1000 * 1000 / (8 * width) /
mclk_freq;
us_video = vpm_us + us_m + us_n + us_p + video_fill_us;
vlwm = us_video * video_drain_rate / (1000 * 1000);
vlwm++;
vbs = 128;
if (vlwm > 128)
vbs = 64;
if (vlwm > (256 - 64))
vbs = 32;
if (nvclk_freq * 2 > mclk_freq * width)
video_fill_us =
vbs * 1000 * 1000 / 16 / nvclk_freq;
else
video_fill_us =
vbs * 1000 * 1000 / (8 * width) /
mclk_freq;
cpm_us =
crtpagemiss * pagemiss * 1000 * 1000 / mclk_freq;
us_crt =
us_video + video_fill_us + cpm_us + us_m + us_n +
us_p;
clwm = us_crt * crtc_drain_rate / (1000 * 1000);
clwm++;
} else {
crtc_drain_rate = pclk_freq * bpp / 8;
crtpagemiss = 2;
crtpagemiss += 1;
cpm_us =
crtpagemiss * pagemiss * 1000 * 1000 / mclk_freq;
us_crt = cpm_us + us_m + us_n + us_p;
clwm = us_crt * crtc_drain_rate / (1000 * 1000);
clwm++;
}
m1 = clwm + cbs - 512;
p1 = m1 * pclk_freq / mclk_freq;
p1 = p1 * bpp / 8;
if ((p1 < m1) && (m1 > 0)) {
fifo->valid = 0;
found = 0;
if (mclk_extra == 0)
found = 1;
mclk_extra--;
} else if (video_enable) {
if ((clwm > 511) || (vlwm > 255)) {
fifo->valid = 0;
found = 0;
if (mclk_extra == 0)
found = 1;
mclk_extra--;
}
} else {
if (clwm > 519) {
fifo->valid = 0;
found = 0;
if (mclk_extra == 0)
found = 1;
mclk_extra--;
}
}
if (clwm < 384)
clwm = 384;
if (vlwm < 128)
vlwm = 128;
data = (int)(clwm);
fifo->graphics_lwm = data;
fifo->graphics_burst_size = 128;
data = (int)((vlwm + 15));
fifo->video_lwm = data;
fifo->video_burst_size = vbs;
}
}
static void nv4UpdateArbitrationSettings(unsigned VClk,
unsigned pixelDepth,
unsigned *burst,
unsigned *lwm, struct nvidia_par *par)
{
nv4_fifo_info fifo_data;
nv4_sim_state sim_data;
unsigned int MClk, NVClk, cfg1;
nvGetClocks(par, &MClk, &NVClk);
cfg1 = NV_RD32(par->PFB, 0x00000204);
sim_data.pix_bpp = (char)pixelDepth;
sim_data.enable_video = 0;
sim_data.enable_mp = 0;
sim_data.memory_width = (NV_RD32(par->PEXTDEV, 0x0000) & 0x10) ?
128 : 64;
sim_data.mem_latency = (char)cfg1 & 0x0F;
sim_data.mem_aligned = 1;
sim_data.mem_page_miss =
(char)(((cfg1 >> 4) & 0x0F) + ((cfg1 >> 31) & 0x01));
sim_data.gr_during_vid = 0;
sim_data.pclk_khz = VClk;
sim_data.mclk_khz = MClk;
sim_data.nvclk_khz = NVClk;
nv4CalcArbitration(&fifo_data, &sim_data);
if (fifo_data.valid) {
int b = fifo_data.graphics_burst_size >> 4;
*burst = 0;
while (b >>= 1)
(*burst)++;
*lwm = fifo_data.graphics_lwm >> 3;
}
}
static void nv10CalcArbitration(nv10_fifo_info * fifo, nv10_sim_state * arb)
{
int data, pagemiss, width, video_enable, bpp;
int nvclks, mclks, pclks, vpagemiss, crtpagemiss;
int nvclk_fill;
int found, mclk_extra, mclk_loop, cbs, m1;
int mclk_freq, pclk_freq, nvclk_freq, mp_enable;
int us_m, us_m_min, us_n, us_p, crtc_drain_rate;
int vus_m;
int vpm_us, us_video, cpm_us, us_crt, clwm;
int clwm_rnd_down;
int m2us, us_pipe_min, p1clk, p2;
int min_mclk_extra;
int us_min_mclk_extra;
fifo->valid = 1;
pclk_freq = arb->pclk_khz; /* freq in KHz */
mclk_freq = arb->mclk_khz;
nvclk_freq = arb->nvclk_khz;
pagemiss = arb->mem_page_miss;
width = arb->memory_width / 64;
video_enable = arb->enable_video;
bpp = arb->pix_bpp;
mp_enable = arb->enable_mp;
clwm = 0;
cbs = 512;
pclks = 4; /* lwm detect. */
nvclks = 3; /* lwm -> sync. */
nvclks += 2; /* fbi bus cycles (1 req + 1 busy) */
/* 2 edge sync. may be very close to edge so just put one. */
mclks = 1;
mclks += 1; /* arb_hp_req */
mclks += 5; /* ap_hp_req tiling pipeline */
mclks += 2; /* tc_req latency fifo */
mclks += 2; /* fb_cas_n_ memory request to fbio block */
mclks += 7; /* sm_d_rdv data returned from fbio block */
/* fb.rd.d.Put_gc need to accumulate 256 bits for read */
if (arb->memory_type == 0)
if (arb->memory_width == 64) /* 64 bit bus */
mclks += 4;
else
mclks += 2;
else if (arb->memory_width == 64) /* 64 bit bus */
mclks += 2;
else
mclks += 1;
if ((!video_enable) && (arb->memory_width == 128)) {
mclk_extra = (bpp == 32) ? 31 : 42; /* Margin of error */
min_mclk_extra = 17;
} else {
mclk_extra = (bpp == 32) ? 8 : 4; /* Margin of error */
/* mclk_extra = 4; *//* Margin of error */
min_mclk_extra = 18;
}
/* 2 edge sync. may be very close to edge so just put one. */
nvclks += 1;
nvclks += 1; /* fbi_d_rdv_n */
nvclks += 1; /* Fbi_d_rdata */
nvclks += 1; /* crtfifo load */
if (mp_enable)
mclks += 4; /* Mp can get in with a burst of 8. */
/* Extra clocks determined by heuristics */
nvclks += 0;
pclks += 0;
found = 0;
while (found != 1) {
fifo->valid = 1;
found = 1;
mclk_loop = mclks + mclk_extra;
/* Mclk latency in us */
us_m = mclk_loop * 1000 * 1000 / mclk_freq;
/* Minimum Mclk latency in us */
us_m_min = mclks * 1000 * 1000 / mclk_freq;
us_min_mclk_extra = min_mclk_extra * 1000 * 1000 / mclk_freq;
/* nvclk latency in us */
us_n = nvclks * 1000 * 1000 / nvclk_freq;
/* nvclk latency in us */
us_p = pclks * 1000 * 1000 / pclk_freq;
us_pipe_min = us_m_min + us_n + us_p;
/* Mclk latency in us */
vus_m = mclk_loop * 1000 * 1000 / mclk_freq;
if (video_enable) {
crtc_drain_rate = pclk_freq * bpp / 8; /* MB/s */
vpagemiss = 1; /* self generating page miss */
vpagemiss += 1; /* One higher priority before */
crtpagemiss = 2; /* self generating page miss */
if (mp_enable)
crtpagemiss += 1; /* if MA0 conflict */
vpm_us =
(vpagemiss * pagemiss) * 1000 * 1000 / mclk_freq;
/* Video has separate read return path */
us_video = vpm_us + vus_m;
cpm_us =
crtpagemiss * pagemiss * 1000 * 1000 / mclk_freq;
/* Wait for video */
us_crt = us_video
+ cpm_us /* CRT Page miss */
+ us_m + us_n + us_p /* other latency */
;
clwm = us_crt * crtc_drain_rate / (1000 * 1000);
/* fixed point <= float_point - 1. Fixes that */
clwm++;
} else {
/* bpp * pclk/8 */
crtc_drain_rate = pclk_freq * bpp / 8;
crtpagemiss = 1; /* self generating page miss */
crtpagemiss += 1; /* MA0 page miss */
if (mp_enable)
crtpagemiss += 1; /* if MA0 conflict */
cpm_us =
crtpagemiss * pagemiss * 1000 * 1000 / mclk_freq;
us_crt = cpm_us + us_m + us_n + us_p;
clwm = us_crt * crtc_drain_rate / (1000 * 1000);
/* fixed point <= float_point - 1. Fixes that */
clwm++;
/* Finally, a heuristic check when width == 64 bits */
if (width == 1) {
nvclk_fill = nvclk_freq * 8;
if (crtc_drain_rate * 100 >= nvclk_fill * 102)
/*Large number to fail */
clwm = 0xfff;
else if (crtc_drain_rate * 100 >=
nvclk_fill * 98) {
clwm = 1024;
cbs = 512;
}
}
}
/*
Overfill check:
*/
clwm_rnd_down = ((int)clwm / 8) * 8;
if (clwm_rnd_down < clwm)
clwm += 8;
m1 = clwm + cbs - 1024; /* Amount of overfill */
m2us = us_pipe_min + us_min_mclk_extra;
/* pclk cycles to drain */
p1clk = m2us * pclk_freq / (1000 * 1000);
p2 = p1clk * bpp / 8; /* bytes drained. */
if ((p2 < m1) && (m1 > 0)) {
fifo->valid = 0;
found = 0;
if (min_mclk_extra == 0) {
if (cbs <= 32) {
/* Can't adjust anymore! */
found = 1;
} else {
/* reduce the burst size */
cbs = cbs / 2;
}
} else {
min_mclk_extra--;
}
} else {
if (clwm > 1023) { /* Have some margin */
fifo->valid = 0;
found = 0;
if (min_mclk_extra == 0)
/* Can't adjust anymore! */
found = 1;
else
min_mclk_extra--;
}
}
if (clwm < (1024 - cbs + 8))
clwm = 1024 - cbs + 8;
data = (int)(clwm);
/* printf("CRT LWM: %f bytes, prog: 0x%x, bs: 256\n",
clwm, data ); */
fifo->graphics_lwm = data;
fifo->graphics_burst_size = cbs;
fifo->video_lwm = 1024;
fifo->video_burst_size = 512;
}
}
static void nv10UpdateArbitrationSettings(unsigned VClk,
unsigned pixelDepth,
unsigned *burst,
unsigned *lwm,
struct nvidia_par *par)
{
nv10_fifo_info fifo_data;
nv10_sim_state sim_data;
unsigned int MClk, NVClk, cfg1;
nvGetClocks(par, &MClk, &NVClk);
cfg1 = NV_RD32(par->PFB, 0x0204);
sim_data.pix_bpp = (char)pixelDepth;
sim_data.enable_video = 1;
sim_data.enable_mp = 0;
sim_data.memory_type = (NV_RD32(par->PFB, 0x0200) & 0x01) ? 1 : 0;
sim_data.memory_width = (NV_RD32(par->PEXTDEV, 0x0000) & 0x10) ?
128 : 64;
sim_data.mem_latency = (char)cfg1 & 0x0F;
sim_data.mem_aligned = 1;
sim_data.mem_page_miss =
(char)(((cfg1 >> 4) & 0x0F) + ((cfg1 >> 31) & 0x01));
sim_data.gr_during_vid = 0;
sim_data.pclk_khz = VClk;
sim_data.mclk_khz = MClk;
sim_data.nvclk_khz = NVClk;
nv10CalcArbitration(&fifo_data, &sim_data);
if (fifo_data.valid) {
int b = fifo_data.graphics_burst_size >> 4;
*burst = 0;
while (b >>= 1)
(*burst)++;
*lwm = fifo_data.graphics_lwm >> 3;
}
}
static void nv30UpdateArbitrationSettings (
struct nvidia_par *par,
unsigned int *burst,
unsigned int *lwm
)
{
unsigned int MClk, NVClk;
unsigned int fifo_size, burst_size, graphics_lwm;
fifo_size = 2048;
burst_size = 512;
graphics_lwm = fifo_size - burst_size;
nvGetClocks(par, &MClk, &NVClk);
*burst = 0;
burst_size >>= 5;
while(burst_size >>= 1) (*burst)++;
*lwm = graphics_lwm >> 3;
}
static void nForceUpdateArbitrationSettings(unsigned VClk,
unsigned pixelDepth,
unsigned *burst,
unsigned *lwm,
struct nvidia_par *par)
{
nv10_fifo_info fifo_data;
nv10_sim_state sim_data;
unsigned int M, N, P, pll, MClk, NVClk, memctrl;
struct pci_dev *dev;
if ((par->Chipset & 0x0FF0) == 0x01A0) {
unsigned int uMClkPostDiv;
dev = pci_get_bus_and_slot(0, 3);
pci_read_config_dword(dev, 0x6C, &uMClkPostDiv);
uMClkPostDiv = (uMClkPostDiv >> 8) & 0xf;
if (!uMClkPostDiv)
uMClkPostDiv = 4;
MClk = 400000 / uMClkPostDiv;
} else {
dev = pci_get_bus_and_slot(0, 5);
pci_read_config_dword(dev, 0x4c, &MClk);
MClk /= 1000;
}
pci_dev_put(dev);
pll = NV_RD32(par->PRAMDAC0, 0x0500);
M = (pll >> 0) & 0xFF;
N = (pll >> 8) & 0xFF;
P = (pll >> 16) & 0x0F;
NVClk = (N * par->CrystalFreqKHz / M) >> P;
sim_data.pix_bpp = (char)pixelDepth;
sim_data.enable_video = 0;
sim_data.enable_mp = 0;
dev = pci_get_bus_and_slot(0, 1);
pci_read_config_dword(dev, 0x7C, &sim_data.memory_type);
pci_dev_put(dev);
sim_data.memory_type = (sim_data.memory_type >> 12) & 1;
sim_data.memory_width = 64;
dev = pci_get_bus_and_slot(0, 3);
pci_read_config_dword(dev, 0, &memctrl);
pci_dev_put(dev);
memctrl >>= 16;
if ((memctrl == 0x1A9) || (memctrl == 0x1AB) || (memctrl == 0x1ED)) {
u32 dimm[3];
dev = pci_get_bus_and_slot(0, 2);
pci_read_config_dword(dev, 0x40, &dimm[0]);
dimm[0] = (dimm[0] >> 8) & 0x4f;
pci_read_config_dword(dev, 0x44, &dimm[1]);
dimm[1] = (dimm[1] >> 8) & 0x4f;
pci_read_config_dword(dev, 0x48, &dimm[2]);
dimm[2] = (dimm[2] >> 8) & 0x4f;
if ((dimm[0] + dimm[1]) != dimm[2]) {
printk("nvidiafb: your nForce DIMMs are not arranged "
"in optimal banks!\n");
}
pci_dev_put(dev);
}
sim_data.mem_latency = 3;
sim_data.mem_aligned = 1;
sim_data.mem_page_miss = 10;
sim_data.gr_during_vid = 0;
sim_data.pclk_khz = VClk;
sim_data.mclk_khz = MClk;
sim_data.nvclk_khz = NVClk;
nv10CalcArbitration(&fifo_data, &sim_data);
if (fifo_data.valid) {
int b = fifo_data.graphics_burst_size >> 4;
*burst = 0;
while (b >>= 1)
(*burst)++;
*lwm = fifo_data.graphics_lwm >> 3;
}
}
/****************************************************************************\
* *
* RIVA Mode State Routines *
* *
\****************************************************************************/
/*
* Calculate the Video Clock parameters for the PLL.
*/
static void CalcVClock(int clockIn,
int *clockOut, u32 * pllOut, struct nvidia_par *par)
{
unsigned lowM, highM;
unsigned DeltaNew, DeltaOld;
unsigned VClk, Freq;
unsigned M, N, P;
DeltaOld = 0xFFFFFFFF;
VClk = (unsigned)clockIn;
if (par->CrystalFreqKHz == 13500) {
lowM = 7;
highM = 13;
} else {
lowM = 8;
highM = 14;
}
for (P = 0; P <= 4; P++) {
Freq = VClk << P;
if ((Freq >= 128000) && (Freq <= 350000)) {
for (M = lowM; M <= highM; M++) {
N = ((VClk << P) * M) / par->CrystalFreqKHz;
if (N <= 255) {
Freq =
((par->CrystalFreqKHz * N) /
M) >> P;
if (Freq > VClk)
DeltaNew = Freq - VClk;
else
DeltaNew = VClk - Freq;
if (DeltaNew < DeltaOld) {
*pllOut =
(P << 16) | (N << 8) | M;
*clockOut = Freq;
DeltaOld = DeltaNew;
}
}
}
}
}
}
static void CalcVClock2Stage(int clockIn,
int *clockOut,
u32 * pllOut,
u32 * pllBOut, struct nvidia_par *par)
{
unsigned DeltaNew, DeltaOld;
unsigned VClk, Freq;
unsigned M, N, P;
DeltaOld = 0xFFFFFFFF;
*pllBOut = 0x80000401; /* fixed at x4 for now */
VClk = (unsigned)clockIn;
for (P = 0; P <= 6; P++) {
Freq = VClk << P;
if ((Freq >= 400000) && (Freq <= 1000000)) {
for (M = 1; M <= 13; M++) {
N = ((VClk << P) * M) /
(par->CrystalFreqKHz << 2);
if ((N >= 5) && (N <= 255)) {
Freq =
(((par->CrystalFreqKHz << 2) * N) /
M) >> P;
if (Freq > VClk)
DeltaNew = Freq - VClk;
else
DeltaNew = VClk - Freq;
if (DeltaNew < DeltaOld) {
*pllOut =
(P << 16) | (N << 8) | M;
*clockOut = Freq;
DeltaOld = DeltaNew;
}
}
}
}
}
}
/*
* Calculate extended mode parameters (SVGA) and save in a
* mode state structure.
*/
void NVCalcStateExt(struct nvidia_par *par,
RIVA_HW_STATE * state,
int bpp,
int width,
int hDisplaySize, int height, int dotClock, int flags)
{
int pixelDepth, VClk = 0;
/*
* Save mode parameters.
*/
state->bpp = bpp; /* this is not bitsPerPixel, it's 8,15,16,32 */
state->width = width;
state->height = height;
/*
* Extended RIVA registers.
*/
pixelDepth = (bpp + 1) / 8;
if (par->twoStagePLL)
CalcVClock2Stage(dotClock, &VClk, &state->pll, &state->pllB,
par);
else
CalcVClock(dotClock, &VClk, &state->pll, par);
switch (par->Architecture) {
case NV_ARCH_04:
nv4UpdateArbitrationSettings(VClk,
pixelDepth * 8,
&(state->arbitration0),
&(state->arbitration1), par);
state->cursor0 = 0x00;
state->cursor1 = 0xbC;
if (flags & FB_VMODE_DOUBLE)
state->cursor1 |= 2;
state->cursor2 = 0x00000000;
state->pllsel = 0x10000700;
state->config = 0x00001114;
state->general = bpp == 16 ? 0x00101100 : 0x00100100;
state->repaint1 = hDisplaySize < 1280 ? 0x04 : 0x00;
break;
case NV_ARCH_40:
if (!par->FlatPanel)
state->control = NV_RD32(par->PRAMDAC0, 0x0580) &
0xeffffeff;
/* fallthrough */
case NV_ARCH_10:
case NV_ARCH_20:
case NV_ARCH_30:
default:
if ((par->Chipset & 0xfff0) == 0x0240 ||
(par->Chipset & 0xfff0) == 0x03d0) {
state->arbitration0 = 256;
state->arbitration1 = 0x0480;
} else if (((par->Chipset & 0xffff) == 0x01A0) ||
((par->Chipset & 0xffff) == 0x01f0)) {
nForceUpdateArbitrationSettings(VClk,
pixelDepth * 8,
&(state->arbitration0),
&(state->arbitration1),
par);
} else if (par->Architecture < NV_ARCH_30) {
nv10UpdateArbitrationSettings(VClk,
pixelDepth * 8,
&(state->arbitration0),
&(state->arbitration1),
par);
} else {
nv30UpdateArbitrationSettings(par,
&(state->arbitration0),
&(state->arbitration1));
}
state->cursor0 = 0x80 | (par->CursorStart >> 17);
state->cursor1 = (par->CursorStart >> 11) << 2;
state->cursor2 = par->CursorStart >> 24;
if (flags & FB_VMODE_DOUBLE)
state->cursor1 |= 2;
state->pllsel = 0x10000700;
state->config = NV_RD32(par->PFB, 0x00000200);
state->general = bpp == 16 ? 0x00101100 : 0x00100100;
state->repaint1 = hDisplaySize < 1280 ? 0x04 : 0x00;
break;
}
if (bpp != 8) /* DirectColor */
state->general |= 0x00000030;
state->repaint0 = (((width / 8) * pixelDepth) & 0x700) >> 3;
state->pixel = (pixelDepth > 2) ? 3 : pixelDepth;
}
void NVLoadStateExt(struct nvidia_par *par, RIVA_HW_STATE * state)
{
int i, j;
NV_WR32(par->PMC, 0x0140, 0x00000000);
NV_WR32(par->PMC, 0x0200, 0xFFFF00FF);
NV_WR32(par->PMC, 0x0200, 0xFFFFFFFF);
NV_WR32(par->PTIMER, 0x0200 * 4, 0x00000008);
NV_WR32(par->PTIMER, 0x0210 * 4, 0x00000003);
NV_WR32(par->PTIMER, 0x0140 * 4, 0x00000000);
NV_WR32(par->PTIMER, 0x0100 * 4, 0xFFFFFFFF);
if (par->Architecture == NV_ARCH_04) {
if (state)
NV_WR32(par->PFB, 0x0200, state->config);
} else if ((par->Architecture < NV_ARCH_40) ||
(par->Chipset & 0xfff0) == 0x0040) {
for (i = 0; i < 8; i++) {
NV_WR32(par->PFB, 0x0240 + (i * 0x10), 0);
NV_WR32(par->PFB, 0x0244 + (i * 0x10),
par->FbMapSize - 1);
}
} else {
int regions = 12;
if (((par->Chipset & 0xfff0) == 0x0090) ||
((par->Chipset & 0xfff0) == 0x01D0) ||
((par->Chipset & 0xfff0) == 0x0290) ||
((par->Chipset & 0xfff0) == 0x0390) ||
((par->Chipset & 0xfff0) == 0x03D0))
regions = 15;
for(i = 0; i < regions; i++) {
NV_WR32(par->PFB, 0x0600 + (i * 0x10), 0);
NV_WR32(par->PFB, 0x0604 + (i * 0x10),
par->FbMapSize - 1);
}
}
if (par->Architecture >= NV_ARCH_40) {
NV_WR32(par->PRAMIN, 0x0000 * 4, 0x80000010);
NV_WR32(par->PRAMIN, 0x0001 * 4, 0x00101202);
NV_WR32(par->PRAMIN, 0x0002 * 4, 0x80000011);
NV_WR32(par->PRAMIN, 0x0003 * 4, 0x00101204);
NV_WR32(par->PRAMIN, 0x0004 * 4, 0x80000012);
NV_WR32(par->PRAMIN, 0x0005 * 4, 0x00101206);
NV_WR32(par->PRAMIN, 0x0006 * 4, 0x80000013);
NV_WR32(par->PRAMIN, 0x0007 * 4, 0x00101208);
NV_WR32(par->PRAMIN, 0x0008 * 4, 0x80000014);
NV_WR32(par->PRAMIN, 0x0009 * 4, 0x0010120A);
NV_WR32(par->PRAMIN, 0x000A * 4, 0x80000015);
NV_WR32(par->PRAMIN, 0x000B * 4, 0x0010120C);
NV_WR32(par->PRAMIN, 0x000C * 4, 0x80000016);
NV_WR32(par->PRAMIN, 0x000D * 4, 0x0010120E);
NV_WR32(par->PRAMIN, 0x000E * 4, 0x80000017);
NV_WR32(par->PRAMIN, 0x000F * 4, 0x00101210);
NV_WR32(par->PRAMIN, 0x0800 * 4, 0x00003000);
NV_WR32(par->PRAMIN, 0x0801 * 4, par->FbMapSize - 1);
NV_WR32(par->PRAMIN, 0x0802 * 4, 0x00000002);
NV_WR32(par->PRAMIN, 0x0808 * 4, 0x02080062);
NV_WR32(par->PRAMIN, 0x0809 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x080A * 4, 0x00001200);
NV_WR32(par->PRAMIN, 0x080B * 4, 0x00001200);
NV_WR32(par->PRAMIN, 0x080C * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x080D * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0810 * 4, 0x02080043);
NV_WR32(par->PRAMIN, 0x0811 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0812 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0813 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0814 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0815 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0818 * 4, 0x02080044);
NV_WR32(par->PRAMIN, 0x0819 * 4, 0x02000000);
NV_WR32(par->PRAMIN, 0x081A * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x081B * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x081C * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x081D * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0820 * 4, 0x02080019);
NV_WR32(par->PRAMIN, 0x0821 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0822 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0823 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0824 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0825 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0828 * 4, 0x020A005C);
NV_WR32(par->PRAMIN, 0x0829 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x082A * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x082B * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x082C * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x082D * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0830 * 4, 0x0208009F);
NV_WR32(par->PRAMIN, 0x0831 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0832 * 4, 0x00001200);
NV_WR32(par->PRAMIN, 0x0833 * 4, 0x00001200);
NV_WR32(par->PRAMIN, 0x0834 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0835 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0838 * 4, 0x0208004A);
NV_WR32(par->PRAMIN, 0x0839 * 4, 0x02000000);
NV_WR32(par->PRAMIN, 0x083A * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x083B * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x083C * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x083D * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0840 * 4, 0x02080077);
NV_WR32(par->PRAMIN, 0x0841 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0842 * 4, 0x00001200);
NV_WR32(par->PRAMIN, 0x0843 * 4, 0x00001200);
NV_WR32(par->PRAMIN, 0x0844 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0845 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x084C * 4, 0x00003002);
NV_WR32(par->PRAMIN, 0x084D * 4, 0x00007FFF);
NV_WR32(par->PRAMIN, 0x084E * 4,
par->FbUsableSize | 0x00000002);
#ifdef __BIG_ENDIAN
NV_WR32(par->PRAMIN, 0x080A * 4,
NV_RD32(par->PRAMIN, 0x080A * 4) | 0x01000000);
NV_WR32(par->PRAMIN, 0x0812 * 4,
NV_RD32(par->PRAMIN, 0x0812 * 4) | 0x01000000);
NV_WR32(par->PRAMIN, 0x081A * 4,
NV_RD32(par->PRAMIN, 0x081A * 4) | 0x01000000);
NV_WR32(par->PRAMIN, 0x0822 * 4,
NV_RD32(par->PRAMIN, 0x0822 * 4) | 0x01000000);
NV_WR32(par->PRAMIN, 0x082A * 4,
NV_RD32(par->PRAMIN, 0x082A * 4) | 0x01000000);
NV_WR32(par->PRAMIN, 0x0832 * 4,
NV_RD32(par->PRAMIN, 0x0832 * 4) | 0x01000000);
NV_WR32(par->PRAMIN, 0x083A * 4,
NV_RD32(par->PRAMIN, 0x083A * 4) | 0x01000000);
NV_WR32(par->PRAMIN, 0x0842 * 4,
NV_RD32(par->PRAMIN, 0x0842 * 4) | 0x01000000);
NV_WR32(par->PRAMIN, 0x0819 * 4, 0x01000000);
NV_WR32(par->PRAMIN, 0x0839 * 4, 0x01000000);
#endif
} else {
NV_WR32(par->PRAMIN, 0x0000 * 4, 0x80000010);
NV_WR32(par->PRAMIN, 0x0001 * 4, 0x80011201);
NV_WR32(par->PRAMIN, 0x0002 * 4, 0x80000011);
NV_WR32(par->PRAMIN, 0x0003 * 4, 0x80011202);
NV_WR32(par->PRAMIN, 0x0004 * 4, 0x80000012);
NV_WR32(par->PRAMIN, 0x0005 * 4, 0x80011203);
NV_WR32(par->PRAMIN, 0x0006 * 4, 0x80000013);
NV_WR32(par->PRAMIN, 0x0007 * 4, 0x80011204);
NV_WR32(par->PRAMIN, 0x0008 * 4, 0x80000014);
NV_WR32(par->PRAMIN, 0x0009 * 4, 0x80011205);
NV_WR32(par->PRAMIN, 0x000A * 4, 0x80000015);
NV_WR32(par->PRAMIN, 0x000B * 4, 0x80011206);
NV_WR32(par->PRAMIN, 0x000C * 4, 0x80000016);
NV_WR32(par->PRAMIN, 0x000D * 4, 0x80011207);
NV_WR32(par->PRAMIN, 0x000E * 4, 0x80000017);
NV_WR32(par->PRAMIN, 0x000F * 4, 0x80011208);
NV_WR32(par->PRAMIN, 0x0800 * 4, 0x00003000);
NV_WR32(par->PRAMIN, 0x0801 * 4, par->FbMapSize - 1);
NV_WR32(par->PRAMIN, 0x0802 * 4, 0x00000002);
NV_WR32(par->PRAMIN, 0x0803 * 4, 0x00000002);
if (par->Architecture >= NV_ARCH_10)
NV_WR32(par->PRAMIN, 0x0804 * 4, 0x01008062);
else
NV_WR32(par->PRAMIN, 0x0804 * 4, 0x01008042);
NV_WR32(par->PRAMIN, 0x0805 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0806 * 4, 0x12001200);
NV_WR32(par->PRAMIN, 0x0807 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0808 * 4, 0x01008043);
NV_WR32(par->PRAMIN, 0x0809 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x080A * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x080B * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x080C * 4, 0x01008044);
NV_WR32(par->PRAMIN, 0x080D * 4, 0x00000002);
NV_WR32(par->PRAMIN, 0x080E * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x080F * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0810 * 4, 0x01008019);
NV_WR32(par->PRAMIN, 0x0811 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0812 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0813 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0814 * 4, 0x0100A05C);
NV_WR32(par->PRAMIN, 0x0815 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0816 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0817 * 4, 0x00000000);
if (par->WaitVSyncPossible)
NV_WR32(par->PRAMIN, 0x0818 * 4, 0x0100809F);
else
NV_WR32(par->PRAMIN, 0x0818 * 4, 0x0100805F);
NV_WR32(par->PRAMIN, 0x0819 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x081A * 4, 0x12001200);
NV_WR32(par->PRAMIN, 0x081B * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x081C * 4, 0x0100804A);
NV_WR32(par->PRAMIN, 0x081D * 4, 0x00000002);
NV_WR32(par->PRAMIN, 0x081E * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x081F * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0820 * 4, 0x01018077);
NV_WR32(par->PRAMIN, 0x0821 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0822 * 4, 0x12001200);
NV_WR32(par->PRAMIN, 0x0823 * 4, 0x00000000);
NV_WR32(par->PRAMIN, 0x0824 * 4, 0x00003002);
NV_WR32(par->PRAMIN, 0x0825 * 4, 0x00007FFF);
NV_WR32(par->PRAMIN, 0x0826 * 4,
par->FbUsableSize | 0x00000002);
NV_WR32(par->PRAMIN, 0x0827 * 4, 0x00000002);
#ifdef __BIG_ENDIAN
NV_WR32(par->PRAMIN, 0x0804 * 4,
NV_RD32(par->PRAMIN, 0x0804 * 4) | 0x00080000);
NV_WR32(par->PRAMIN, 0x0808 * 4,
NV_RD32(par->PRAMIN, 0x0808 * 4) | 0x00080000);
NV_WR32(par->PRAMIN, 0x080C * 4,
NV_RD32(par->PRAMIN, 0x080C * 4) | 0x00080000);
NV_WR32(par->PRAMIN, 0x0810 * 4,
NV_RD32(par->PRAMIN, 0x0810 * 4) | 0x00080000);
NV_WR32(par->PRAMIN, 0x0814 * 4,
NV_RD32(par->PRAMIN, 0x0814 * 4) | 0x00080000);
NV_WR32(par->PRAMIN, 0x0818 * 4,
NV_RD32(par->PRAMIN, 0x0818 * 4) | 0x00080000);
NV_WR32(par->PRAMIN, 0x081C * 4,
NV_RD32(par->PRAMIN, 0x081C * 4) | 0x00080000);
NV_WR32(par->PRAMIN, 0x0820 * 4,
NV_RD32(par->PRAMIN, 0x0820 * 4) | 0x00080000);
NV_WR32(par->PRAMIN, 0x080D * 4, 0x00000001);
NV_WR32(par->PRAMIN, 0x081D * 4, 0x00000001);
#endif
}
if (par->Architecture < NV_ARCH_10) {
if ((par->Chipset & 0x0fff) == 0x0020) {
NV_WR32(par->PRAMIN, 0x0824 * 4,
NV_RD32(par->PRAMIN, 0x0824 * 4) | 0x00020000);
NV_WR32(par->PRAMIN, 0x0826 * 4,
NV_RD32(par->PRAMIN,
0x0826 * 4) + par->FbAddress);
}
NV_WR32(par->PGRAPH, 0x0080, 0x000001FF);
NV_WR32(par->PGRAPH, 0x0080, 0x1230C000);
NV_WR32(par->PGRAPH, 0x0084, 0x72111101);
NV_WR32(par->PGRAPH, 0x0088, 0x11D5F071);
NV_WR32(par->PGRAPH, 0x008C, 0x0004FF31);
NV_WR32(par->PGRAPH, 0x008C, 0x4004FF31);
NV_WR32(par->PGRAPH, 0x0140, 0x00000000);
NV_WR32(par->PGRAPH, 0x0100, 0xFFFFFFFF);
NV_WR32(par->PGRAPH, 0x0170, 0x10010100);
NV_WR32(par->PGRAPH, 0x0710, 0xFFFFFFFF);
NV_WR32(par->PGRAPH, 0x0720, 0x00000001);
NV_WR32(par->PGRAPH, 0x0810, 0x00000000);
NV_WR32(par->PGRAPH, 0x0608, 0xFFFFFFFF);
} else {
NV_WR32(par->PGRAPH, 0x0080, 0xFFFFFFFF);
NV_WR32(par->PGRAPH, 0x0080, 0x00000000);
NV_WR32(par->PGRAPH, 0x0140, 0x00000000);
NV_WR32(par->PGRAPH, 0x0100, 0xFFFFFFFF);
NV_WR32(par->PGRAPH, 0x0144, 0x10010100);
NV_WR32(par->PGRAPH, 0x0714, 0xFFFFFFFF);
NV_WR32(par->PGRAPH, 0x0720, 0x00000001);
NV_WR32(par->PGRAPH, 0x0710,
NV_RD32(par->PGRAPH, 0x0710) & 0x0007ff00);
NV_WR32(par->PGRAPH, 0x0710,
NV_RD32(par->PGRAPH, 0x0710) | 0x00020100);
if (par->Architecture == NV_ARCH_10) {
NV_WR32(par->PGRAPH, 0x0084, 0x00118700);
NV_WR32(par->PGRAPH, 0x0088, 0x24E00810);
NV_WR32(par->PGRAPH, 0x008C, 0x55DE0030);
for (i = 0; i < 32; i++)
NV_WR32(&par->PGRAPH[(0x0B00 / 4) + i], 0,
NV_RD32(&par->PFB[(0x0240 / 4) + i],
0));
NV_WR32(par->PGRAPH, 0x640, 0);
NV_WR32(par->PGRAPH, 0x644, 0);
NV_WR32(par->PGRAPH, 0x684, par->FbMapSize - 1);
NV_WR32(par->PGRAPH, 0x688, par->FbMapSize - 1);
NV_WR32(par->PGRAPH, 0x0810, 0x00000000);
NV_WR32(par->PGRAPH, 0x0608, 0xFFFFFFFF);
} else {
if (par->Architecture >= NV_ARCH_40) {
NV_WR32(par->PGRAPH, 0x0084, 0x401287c0);
NV_WR32(par->PGRAPH, 0x008C, 0x60de8051);
NV_WR32(par->PGRAPH, 0x0090, 0x00008000);
NV_WR32(par->PGRAPH, 0x0610, 0x00be3c5f);
NV_WR32(par->PGRAPH, 0x0bc4,
NV_RD32(par->PGRAPH, 0x0bc4) |
0x00008000);
j = NV_RD32(par->REGS, 0x1540) & 0xff;
if (j) {
for (i = 0; !(j & 1); j >>= 1, i++);
NV_WR32(par->PGRAPH, 0x5000, i);
}
if ((par->Chipset & 0xfff0) == 0x0040) {
NV_WR32(par->PGRAPH, 0x09b0,
0x83280fff);
NV_WR32(par->PGRAPH, 0x09b4,
0x000000a0);
} else {
NV_WR32(par->PGRAPH, 0x0820,
0x83280eff);
NV_WR32(par->PGRAPH, 0x0824,
0x000000a0);
}
switch (par->Chipset & 0xfff0) {
case 0x0040:
case 0x0210:
NV_WR32(par->PGRAPH, 0x09b8,
0x0078e366);
NV_WR32(par->PGRAPH, 0x09bc,
0x0000014c);
NV_WR32(par->PFB, 0x033C,
NV_RD32(par->PFB, 0x33C) &
0xffff7fff);
break;
case 0x00C0:
case 0x0120:
NV_WR32(par->PGRAPH, 0x0828,
0x007596ff);
NV_WR32(par->PGRAPH, 0x082C,
0x00000108);
break;
case 0x0160:
case 0x01D0:
case 0x0240:
case 0x03D0:
NV_WR32(par->PMC, 0x1700,
NV_RD32(par->PFB, 0x020C));
NV_WR32(par->PMC, 0x1704, 0);
NV_WR32(par->PMC, 0x1708, 0);
NV_WR32(par->PMC, 0x170C,
NV_RD32(par->PFB, 0x020C));
NV_WR32(par->PGRAPH, 0x0860, 0);
NV_WR32(par->PGRAPH, 0x0864, 0);
NV_WR32(par->PRAMDAC, 0x0608,
NV_RD32(par->PRAMDAC,
0x0608) | 0x00100000);
break;
case 0x0140:
NV_WR32(par->PGRAPH, 0x0828,
0x0072cb77);
NV_WR32(par->PGRAPH, 0x082C,
0x00000108);
break;
case 0x0220:
NV_WR32(par->PGRAPH, 0x0860, 0);
NV_WR32(par->PGRAPH, 0x0864, 0);
NV_WR32(par->PRAMDAC, 0x0608,
NV_RD32(par->PRAMDAC, 0x0608) |
0x00100000);
break;
case 0x0090:
case 0x0290:
case 0x0390:
NV_WR32(par->PRAMDAC, 0x0608,
NV_RD32(par->PRAMDAC, 0x0608) |
0x00100000);
NV_WR32(par->PGRAPH, 0x0828,
0x07830610);
NV_WR32(par->PGRAPH, 0x082C,
0x0000016A);
break;
default:
break;
};
NV_WR32(par->PGRAPH, 0x0b38, 0x2ffff800);
NV_WR32(par->PGRAPH, 0x0b3c, 0x00006000);
NV_WR32(par->PGRAPH, 0x032C, 0x01000000);
NV_WR32(par->PGRAPH, 0x0220, 0x00001200);
} else if (par->Architecture == NV_ARCH_30) {
NV_WR32(par->PGRAPH, 0x0084, 0x40108700);
NV_WR32(par->PGRAPH, 0x0890, 0x00140000);
NV_WR32(par->PGRAPH, 0x008C, 0xf00e0431);
NV_WR32(par->PGRAPH, 0x0090, 0x00008000);
NV_WR32(par->PGRAPH, 0x0610, 0xf04b1f36);
NV_WR32(par->PGRAPH, 0x0B80, 0x1002d888);
NV_WR32(par->PGRAPH, 0x0B88, 0x62ff007f);
} else {
NV_WR32(par->PGRAPH, 0x0084, 0x00118700);
NV_WR32(par->PGRAPH, 0x008C, 0xF20E0431);
NV_WR32(par->PGRAPH, 0x0090, 0x00000000);
NV_WR32(par->PGRAPH, 0x009C, 0x00000040);
if ((par->Chipset & 0x0ff0) >= 0x0250) {
NV_WR32(par->PGRAPH, 0x0890,
0x00080000);
NV_WR32(par->PGRAPH, 0x0610,
0x304B1FB6);
NV_WR32(par->PGRAPH, 0x0B80,
0x18B82880);
NV_WR32(par->PGRAPH, 0x0B84,
0x44000000);
NV_WR32(par->PGRAPH, 0x0098,
0x40000080);
NV_WR32(par->PGRAPH, 0x0B88,
0x000000ff);
} else {
NV_WR32(par->PGRAPH, 0x0880,
0x00080000);
NV_WR32(par->PGRAPH, 0x0094,
0x00000005);
NV_WR32(par->PGRAPH, 0x0B80,
0x45CAA208);
NV_WR32(par->PGRAPH, 0x0B84,
0x24000000);
NV_WR32(par->PGRAPH, 0x0098,
0x00000040);
NV_WR32(par->PGRAPH, 0x0750,
0x00E00038);
NV_WR32(par->PGRAPH, 0x0754,
0x00000030);
NV_WR32(par->PGRAPH, 0x0750,
0x00E10038);
NV_WR32(par->PGRAPH, 0x0754,
0x00000030);
}
}
if ((par->Architecture < NV_ARCH_40) ||
((par->Chipset & 0xfff0) == 0x0040)) {
for (i = 0; i < 32; i++) {
NV_WR32(par->PGRAPH, 0x0900 + i*4,
NV_RD32(par->PFB, 0x0240 +i*4));
NV_WR32(par->PGRAPH, 0x6900 + i*4,
NV_RD32(par->PFB, 0x0240 +i*4));
}
} else {
if (((par->Chipset & 0xfff0) == 0x0090) ||
((par->Chipset & 0xfff0) == 0x01D0) ||
((par->Chipset & 0xfff0) == 0x0290) ||
((par->Chipset & 0xfff0) == 0x0390) ||
((par->Chipset & 0xfff0) == 0x03D0)) {
for (i = 0; i < 60; i++) {
NV_WR32(par->PGRAPH,
0x0D00 + i*4,
NV_RD32(par->PFB,
0x0600 + i*4));
NV_WR32(par->PGRAPH,
0x6900 + i*4,
NV_RD32(par->PFB,
0x0600 + i*4));
}
} else {
for (i = 0; i < 48; i++) {
NV_WR32(par->PGRAPH,
0x0900 + i*4,
NV_RD32(par->PFB,
0x0600 + i*4));
if(((par->Chipset & 0xfff0)
!= 0x0160) &&
((par->Chipset & 0xfff0)
!= 0x0220) &&
((par->Chipset & 0xfff0)
!= 0x240))
NV_WR32(par->PGRAPH,
0x6900 + i*4,
NV_RD32(par->PFB,
0x0600 + i*4));
}
}
}
if (par->Architecture >= NV_ARCH_40) {
if ((par->Chipset & 0xfff0) == 0x0040) {
NV_WR32(par->PGRAPH, 0x09A4,
NV_RD32(par->PFB, 0x0200));
NV_WR32(par->PGRAPH, 0x09A8,
NV_RD32(par->PFB, 0x0204));
NV_WR32(par->PGRAPH, 0x69A4,
NV_RD32(par->PFB, 0x0200));
NV_WR32(par->PGRAPH, 0x69A8,
NV_RD32(par->PFB, 0x0204));
NV_WR32(par->PGRAPH, 0x0820, 0);
NV_WR32(par->PGRAPH, 0x0824, 0);
NV_WR32(par->PGRAPH, 0x0864,
par->FbMapSize - 1);
NV_WR32(par->PGRAPH, 0x0868,
par->FbMapSize - 1);
} else {
if ((par->Chipset & 0xfff0) == 0x0090 ||
(par->Chipset & 0xfff0) == 0x01D0 ||
(par->Chipset & 0xfff0) == 0x0290 ||
(par->Chipset & 0xfff0) == 0x0390) {
NV_WR32(par->PGRAPH, 0x0DF0,
NV_RD32(par->PFB, 0x0200));
NV_WR32(par->PGRAPH, 0x0DF4,
NV_RD32(par->PFB, 0x0204));
} else {
NV_WR32(par->PGRAPH, 0x09F0,
NV_RD32(par->PFB, 0x0200));
NV_WR32(par->PGRAPH, 0x09F4,
NV_RD32(par->PFB, 0x0204));
}
NV_WR32(par->PGRAPH, 0x69F0,
NV_RD32(par->PFB, 0x0200));
NV_WR32(par->PGRAPH, 0x69F4,
NV_RD32(par->PFB, 0x0204));
NV_WR32(par->PGRAPH, 0x0840, 0);
NV_WR32(par->PGRAPH, 0x0844, 0);
NV_WR32(par->PGRAPH, 0x08a0,
par->FbMapSize - 1);
NV_WR32(par->PGRAPH, 0x08a4,
par->FbMapSize - 1);
}
} else {
NV_WR32(par->PGRAPH, 0x09A4,
NV_RD32(par->PFB, 0x0200));
NV_WR32(par->PGRAPH, 0x09A8,
NV_RD32(par->PFB, 0x0204));
NV_WR32(par->PGRAPH, 0x0750, 0x00EA0000);
NV_WR32(par->PGRAPH, 0x0754,
NV_RD32(par->PFB, 0x0200));
NV_WR32(par->PGRAPH, 0x0750, 0x00EA0004);
NV_WR32(par->PGRAPH, 0x0754,
NV_RD32(par->PFB, 0x0204));
NV_WR32(par->PGRAPH, 0x0820, 0);
NV_WR32(par->PGRAPH, 0x0824, 0);
NV_WR32(par->PGRAPH, 0x0864,
par->FbMapSize - 1);
NV_WR32(par->PGRAPH, 0x0868,
par->FbMapSize - 1);
}
NV_WR32(par->PGRAPH, 0x0B20, 0x00000000);
NV_WR32(par->PGRAPH, 0x0B04, 0xFFFFFFFF);
}
}
NV_WR32(par->PGRAPH, 0x053C, 0);
NV_WR32(par->PGRAPH, 0x0540, 0);
NV_WR32(par->PGRAPH, 0x0544, 0x00007FFF);
NV_WR32(par->PGRAPH, 0x0548, 0x00007FFF);
NV_WR32(par->PFIFO, 0x0140 * 4, 0x00000000);
NV_WR32(par->PFIFO, 0x0141 * 4, 0x00000001);
NV_WR32(par->PFIFO, 0x0480 * 4, 0x00000000);
NV_WR32(par->PFIFO, 0x0494 * 4, 0x00000000);
if (par->Architecture >= NV_ARCH_40)
NV_WR32(par->PFIFO, 0x0481 * 4, 0x00010000);
else
NV_WR32(par->PFIFO, 0x0481 * 4, 0x00000100);
NV_WR32(par->PFIFO, 0x0490 * 4, 0x00000000);
NV_WR32(par->PFIFO, 0x0491 * 4, 0x00000000);
if (par->Architecture >= NV_ARCH_40)
NV_WR32(par->PFIFO, 0x048B * 4, 0x00001213);
else
NV_WR32(par->PFIFO, 0x048B * 4, 0x00001209);
NV_WR32(par->PFIFO, 0x0400 * 4, 0x00000000);
NV_WR32(par->PFIFO, 0x0414 * 4, 0x00000000);
NV_WR32(par->PFIFO, 0x0084 * 4, 0x03000100);
NV_WR32(par->PFIFO, 0x0085 * 4, 0x00000110);
NV_WR32(par->PFIFO, 0x0086 * 4, 0x00000112);
NV_WR32(par->PFIFO, 0x0143 * 4, 0x0000FFFF);
NV_WR32(par->PFIFO, 0x0496 * 4, 0x0000FFFF);
NV_WR32(par->PFIFO, 0x0050 * 4, 0x00000000);
NV_WR32(par->PFIFO, 0x0040 * 4, 0xFFFFFFFF);
NV_WR32(par->PFIFO, 0x0415 * 4, 0x00000001);
NV_WR32(par->PFIFO, 0x048C * 4, 0x00000000);
NV_WR32(par->PFIFO, 0x04A0 * 4, 0x00000000);
#ifdef __BIG_ENDIAN
NV_WR32(par->PFIFO, 0x0489 * 4, 0x800F0078);
#else
NV_WR32(par->PFIFO, 0x0489 * 4, 0x000F0078);
#endif
NV_WR32(par->PFIFO, 0x0488 * 4, 0x00000001);
NV_WR32(par->PFIFO, 0x0480 * 4, 0x00000001);
NV_WR32(par->PFIFO, 0x0494 * 4, 0x00000001);
NV_WR32(par->PFIFO, 0x0495 * 4, 0x00000001);
NV_WR32(par->PFIFO, 0x0140 * 4, 0x00000001);
if (!state) {
par->CurrentState = NULL;
return;
}
if (par->Architecture >= NV_ARCH_10) {
if (par->twoHeads) {
NV_WR32(par->PCRTC0, 0x0860, state->head);
NV_WR32(par->PCRTC0, 0x2860, state->head2);
}
NV_WR32(par->PRAMDAC, 0x0404, NV_RD32(par->PRAMDAC, 0x0404) |
(1 << 25));
NV_WR32(par->PMC, 0x8704, 1);
NV_WR32(par->PMC, 0x8140, 0);
NV_WR32(par->PMC, 0x8920, 0);
NV_WR32(par->PMC, 0x8924, 0);
NV_WR32(par->PMC, 0x8908, par->FbMapSize - 1);
NV_WR32(par->PMC, 0x890C, par->FbMapSize - 1);
NV_WR32(par->PMC, 0x1588, 0);
NV_WR32(par->PCRTC, 0x0810, state->cursorConfig);
NV_WR32(par->PCRTC, 0x0830, state->displayV - 3);
NV_WR32(par->PCRTC, 0x0834, state->displayV - 1);
if (par->FlatPanel) {
if ((par->Chipset & 0x0ff0) == 0x0110) {
NV_WR32(par->PRAMDAC, 0x0528, state->dither);
} else if (par->twoHeads) {
NV_WR32(par->PRAMDAC, 0x083C, state->dither);
}
VGA_WR08(par->PCIO, 0x03D4, 0x53);
VGA_WR08(par->PCIO, 0x03D5, state->timingH);
VGA_WR08(par->PCIO, 0x03D4, 0x54);
VGA_WR08(par->PCIO, 0x03D5, state->timingV);
VGA_WR08(par->PCIO, 0x03D4, 0x21);
VGA_WR08(par->PCIO, 0x03D5, 0xfa);
}
VGA_WR08(par->PCIO, 0x03D4, 0x41);
VGA_WR08(par->PCIO, 0x03D5, state->extra);
}
VGA_WR08(par->PCIO, 0x03D4, 0x19);
VGA_WR08(par->PCIO, 0x03D5, state->repaint0);
VGA_WR08(par->PCIO, 0x03D4, 0x1A);
VGA_WR08(par->PCIO, 0x03D5, state->repaint1);
VGA_WR08(par->PCIO, 0x03D4, 0x25);
VGA_WR08(par->PCIO, 0x03D5, state->screen);
VGA_WR08(par->PCIO, 0x03D4, 0x28);
VGA_WR08(par->PCIO, 0x03D5, state->pixel);
VGA_WR08(par->PCIO, 0x03D4, 0x2D);
VGA_WR08(par->PCIO, 0x03D5, state->horiz);
VGA_WR08(par->PCIO, 0x03D4, 0x1C);
VGA_WR08(par->PCIO, 0x03D5, state->fifo);
VGA_WR08(par->PCIO, 0x03D4, 0x1B);
VGA_WR08(par->PCIO, 0x03D5, state->arbitration0);
VGA_WR08(par->PCIO, 0x03D4, 0x20);
VGA_WR08(par->PCIO, 0x03D5, state->arbitration1);
if(par->Architecture >= NV_ARCH_30) {
VGA_WR08(par->PCIO, 0x03D4, 0x47);
VGA_WR08(par->PCIO, 0x03D5, state->arbitration1 >> 8);
}
VGA_WR08(par->PCIO, 0x03D4, 0x30);
VGA_WR08(par->PCIO, 0x03D5, state->cursor0);
VGA_WR08(par->PCIO, 0x03D4, 0x31);
VGA_WR08(par->PCIO, 0x03D5, state->cursor1);
VGA_WR08(par->PCIO, 0x03D4, 0x2F);
VGA_WR08(par->PCIO, 0x03D5, state->cursor2);
VGA_WR08(par->PCIO, 0x03D4, 0x39);
VGA_WR08(par->PCIO, 0x03D5, state->interlace);
if (!par->FlatPanel) {
if (par->Architecture >= NV_ARCH_40)
NV_WR32(par->PRAMDAC0, 0x0580, state->control);
NV_WR32(par->PRAMDAC0, 0x050C, state->pllsel);
NV_WR32(par->PRAMDAC0, 0x0508, state->vpll);
if (par->twoHeads)
NV_WR32(par->PRAMDAC0, 0x0520, state->vpll2);
if (par->twoStagePLL) {
NV_WR32(par->PRAMDAC0, 0x0578, state->vpllB);
NV_WR32(par->PRAMDAC0, 0x057C, state->vpll2B);
}
} else {
NV_WR32(par->PRAMDAC, 0x0848, state->scale);
NV_WR32(par->PRAMDAC, 0x0828, state->crtcSync +
par->PanelTweak);
}
NV_WR32(par->PRAMDAC, 0x0600, state->general);
NV_WR32(par->PCRTC, 0x0140, 0);
NV_WR32(par->PCRTC, 0x0100, 1);
par->CurrentState = state;
}
void NVUnloadStateExt(struct nvidia_par *par, RIVA_HW_STATE * state) {
VGA_WR08(par->PCIO, 0x03D4, 0x19);
state->repaint0 = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x1A);
state->repaint1 = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x25);
state->screen = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x28);
state->pixel = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x2D);
state->horiz = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x1C);
state->fifo = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x1B);
state->arbitration0 = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x20);
state->arbitration1 = VGA_RD08(par->PCIO, 0x03D5);
if(par->Architecture >= NV_ARCH_30) {
VGA_WR08(par->PCIO, 0x03D4, 0x47);
state->arbitration1 |= (VGA_RD08(par->PCIO, 0x03D5) & 1) << 8;
}
VGA_WR08(par->PCIO, 0x03D4, 0x30);
state->cursor0 = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x31);
state->cursor1 = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x2F);
state->cursor2 = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x39);
state->interlace = VGA_RD08(par->PCIO, 0x03D5);
state->vpll = NV_RD32(par->PRAMDAC0, 0x0508);
if (par->twoHeads)
state->vpll2 = NV_RD32(par->PRAMDAC0, 0x0520);
if (par->twoStagePLL) {
state->vpllB = NV_RD32(par->PRAMDAC0, 0x0578);
state->vpll2B = NV_RD32(par->PRAMDAC0, 0x057C);
}
state->pllsel = NV_RD32(par->PRAMDAC0, 0x050C);
state->general = NV_RD32(par->PRAMDAC, 0x0600);
state->scale = NV_RD32(par->PRAMDAC, 0x0848);
state->config = NV_RD32(par->PFB, 0x0200);
if (par->Architecture >= NV_ARCH_40 && !par->FlatPanel)
state->control = NV_RD32(par->PRAMDAC0, 0x0580);
if (par->Architecture >= NV_ARCH_10) {
if (par->twoHeads) {
state->head = NV_RD32(par->PCRTC0, 0x0860);
state->head2 = NV_RD32(par->PCRTC0, 0x2860);
VGA_WR08(par->PCIO, 0x03D4, 0x44);
state->crtcOwner = VGA_RD08(par->PCIO, 0x03D5);
}
VGA_WR08(par->PCIO, 0x03D4, 0x41);
state->extra = VGA_RD08(par->PCIO, 0x03D5);
state->cursorConfig = NV_RD32(par->PCRTC, 0x0810);
if ((par->Chipset & 0x0ff0) == 0x0110) {
state->dither = NV_RD32(par->PRAMDAC, 0x0528);
} else if (par->twoHeads) {
state->dither = NV_RD32(par->PRAMDAC, 0x083C);
}
if (par->FlatPanel) {
VGA_WR08(par->PCIO, 0x03D4, 0x53);
state->timingH = VGA_RD08(par->PCIO, 0x03D5);
VGA_WR08(par->PCIO, 0x03D4, 0x54);
state->timingV = VGA_RD08(par->PCIO, 0x03D5);
}
}
}
void NVSetStartAddress(struct nvidia_par *par, u32 start)
{
NV_WR32(par->PCRTC, 0x800, start);
}
| gpl-2.0 |
mlinuxguy/odroid-c1-kernel-3.19 | drivers/clocksource/sh_tmu.c | 181 | 15384 | /*
* SuperH Timer Support - TMU
*
* Copyright (C) 2009 Magnus Damm
*
* 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
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/clk.h>
#include <linux/clockchips.h>
#include <linux/clocksource.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/pm_domain.h>
#include <linux/pm_runtime.h>
#include <linux/sh_timer.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
enum sh_tmu_model {
SH_TMU,
SH_TMU_SH3,
};
struct sh_tmu_device;
struct sh_tmu_channel {
struct sh_tmu_device *tmu;
unsigned int index;
void __iomem *base;
int irq;
unsigned long rate;
unsigned long periodic;
struct clock_event_device ced;
struct clocksource cs;
bool cs_enabled;
unsigned int enable_count;
};
struct sh_tmu_device {
struct platform_device *pdev;
void __iomem *mapbase;
struct clk *clk;
enum sh_tmu_model model;
raw_spinlock_t lock; /* Protect the shared start/stop register */
struct sh_tmu_channel *channels;
unsigned int num_channels;
bool has_clockevent;
bool has_clocksource;
};
#define TSTR -1 /* shared register */
#define TCOR 0 /* channel register */
#define TCNT 1 /* channel register */
#define TCR 2 /* channel register */
#define TCR_UNF (1 << 8)
#define TCR_UNIE (1 << 5)
#define TCR_TPSC_CLK4 (0 << 0)
#define TCR_TPSC_CLK16 (1 << 0)
#define TCR_TPSC_CLK64 (2 << 0)
#define TCR_TPSC_CLK256 (3 << 0)
#define TCR_TPSC_CLK1024 (4 << 0)
#define TCR_TPSC_MASK (7 << 0)
static inline unsigned long sh_tmu_read(struct sh_tmu_channel *ch, int reg_nr)
{
unsigned long offs;
if (reg_nr == TSTR) {
switch (ch->tmu->model) {
case SH_TMU_SH3:
return ioread8(ch->tmu->mapbase + 2);
case SH_TMU:
return ioread8(ch->tmu->mapbase + 4);
}
}
offs = reg_nr << 2;
if (reg_nr == TCR)
return ioread16(ch->base + offs);
else
return ioread32(ch->base + offs);
}
static inline void sh_tmu_write(struct sh_tmu_channel *ch, int reg_nr,
unsigned long value)
{
unsigned long offs;
if (reg_nr == TSTR) {
switch (ch->tmu->model) {
case SH_TMU_SH3:
return iowrite8(value, ch->tmu->mapbase + 2);
case SH_TMU:
return iowrite8(value, ch->tmu->mapbase + 4);
}
}
offs = reg_nr << 2;
if (reg_nr == TCR)
iowrite16(value, ch->base + offs);
else
iowrite32(value, ch->base + offs);
}
static void sh_tmu_start_stop_ch(struct sh_tmu_channel *ch, int start)
{
unsigned long flags, value;
/* start stop register shared by multiple timer channels */
raw_spin_lock_irqsave(&ch->tmu->lock, flags);
value = sh_tmu_read(ch, TSTR);
if (start)
value |= 1 << ch->index;
else
value &= ~(1 << ch->index);
sh_tmu_write(ch, TSTR, value);
raw_spin_unlock_irqrestore(&ch->tmu->lock, flags);
}
static int __sh_tmu_enable(struct sh_tmu_channel *ch)
{
int ret;
/* enable clock */
ret = clk_enable(ch->tmu->clk);
if (ret) {
dev_err(&ch->tmu->pdev->dev, "ch%u: cannot enable clock\n",
ch->index);
return ret;
}
/* make sure channel is disabled */
sh_tmu_start_stop_ch(ch, 0);
/* maximum timeout */
sh_tmu_write(ch, TCOR, 0xffffffff);
sh_tmu_write(ch, TCNT, 0xffffffff);
/* configure channel to parent clock / 4, irq off */
ch->rate = clk_get_rate(ch->tmu->clk) / 4;
sh_tmu_write(ch, TCR, TCR_TPSC_CLK4);
/* enable channel */
sh_tmu_start_stop_ch(ch, 1);
return 0;
}
static int sh_tmu_enable(struct sh_tmu_channel *ch)
{
if (ch->enable_count++ > 0)
return 0;
pm_runtime_get_sync(&ch->tmu->pdev->dev);
dev_pm_syscore_device(&ch->tmu->pdev->dev, true);
return __sh_tmu_enable(ch);
}
static void __sh_tmu_disable(struct sh_tmu_channel *ch)
{
/* disable channel */
sh_tmu_start_stop_ch(ch, 0);
/* disable interrupts in TMU block */
sh_tmu_write(ch, TCR, TCR_TPSC_CLK4);
/* stop clock */
clk_disable(ch->tmu->clk);
}
static void sh_tmu_disable(struct sh_tmu_channel *ch)
{
if (WARN_ON(ch->enable_count == 0))
return;
if (--ch->enable_count > 0)
return;
__sh_tmu_disable(ch);
dev_pm_syscore_device(&ch->tmu->pdev->dev, false);
pm_runtime_put(&ch->tmu->pdev->dev);
}
static void sh_tmu_set_next(struct sh_tmu_channel *ch, unsigned long delta,
int periodic)
{
/* stop timer */
sh_tmu_start_stop_ch(ch, 0);
/* acknowledge interrupt */
sh_tmu_read(ch, TCR);
/* enable interrupt */
sh_tmu_write(ch, TCR, TCR_UNIE | TCR_TPSC_CLK4);
/* reload delta value in case of periodic timer */
if (periodic)
sh_tmu_write(ch, TCOR, delta);
else
sh_tmu_write(ch, TCOR, 0xffffffff);
sh_tmu_write(ch, TCNT, delta);
/* start timer */
sh_tmu_start_stop_ch(ch, 1);
}
static irqreturn_t sh_tmu_interrupt(int irq, void *dev_id)
{
struct sh_tmu_channel *ch = dev_id;
/* disable or acknowledge interrupt */
if (ch->ced.mode == CLOCK_EVT_MODE_ONESHOT)
sh_tmu_write(ch, TCR, TCR_TPSC_CLK4);
else
sh_tmu_write(ch, TCR, TCR_UNIE | TCR_TPSC_CLK4);
/* notify clockevent layer */
ch->ced.event_handler(&ch->ced);
return IRQ_HANDLED;
}
static struct sh_tmu_channel *cs_to_sh_tmu(struct clocksource *cs)
{
return container_of(cs, struct sh_tmu_channel, cs);
}
static cycle_t sh_tmu_clocksource_read(struct clocksource *cs)
{
struct sh_tmu_channel *ch = cs_to_sh_tmu(cs);
return sh_tmu_read(ch, TCNT) ^ 0xffffffff;
}
static int sh_tmu_clocksource_enable(struct clocksource *cs)
{
struct sh_tmu_channel *ch = cs_to_sh_tmu(cs);
int ret;
if (WARN_ON(ch->cs_enabled))
return 0;
ret = sh_tmu_enable(ch);
if (!ret) {
__clocksource_updatefreq_hz(cs, ch->rate);
ch->cs_enabled = true;
}
return ret;
}
static void sh_tmu_clocksource_disable(struct clocksource *cs)
{
struct sh_tmu_channel *ch = cs_to_sh_tmu(cs);
if (WARN_ON(!ch->cs_enabled))
return;
sh_tmu_disable(ch);
ch->cs_enabled = false;
}
static void sh_tmu_clocksource_suspend(struct clocksource *cs)
{
struct sh_tmu_channel *ch = cs_to_sh_tmu(cs);
if (!ch->cs_enabled)
return;
if (--ch->enable_count == 0) {
__sh_tmu_disable(ch);
pm_genpd_syscore_poweroff(&ch->tmu->pdev->dev);
}
}
static void sh_tmu_clocksource_resume(struct clocksource *cs)
{
struct sh_tmu_channel *ch = cs_to_sh_tmu(cs);
if (!ch->cs_enabled)
return;
if (ch->enable_count++ == 0) {
pm_genpd_syscore_poweron(&ch->tmu->pdev->dev);
__sh_tmu_enable(ch);
}
}
static int sh_tmu_register_clocksource(struct sh_tmu_channel *ch,
const char *name)
{
struct clocksource *cs = &ch->cs;
cs->name = name;
cs->rating = 200;
cs->read = sh_tmu_clocksource_read;
cs->enable = sh_tmu_clocksource_enable;
cs->disable = sh_tmu_clocksource_disable;
cs->suspend = sh_tmu_clocksource_suspend;
cs->resume = sh_tmu_clocksource_resume;
cs->mask = CLOCKSOURCE_MASK(32);
cs->flags = CLOCK_SOURCE_IS_CONTINUOUS;
dev_info(&ch->tmu->pdev->dev, "ch%u: used as clock source\n",
ch->index);
/* Register with dummy 1 Hz value, gets updated in ->enable() */
clocksource_register_hz(cs, 1);
return 0;
}
static struct sh_tmu_channel *ced_to_sh_tmu(struct clock_event_device *ced)
{
return container_of(ced, struct sh_tmu_channel, ced);
}
static void sh_tmu_clock_event_start(struct sh_tmu_channel *ch, int periodic)
{
struct clock_event_device *ced = &ch->ced;
sh_tmu_enable(ch);
clockevents_config(ced, ch->rate);
if (periodic) {
ch->periodic = (ch->rate + HZ/2) / HZ;
sh_tmu_set_next(ch, ch->periodic, 1);
}
}
static void sh_tmu_clock_event_mode(enum clock_event_mode mode,
struct clock_event_device *ced)
{
struct sh_tmu_channel *ch = ced_to_sh_tmu(ced);
int disabled = 0;
/* deal with old setting first */
switch (ced->mode) {
case CLOCK_EVT_MODE_PERIODIC:
case CLOCK_EVT_MODE_ONESHOT:
sh_tmu_disable(ch);
disabled = 1;
break;
default:
break;
}
switch (mode) {
case CLOCK_EVT_MODE_PERIODIC:
dev_info(&ch->tmu->pdev->dev,
"ch%u: used for periodic clock events\n", ch->index);
sh_tmu_clock_event_start(ch, 1);
break;
case CLOCK_EVT_MODE_ONESHOT:
dev_info(&ch->tmu->pdev->dev,
"ch%u: used for oneshot clock events\n", ch->index);
sh_tmu_clock_event_start(ch, 0);
break;
case CLOCK_EVT_MODE_UNUSED:
if (!disabled)
sh_tmu_disable(ch);
break;
case CLOCK_EVT_MODE_SHUTDOWN:
default:
break;
}
}
static int sh_tmu_clock_event_next(unsigned long delta,
struct clock_event_device *ced)
{
struct sh_tmu_channel *ch = ced_to_sh_tmu(ced);
BUG_ON(ced->mode != CLOCK_EVT_MODE_ONESHOT);
/* program new delta value */
sh_tmu_set_next(ch, delta, 0);
return 0;
}
static void sh_tmu_clock_event_suspend(struct clock_event_device *ced)
{
pm_genpd_syscore_poweroff(&ced_to_sh_tmu(ced)->tmu->pdev->dev);
}
static void sh_tmu_clock_event_resume(struct clock_event_device *ced)
{
pm_genpd_syscore_poweron(&ced_to_sh_tmu(ced)->tmu->pdev->dev);
}
static void sh_tmu_register_clockevent(struct sh_tmu_channel *ch,
const char *name)
{
struct clock_event_device *ced = &ch->ced;
int ret;
ced->name = name;
ced->features = CLOCK_EVT_FEAT_PERIODIC;
ced->features |= CLOCK_EVT_FEAT_ONESHOT;
ced->rating = 200;
ced->cpumask = cpu_possible_mask;
ced->set_next_event = sh_tmu_clock_event_next;
ced->set_mode = sh_tmu_clock_event_mode;
ced->suspend = sh_tmu_clock_event_suspend;
ced->resume = sh_tmu_clock_event_resume;
dev_info(&ch->tmu->pdev->dev, "ch%u: used for clock events\n",
ch->index);
clockevents_config_and_register(ced, 1, 0x300, 0xffffffff);
ret = request_irq(ch->irq, sh_tmu_interrupt,
IRQF_TIMER | IRQF_IRQPOLL | IRQF_NOBALANCING,
dev_name(&ch->tmu->pdev->dev), ch);
if (ret) {
dev_err(&ch->tmu->pdev->dev, "ch%u: failed to request irq %d\n",
ch->index, ch->irq);
return;
}
}
static int sh_tmu_register(struct sh_tmu_channel *ch, const char *name,
bool clockevent, bool clocksource)
{
if (clockevent) {
ch->tmu->has_clockevent = true;
sh_tmu_register_clockevent(ch, name);
} else if (clocksource) {
ch->tmu->has_clocksource = true;
sh_tmu_register_clocksource(ch, name);
}
return 0;
}
static int sh_tmu_channel_setup(struct sh_tmu_channel *ch, unsigned int index,
bool clockevent, bool clocksource,
struct sh_tmu_device *tmu)
{
/* Skip unused channels. */
if (!clockevent && !clocksource)
return 0;
ch->tmu = tmu;
ch->index = index;
if (tmu->model == SH_TMU_SH3)
ch->base = tmu->mapbase + 4 + ch->index * 12;
else
ch->base = tmu->mapbase + 8 + ch->index * 12;
ch->irq = platform_get_irq(tmu->pdev, index);
if (ch->irq < 0) {
dev_err(&tmu->pdev->dev, "ch%u: failed to get irq\n",
ch->index);
return ch->irq;
}
ch->cs_enabled = false;
ch->enable_count = 0;
return sh_tmu_register(ch, dev_name(&tmu->pdev->dev),
clockevent, clocksource);
}
static int sh_tmu_map_memory(struct sh_tmu_device *tmu)
{
struct resource *res;
res = platform_get_resource(tmu->pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&tmu->pdev->dev, "failed to get I/O memory\n");
return -ENXIO;
}
tmu->mapbase = ioremap_nocache(res->start, resource_size(res));
if (tmu->mapbase == NULL)
return -ENXIO;
return 0;
}
static int sh_tmu_parse_dt(struct sh_tmu_device *tmu)
{
struct device_node *np = tmu->pdev->dev.of_node;
tmu->model = SH_TMU;
tmu->num_channels = 3;
of_property_read_u32(np, "#renesas,channels", &tmu->num_channels);
if (tmu->num_channels != 2 && tmu->num_channels != 3) {
dev_err(&tmu->pdev->dev, "invalid number of channels %u\n",
tmu->num_channels);
return -EINVAL;
}
return 0;
}
static int sh_tmu_setup(struct sh_tmu_device *tmu, struct platform_device *pdev)
{
unsigned int i;
int ret;
tmu->pdev = pdev;
raw_spin_lock_init(&tmu->lock);
if (IS_ENABLED(CONFIG_OF) && pdev->dev.of_node) {
ret = sh_tmu_parse_dt(tmu);
if (ret < 0)
return ret;
} else if (pdev->dev.platform_data) {
const struct platform_device_id *id = pdev->id_entry;
struct sh_timer_config *cfg = pdev->dev.platform_data;
tmu->model = id->driver_data;
tmu->num_channels = hweight8(cfg->channels_mask);
} else {
dev_err(&tmu->pdev->dev, "missing platform data\n");
return -ENXIO;
}
/* Get hold of clock. */
tmu->clk = clk_get(&tmu->pdev->dev, "fck");
if (IS_ERR(tmu->clk)) {
dev_err(&tmu->pdev->dev, "cannot get clock\n");
return PTR_ERR(tmu->clk);
}
ret = clk_prepare(tmu->clk);
if (ret < 0)
goto err_clk_put;
/* Map the memory resource. */
ret = sh_tmu_map_memory(tmu);
if (ret < 0) {
dev_err(&tmu->pdev->dev, "failed to remap I/O memory\n");
goto err_clk_unprepare;
}
/* Allocate and setup the channels. */
tmu->channels = kzalloc(sizeof(*tmu->channels) * tmu->num_channels,
GFP_KERNEL);
if (tmu->channels == NULL) {
ret = -ENOMEM;
goto err_unmap;
}
/*
* Use the first channel as a clock event device and the second channel
* as a clock source.
*/
for (i = 0; i < tmu->num_channels; ++i) {
ret = sh_tmu_channel_setup(&tmu->channels[i], i,
i == 0, i == 1, tmu);
if (ret < 0)
goto err_unmap;
}
platform_set_drvdata(pdev, tmu);
return 0;
err_unmap:
kfree(tmu->channels);
iounmap(tmu->mapbase);
err_clk_unprepare:
clk_unprepare(tmu->clk);
err_clk_put:
clk_put(tmu->clk);
return ret;
}
static int sh_tmu_probe(struct platform_device *pdev)
{
struct sh_tmu_device *tmu = platform_get_drvdata(pdev);
int ret;
if (!is_early_platform_device(pdev)) {
pm_runtime_set_active(&pdev->dev);
pm_runtime_enable(&pdev->dev);
}
if (tmu) {
dev_info(&pdev->dev, "kept as earlytimer\n");
goto out;
}
tmu = kzalloc(sizeof(*tmu), GFP_KERNEL);
if (tmu == NULL)
return -ENOMEM;
ret = sh_tmu_setup(tmu, pdev);
if (ret) {
kfree(tmu);
pm_runtime_idle(&pdev->dev);
return ret;
}
if (is_early_platform_device(pdev))
return 0;
out:
if (tmu->has_clockevent || tmu->has_clocksource)
pm_runtime_irq_safe(&pdev->dev);
else
pm_runtime_idle(&pdev->dev);
return 0;
}
static int sh_tmu_remove(struct platform_device *pdev)
{
return -EBUSY; /* cannot unregister clockevent and clocksource */
}
static const struct platform_device_id sh_tmu_id_table[] = {
{ "sh-tmu", SH_TMU },
{ "sh-tmu-sh3", SH_TMU_SH3 },
{ }
};
MODULE_DEVICE_TABLE(platform, sh_tmu_id_table);
static const struct of_device_id sh_tmu_of_table[] __maybe_unused = {
{ .compatible = "renesas,tmu" },
{ }
};
MODULE_DEVICE_TABLE(of, sh_tmu_of_table);
static struct platform_driver sh_tmu_device_driver = {
.probe = sh_tmu_probe,
.remove = sh_tmu_remove,
.driver = {
.name = "sh_tmu",
.of_match_table = of_match_ptr(sh_tmu_of_table),
},
.id_table = sh_tmu_id_table,
};
static int __init sh_tmu_init(void)
{
return platform_driver_register(&sh_tmu_device_driver);
}
static void __exit sh_tmu_exit(void)
{
platform_driver_unregister(&sh_tmu_device_driver);
}
early_platform_init("earlytimer", &sh_tmu_device_driver);
subsys_initcall(sh_tmu_init);
module_exit(sh_tmu_exit);
MODULE_AUTHOR("Magnus Damm");
MODULE_DESCRIPTION("SuperH TMU Timer Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
primiano/udoo_bootable_bootloader_uboot-imx | board/apollon/sys_info.c | 181 | 11446 | /*
* (C) Copyright 2005-2007
* Samsung Electronics,
* Kyungmin Park <kyungmin.park@samsung.com>
*
* Derived from omap2420
*
* 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 <common.h>
#include <asm/arch/omap2420.h>
#include <asm/io.h>
#include <asm/arch/bits.h>
#include <asm/arch/mem.h> /* get mem tables */
#include <asm/arch/sys_proto.h>
#include <asm/arch/sys_info.h>
#include <i2c.h>
/**************************************************************************
* get_prod_id() - get id info from chips
***************************************************************************/
static u32 get_prod_id(void)
{
u32 p;
p = __raw_readl(PRODUCTION_ID); /* get production ID */
return ((p & CPU_242X_PID_MASK) >> 16);
}
/**************************************************************************
* get_cpu_type() - low level get cpu type
* - no C globals yet.
* - just looking to say if this is a 2422 or 2420 or ...
* - to start with we will look at switch settings..
* - 2422 id's same as 2420 for ES1 will rely on H4 board characteristics
* (mux for 2420, non-mux for 2422).
***************************************************************************/
u32 get_cpu_type(void)
{
u32 v;
switch (get_prod_id()) {
case 1:; /* 2420 */
case 2:
return (CPU_2420);
break; /* 2420 pop */
case 4:
return (CPU_2422);
break;
case 8:
return (CPU_2423);
break;
default:
break; /* early 2420/2422's unmarked */
}
v = __raw_readl(TAP_IDCODE_REG);
v &= CPU_24XX_ID_MASK;
/* currently 2420 and 2422 have same id */
if (v == CPU_2420_CHIPID) {
if (is_gpmc_muxed() == GPMC_MUXED) /* if mux'ed */
return (CPU_2420);
else
return (CPU_2422);
} else
return (CPU_2420); /* don't know, say 2420 */
}
/******************************************
* get_cpu_rev(void) - extract version info
******************************************/
u32 get_cpu_rev(void)
{
u32 v;
v = __raw_readl(TAP_IDCODE_REG);
v = v >> 28;
return (v + 1); /* currently 2422 and 2420 match up */
}
/****************************************************
* is_mem_sdr() - return 1 if mem type in use is SDR
****************************************************/
u32 is_mem_sdr(void)
{
volatile u32 *burst = (volatile u32 *)(SDRC_MR_0 + SDRC_CS0_OSET);
if (*burst == H4_2420_SDRC_MR_0_SDR)
return (1);
return (0);
}
/***********************************************************
* get_mem_type() - identify type of mDDR part used.
* 2422 uses stacked DDR, 2 parts CS0/CS1.
* 2420 may have 1 or 2, no good way to know...only init 1...
* when eeprom data is up we can select 1 more.
*************************************************************/
u32 get_mem_type(void)
{
u32 cpu, sdr = is_mem_sdr();
cpu = get_cpu_type();
if (cpu == CPU_2422 || cpu == CPU_2423)
return (DDR_STACKED);
if (get_prod_id() == 0x2)
return (XDR_POP);
if (get_board_type() == BOARD_H4_MENELAUS)
if (sdr)
return (SDR_DISCRETE);
else
return (DDR_COMBO);
else if (sdr) /* SDP + SDR kit */
return (SDR_DISCRETE);
else
return (DDR_DISCRETE); /* origional SDP */
}
/***********************************************************************
* get_cs0_size() - get size of chip select 0/1
************************************************************************/
u32 get_sdr_cs_size(u32 offset)
{
u32 size;
size = __raw_readl(SDRC_MCFG_0 + offset) >> 8; /* get ram size field */
size &= 0x2FF; /* remove unwanted bits */
size *= SZ_2M; /* find size in MB */
return (size);
}
/***********************************************************************
* get_board_type() - get board type based on current production stats.
* --- NOTE: 2 I2C EEPROMs will someday be populated with proper info.
* when they are available we can get info from there. This should
* be correct of all known boards up until today.
************************************************************************/
u32 get_board_type(void)
{
return (BOARD_H4_SDP);
}
/******************************************************************
* get_sysboot_value() - get init word settings (dip switch on h4)
******************************************************************/
inline u32 get_sysboot_value(void)
{
return (0x00000FFF & __raw_readl(CONTROL_STATUS));
}
/***************************************************************************
* get_gpmc0_base() - Return current address hardware will be
* fetching from. The below effectively gives what is correct, its a bit
* mis-leading compared to the TRM. For the most general case the mask
* needs to be also taken into account this does work in practice.
* - for u-boot we currently map:
* -- 0 to nothing,
* -- 4 to flash
* -- 8 to enent
* -- c to wifi
****************************************************************************/
u32 get_gpmc0_base(void)
{
u32 b;
b = __raw_readl(GPMC_CONFIG7_0);
b &= 0x1F; /* keep base [5:0] */
b = b << 24; /* ret 0x0b000000 */
return (b);
}
/*****************************************************************
* is_gpmc_muxed() - tells if address/data lines are multiplexed
*****************************************************************/
u32 is_gpmc_muxed(void)
{
u32 mux;
mux = get_sysboot_value();
if ((mux & (BIT0 | BIT1 | BIT2 | BIT3)) == (BIT0 | BIT2 | BIT3))
return (GPMC_MUXED); /* NAND Boot mode */
if (mux & BIT1) /* if mux'ed */
return (GPMC_MUXED);
else
return (GPMC_NONMUXED);
}
/************************************************************************
* get_gpmc0_type() - read sysboot lines to see type of memory attached
************************************************************************/
u32 get_gpmc0_type(void)
{
u32 type;
type = get_sysboot_value();
if ((type & (BIT3 | BIT2)) == (BIT3 | BIT2))
return (TYPE_NAND);
else
return (TYPE_NOR);
}
/*******************************************************************
* get_gpmc0_width() - See if bus is in x8 or x16 (mainly for nand)
*******************************************************************/
u32 get_gpmc0_width(void)
{
u32 width;
width = get_sysboot_value();
if ((width & 0xF) == (BIT3 | BIT2))
return (WIDTH_8BIT);
else
return (WIDTH_16BIT);
}
/*********************************************************************
* wait_on_value() - common routine to allow waiting for changes in
* volatile regs.
*********************************************************************/
u32 wait_on_value(u32 read_bit_mask, u32 match_value, u32 read_addr, u32 bound)
{
u32 i = 0, val;
do {
++i;
val = __raw_readl(read_addr) & read_bit_mask;
if (val == match_value)
return (1);
if (i == bound)
return (0);
} while (1);
}
/*********************************************************************
* display_board_info() - print banner with board info.
*********************************************************************/
void display_board_info(u32 btype)
{
char cpu_2420[] = "2420"; /* cpu type */
char cpu_2422[] = "2422";
char cpu_2423[] = "2423";
char db_men[] = "Menelaus"; /* board type */
char db_ip[] = "IP";
char mem_sdr[] = "mSDR"; /* memory type */
char mem_ddr[] = "mDDR";
char t_tst[] = "TST"; /* security level */
char t_emu[] = "EMU";
char t_hs[] = "HS";
char t_gp[] = "GP";
char unk[] = "?";
char *cpu_s, *db_s, *mem_s, *sec_s;
u32 cpu, rev, sec;
rev = get_cpu_rev();
cpu = get_cpu_type();
sec = get_device_type();
if (is_mem_sdr())
mem_s = mem_sdr;
else
mem_s = mem_ddr;
if (cpu == CPU_2423)
cpu_s = cpu_2423;
else if (cpu == CPU_2422)
cpu_s = cpu_2422;
else
cpu_s = cpu_2420;
if (btype == BOARD_H4_MENELAUS)
db_s = db_men;
else
db_s = db_ip;
switch (sec) {
case TST_DEVICE:
sec_s = t_tst;
break;
case EMU_DEVICE:
sec_s = t_emu;
break;
case HS_DEVICE:
sec_s = t_hs;
break;
case GP_DEVICE:
sec_s = t_gp;
break;
default:
sec_s = unk;
}
printf("OMAP%s-%s revision %d\n", cpu_s, sec_s, rev - 1);
printf("Samsung Apollon SDP Base Board + %s \n", mem_s);
}
/*************************************************************************
* get_board_rev() - setup to pass kernel board revision information
* 0 = 242x IP platform (first 2xx boards)
* 1 = 242x Menelaus platfrom.
*************************************************************************/
u32 get_board_rev(void)
{
u32 rev = 0;
u32 btype = get_board_type();
if (btype == BOARD_H4_MENELAUS)
rev = 1;
return (rev);
}
/********************************************************
* get_base(); get upper addr of current execution
*******************************************************/
u32 get_base(void)
{
u32 val;
__asm__ __volatile__("mov %0, pc \n":"=r"(val)::"memory");
val &= 0xF0000000;
val >>= 28;
return (val);
}
/********************************************************
* get_base2(); get 2upper addr of current execution
*******************************************************/
u32 get_base2(void)
{
u32 val;
__asm__ __volatile__("mov %0, pc \n":"=r"(val)::"memory");
val &= 0xFF000000;
val >>= 24;
return (val);
}
/********************************************************
* running_in_flash() - tell if currently running in
* flash.
*******************************************************/
u32 running_in_flash(void)
{
if (get_base() < 4)
return (1); /* in flash */
return (0); /* running in SRAM or SDRAM */
}
/********************************************************
* running_in_sram() - tell if currently running in
* sram.
*******************************************************/
u32 running_in_sram(void)
{
if (get_base() == 4)
return (1); /* in SRAM */
return (0); /* running in FLASH or SDRAM */
}
/********************************************************
* running_in_sdram() - tell if currently running in
* flash.
*******************************************************/
u32 running_in_sdram(void)
{
if (get_base() > 4)
return (1); /* in sdram */
return (0); /* running in SRAM or FLASH */
}
/*************************************************************
* running_from_internal_boot() - am I a signed NOR image.
*************************************************************/
u32 running_from_internal_boot(void)
{
u32 v, base;
v = get_sysboot_value() & BIT3;
base = get_base2();
/* if running at mask rom flash address and
* sysboot3 says this was an internal boot
*/
if ((base == 0x08) && v)
return (1);
else
return (0);
}
/*************************************************************
* get_device_type(): tell if GP/HS/EMU/TST
*************************************************************/
u32 get_device_type(void)
{
int mode;
mode = __raw_readl(CONTROL_STATUS) & (BIT10 | BIT9 | BIT8);
return (mode >>= 8);
}
| gpl-2.0 |
vurrut/android_kernel_latona | drivers/usb/misc/usblcd.c | 181 | 12133 | /*****************************************************************************
* USBLCD Kernel Driver *
* Version 1.05 *
* (C) 2005 Georges Toth <g.toth@e-biz.lu> *
* *
* This file is licensed under the GPL. See COPYING in the package. *
* Based on usb-skeleton.c 2.0 by Greg Kroah-Hartman (greg@kroah.com) *
* *
* *
* 28.02.05 Complete rewrite of the original usblcd.c driver, *
* based on usb_skeleton.c. *
* This new driver allows more than one USB-LCD to be connected *
* and controlled, at once *
*****************************************************************************/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <linux/usb.h>
#define DRIVER_VERSION "USBLCD Driver Version 1.05"
#define USBLCD_MINOR 144
#define IOCTL_GET_HARD_VERSION 1
#define IOCTL_GET_DRV_VERSION 2
static DEFINE_MUTEX(lcd_mutex);
static const struct usb_device_id id_table[] = {
{ .idVendor = 0x10D2, .match_flags = USB_DEVICE_ID_MATCH_VENDOR, },
{ },
};
MODULE_DEVICE_TABLE (usb, id_table);
static DEFINE_MUTEX(open_disc_mutex);
struct usb_lcd {
struct usb_device * udev; /* init: probe_lcd */
struct usb_interface * interface; /* the interface for this device */
unsigned char * bulk_in_buffer; /* the buffer to receive data */
size_t bulk_in_size; /* the size of the receive buffer */
__u8 bulk_in_endpointAddr; /* the address of the bulk in endpoint */
__u8 bulk_out_endpointAddr; /* the address of the bulk out endpoint */
struct kref kref;
struct semaphore limit_sem; /* to stop writes at full throttle from
* using up all RAM */
struct usb_anchor submitted; /* URBs to wait for before suspend */
};
#define to_lcd_dev(d) container_of(d, struct usb_lcd, kref)
#define USB_LCD_CONCURRENT_WRITES 5
static struct usb_driver lcd_driver;
static void lcd_delete(struct kref *kref)
{
struct usb_lcd *dev = to_lcd_dev(kref);
usb_put_dev(dev->udev);
kfree (dev->bulk_in_buffer);
kfree (dev);
}
static int lcd_open(struct inode *inode, struct file *file)
{
struct usb_lcd *dev;
struct usb_interface *interface;
int subminor, r;
mutex_lock(&lcd_mutex);
subminor = iminor(inode);
interface = usb_find_interface(&lcd_driver, subminor);
if (!interface) {
mutex_unlock(&lcd_mutex);
err ("USBLCD: %s - error, can't find device for minor %d",
__func__, subminor);
return -ENODEV;
}
mutex_lock(&open_disc_mutex);
dev = usb_get_intfdata(interface);
if (!dev) {
mutex_unlock(&open_disc_mutex);
mutex_unlock(&lcd_mutex);
return -ENODEV;
}
/* increment our usage count for the device */
kref_get(&dev->kref);
mutex_unlock(&open_disc_mutex);
/* grab a power reference */
r = usb_autopm_get_interface(interface);
if (r < 0) {
kref_put(&dev->kref, lcd_delete);
mutex_unlock(&lcd_mutex);
return r;
}
/* save our object in the file's private structure */
file->private_data = dev;
mutex_unlock(&lcd_mutex);
return 0;
}
static int lcd_release(struct inode *inode, struct file *file)
{
struct usb_lcd *dev;
dev = file->private_data;
if (dev == NULL)
return -ENODEV;
/* decrement the count on our device */
usb_autopm_put_interface(dev->interface);
kref_put(&dev->kref, lcd_delete);
return 0;
}
static ssize_t lcd_read(struct file *file, char __user * buffer, size_t count, loff_t *ppos)
{
struct usb_lcd *dev;
int retval = 0;
int bytes_read;
dev = file->private_data;
/* do a blocking bulk read to get data from the device */
retval = usb_bulk_msg(dev->udev,
usb_rcvbulkpipe(dev->udev, dev->bulk_in_endpointAddr),
dev->bulk_in_buffer,
min(dev->bulk_in_size, count),
&bytes_read, 10000);
/* if the read was successful, copy the data to userspace */
if (!retval) {
if (copy_to_user(buffer, dev->bulk_in_buffer, bytes_read))
retval = -EFAULT;
else
retval = bytes_read;
}
return retval;
}
static long lcd_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct usb_lcd *dev;
u16 bcdDevice;
char buf[30];
dev = file->private_data;
if (dev == NULL)
return -ENODEV;
switch (cmd) {
case IOCTL_GET_HARD_VERSION:
mutex_lock(&lcd_mutex);
bcdDevice = le16_to_cpu((dev->udev)->descriptor.bcdDevice);
sprintf(buf,"%1d%1d.%1d%1d",
(bcdDevice & 0xF000)>>12,
(bcdDevice & 0xF00)>>8,
(bcdDevice & 0xF0)>>4,
(bcdDevice & 0xF));
mutex_unlock(&lcd_mutex);
if (copy_to_user((void __user *)arg,buf,strlen(buf))!=0)
return -EFAULT;
break;
case IOCTL_GET_DRV_VERSION:
sprintf(buf,DRIVER_VERSION);
if (copy_to_user((void __user *)arg,buf,strlen(buf))!=0)
return -EFAULT;
break;
default:
return -ENOTTY;
break;
}
return 0;
}
static void lcd_write_bulk_callback(struct urb *urb)
{
struct usb_lcd *dev;
int status = urb->status;
dev = urb->context;
/* sync/async unlink faults aren't errors */
if (status &&
!(status == -ENOENT ||
status == -ECONNRESET ||
status == -ESHUTDOWN)) {
dbg("USBLCD: %s - nonzero write bulk status received: %d",
__func__, status);
}
/* free up our allocated buffer */
usb_free_coherent(urb->dev, urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma);
up(&dev->limit_sem);
}
static ssize_t lcd_write(struct file *file, const char __user * user_buffer, size_t count, loff_t *ppos)
{
struct usb_lcd *dev;
int retval = 0, r;
struct urb *urb = NULL;
char *buf = NULL;
dev = file->private_data;
/* verify that we actually have some data to write */
if (count == 0)
goto exit;
r = down_interruptible(&dev->limit_sem);
if (r < 0)
return -EINTR;
/* create a urb, and a buffer for it, and copy the data to the urb */
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb) {
retval = -ENOMEM;
goto err_no_buf;
}
buf = usb_alloc_coherent(dev->udev, count, GFP_KERNEL, &urb->transfer_dma);
if (!buf) {
retval = -ENOMEM;
goto error;
}
if (copy_from_user(buf, user_buffer, count)) {
retval = -EFAULT;
goto error;
}
/* initialize the urb properly */
usb_fill_bulk_urb(urb, dev->udev,
usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
buf, count, lcd_write_bulk_callback, dev);
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
usb_anchor_urb(urb, &dev->submitted);
/* send the data out the bulk port */
retval = usb_submit_urb(urb, GFP_KERNEL);
if (retval) {
err("USBLCD: %s - failed submitting write urb, error %d", __func__, retval);
goto error_unanchor;
}
/* release our reference to this urb, the USB core will eventually free it entirely */
usb_free_urb(urb);
exit:
return count;
error_unanchor:
usb_unanchor_urb(urb);
error:
usb_free_coherent(dev->udev, count, buf, urb->transfer_dma);
usb_free_urb(urb);
err_no_buf:
up(&dev->limit_sem);
return retval;
}
static const struct file_operations lcd_fops = {
.owner = THIS_MODULE,
.read = lcd_read,
.write = lcd_write,
.open = lcd_open,
.unlocked_ioctl = lcd_ioctl,
.release = lcd_release,
};
/*
* usb class driver info in order to get a minor number from the usb core,
* and to have the device registered with the driver core
*/
static struct usb_class_driver lcd_class = {
.name = "lcd%d",
.fops = &lcd_fops,
.minor_base = USBLCD_MINOR,
};
static int lcd_probe(struct usb_interface *interface, const struct usb_device_id *id)
{
struct usb_lcd *dev = NULL;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
size_t buffer_size;
int i;
int retval = -ENOMEM;
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (dev == NULL) {
err("Out of memory");
goto error;
}
kref_init(&dev->kref);
sema_init(&dev->limit_sem, USB_LCD_CONCURRENT_WRITES);
init_usb_anchor(&dev->submitted);
dev->udev = usb_get_dev(interface_to_usbdev(interface));
dev->interface = interface;
if (le16_to_cpu(dev->udev->descriptor.idProduct) != 0x0001) {
dev_warn(&interface->dev, "USBLCD model not supported.\n");
retval = -ENODEV;
goto error;
}
/* set up the endpoint information */
/* use only the first bulk-in and bulk-out endpoints */
iface_desc = interface->cur_altsetting;
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if (!dev->bulk_in_endpointAddr &&
usb_endpoint_is_bulk_in(endpoint)) {
/* we found a bulk in endpoint */
buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
dev->bulk_in_size = buffer_size;
dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
dev->bulk_in_buffer = kmalloc(buffer_size, GFP_KERNEL);
if (!dev->bulk_in_buffer) {
err("Could not allocate bulk_in_buffer");
goto error;
}
}
if (!dev->bulk_out_endpointAddr &&
usb_endpoint_is_bulk_out(endpoint)) {
/* we found a bulk out endpoint */
dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;
}
}
if (!(dev->bulk_in_endpointAddr && dev->bulk_out_endpointAddr)) {
err("Could not find both bulk-in and bulk-out endpoints");
goto error;
}
/* save our data pointer in this interface device */
usb_set_intfdata(interface, dev);
/* we can register the device now, as it is ready */
retval = usb_register_dev(interface, &lcd_class);
if (retval) {
/* something prevented us from registering this driver */
err("Not able to get a minor for this device.");
usb_set_intfdata(interface, NULL);
goto error;
}
i = le16_to_cpu(dev->udev->descriptor.bcdDevice);
dev_info(&interface->dev, "USBLCD Version %1d%1d.%1d%1d found "
"at address %d\n", (i & 0xF000)>>12, (i & 0xF00)>>8,
(i & 0xF0)>>4,(i & 0xF), dev->udev->devnum);
/* let the user know what node this device is now attached to */
dev_info(&interface->dev, "USB LCD device now attached to USBLCD-%d\n",
interface->minor);
return 0;
error:
if (dev)
kref_put(&dev->kref, lcd_delete);
return retval;
}
static void lcd_draw_down(struct usb_lcd *dev)
{
int time;
time = usb_wait_anchor_empty_timeout(&dev->submitted, 1000);
if (!time)
usb_kill_anchored_urbs(&dev->submitted);
}
static int lcd_suspend(struct usb_interface *intf, pm_message_t message)
{
struct usb_lcd *dev = usb_get_intfdata(intf);
if (!dev)
return 0;
lcd_draw_down(dev);
return 0;
}
static int lcd_resume (struct usb_interface *intf)
{
return 0;
}
static void lcd_disconnect(struct usb_interface *interface)
{
struct usb_lcd *dev;
int minor = interface->minor;
mutex_lock(&open_disc_mutex);
dev = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
mutex_unlock(&open_disc_mutex);
/* give back our minor */
usb_deregister_dev(interface, &lcd_class);
/* decrement our usage count */
kref_put(&dev->kref, lcd_delete);
dev_info(&interface->dev, "USB LCD #%d now disconnected\n", minor);
}
static struct usb_driver lcd_driver = {
.name = "usblcd",
.probe = lcd_probe,
.disconnect = lcd_disconnect,
.suspend = lcd_suspend,
.resume = lcd_resume,
.id_table = id_table,
.supports_autosuspend = 1,
};
static int __init usb_lcd_init(void)
{
int result;
result = usb_register(&lcd_driver);
if (result)
err("usb_register failed. Error number %d", result);
return result;
}
static void __exit usb_lcd_exit(void)
{
usb_deregister(&lcd_driver);
}
module_init(usb_lcd_init);
module_exit(usb_lcd_exit);
MODULE_AUTHOR("Georges Toth <g.toth@e-biz.lu>");
MODULE_DESCRIPTION(DRIVER_VERSION);
MODULE_LICENSE("GPL");
| gpl-2.0 |
vidyaravipati/net-next-rocker | arch/arm/firmware/trusted_foundations.c | 1973 | 2684 | /*
* Trusted Foundations support for ARM CPUs
*
* Copyright (c) 2013, NVIDIA 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.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/of.h>
#include <asm/firmware.h>
#include <asm/trusted_foundations.h>
#define TF_SET_CPU_BOOT_ADDR_SMC 0xfffff200
#define TF_CPU_PM 0xfffffffc
#define TF_CPU_PM_S3 0xffffffe3
#define TF_CPU_PM_S2 0xffffffe6
#define TF_CPU_PM_S2_NO_MC_CLK 0xffffffe5
#define TF_CPU_PM_S1 0xffffffe4
#define TF_CPU_PM_S1_NOFLUSH_L2 0xffffffe7
static unsigned long cpu_boot_addr;
static void __naked tf_generic_smc(u32 type, u32 arg1, u32 arg2)
{
asm volatile(
".arch_extension sec\n\t"
"stmfd sp!, {r4 - r11, lr}\n\t"
__asmeq("%0", "r0")
__asmeq("%1", "r1")
__asmeq("%2", "r2")
"mov r3, #0\n\t"
"mov r4, #0\n\t"
"smc #0\n\t"
"ldmfd sp!, {r4 - r11, pc}"
:
: "r" (type), "r" (arg1), "r" (arg2)
: "memory");
}
static int tf_set_cpu_boot_addr(int cpu, unsigned long boot_addr)
{
cpu_boot_addr = boot_addr;
tf_generic_smc(TF_SET_CPU_BOOT_ADDR_SMC, cpu_boot_addr, 0);
return 0;
}
static int tf_prepare_idle(void)
{
tf_generic_smc(TF_CPU_PM, TF_CPU_PM_S1_NOFLUSH_L2, cpu_boot_addr);
return 0;
}
static const struct firmware_ops trusted_foundations_ops = {
.set_cpu_boot_addr = tf_set_cpu_boot_addr,
.prepare_idle = tf_prepare_idle,
};
void register_trusted_foundations(struct trusted_foundations_platform_data *pd)
{
/*
* we are not using version information for now since currently
* supported SMCs are compatible with all TF releases
*/
register_firmware_ops(&trusted_foundations_ops);
}
void of_register_trusted_foundations(void)
{
struct device_node *node;
struct trusted_foundations_platform_data pdata;
int err;
node = of_find_compatible_node(NULL, NULL, "tlm,trusted-foundations");
if (!node)
return;
err = of_property_read_u32(node, "tlm,version-major",
&pdata.version_major);
if (err != 0)
panic("Trusted Foundation: missing version-major property\n");
err = of_property_read_u32(node, "tlm,version-minor",
&pdata.version_minor);
if (err != 0)
panic("Trusted Foundation: missing version-minor property\n");
register_trusted_foundations(&pdata);
}
| gpl-2.0 |
venue3x40-dev/android_kernel_dell_venue3x40 | drivers/base/devtmpfs.c | 2229 | 9219 | /*
* devtmpfs - kernel-maintained tmpfs-based /dev
*
* Copyright (C) 2009, Kay Sievers <kay.sievers@vrfy.org>
*
* During bootup, before any driver core device is registered,
* devtmpfs, a tmpfs-based filesystem is created. Every driver-core
* device which requests a device node, will add a node in this
* filesystem.
* By default, all devices are named after the name of the device,
* owned by root and have a default mode of 0600. Subsystems can
* overwrite the default setting if needed.
*/
#include <linux/kernel.h>
#include <linux/syscalls.h>
#include <linux/mount.h>
#include <linux/device.h>
#include <linux/genhd.h>
#include <linux/namei.h>
#include <linux/fs.h>
#include <linux/shmem_fs.h>
#include <linux/ramfs.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/kthread.h>
#include "base.h"
static struct task_struct *thread;
#if defined CONFIG_DEVTMPFS_MOUNT
static int mount_dev = 1;
#else
static int mount_dev;
#endif
static DEFINE_SPINLOCK(req_lock);
static struct req {
struct req *next;
struct completion done;
int err;
const char *name;
umode_t mode; /* 0 => delete */
kuid_t uid;
kgid_t gid;
struct device *dev;
} *requests;
static int __init mount_param(char *str)
{
mount_dev = simple_strtoul(str, NULL, 0);
return 1;
}
__setup("devtmpfs.mount=", mount_param);
static struct dentry *dev_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data)
{
#ifdef CONFIG_TMPFS
return mount_single(fs_type, flags, data, shmem_fill_super);
#else
return mount_single(fs_type, flags, data, ramfs_fill_super);
#endif
}
static struct file_system_type dev_fs_type = {
.name = "devtmpfs",
.mount = dev_mount,
.kill_sb = kill_litter_super,
};
#ifdef CONFIG_BLOCK
static inline int is_blockdev(struct device *dev)
{
return dev->class == &block_class;
}
#else
static inline int is_blockdev(struct device *dev) { return 0; }
#endif
int devtmpfs_create_node(struct device *dev)
{
const char *tmp = NULL;
struct req req;
if (!thread)
return 0;
req.mode = 0;
req.uid = GLOBAL_ROOT_UID;
req.gid = GLOBAL_ROOT_GID;
req.name = device_get_devnode(dev, &req.mode, &req.uid, &req.gid, &tmp);
if (!req.name)
return -ENOMEM;
if (req.mode == 0)
req.mode = 0600;
if (is_blockdev(dev))
req.mode |= S_IFBLK;
else
req.mode |= S_IFCHR;
req.dev = dev;
init_completion(&req.done);
spin_lock(&req_lock);
req.next = requests;
requests = &req;
spin_unlock(&req_lock);
wake_up_process(thread);
wait_for_completion(&req.done);
kfree(tmp);
return req.err;
}
int devtmpfs_delete_node(struct device *dev)
{
const char *tmp = NULL;
struct req req;
if (!thread)
return 0;
req.name = device_get_devnode(dev, NULL, NULL, NULL, &tmp);
if (!req.name)
return -ENOMEM;
req.mode = 0;
req.dev = dev;
init_completion(&req.done);
spin_lock(&req_lock);
req.next = requests;
requests = &req;
spin_unlock(&req_lock);
wake_up_process(thread);
wait_for_completion(&req.done);
kfree(tmp);
return req.err;
}
static int dev_mkdir(const char *name, umode_t mode)
{
struct dentry *dentry;
struct path path;
int err;
dentry = kern_path_create(AT_FDCWD, name, &path, LOOKUP_DIRECTORY);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
err = vfs_mkdir(path.dentry->d_inode, dentry, mode);
if (!err)
/* mark as kernel-created inode */
dentry->d_inode->i_private = &thread;
done_path_create(&path, dentry);
return err;
}
static int create_path(const char *nodepath)
{
char *path;
char *s;
int err = 0;
/* parent directories do not exist, create them */
path = kstrdup(nodepath, GFP_KERNEL);
if (!path)
return -ENOMEM;
s = path;
for (;;) {
s = strchr(s, '/');
if (!s)
break;
s[0] = '\0';
err = dev_mkdir(path, 0755);
if (err && err != -EEXIST)
break;
s[0] = '/';
s++;
}
kfree(path);
return err;
}
static int handle_create(const char *nodename, umode_t mode, kuid_t uid,
kgid_t gid, struct device *dev)
{
struct dentry *dentry;
struct path path;
int err;
dentry = kern_path_create(AT_FDCWD, nodename, &path, 0);
if (dentry == ERR_PTR(-ENOENT)) {
create_path(nodename);
dentry = kern_path_create(AT_FDCWD, nodename, &path, 0);
}
if (IS_ERR(dentry))
return PTR_ERR(dentry);
err = vfs_mknod(path.dentry->d_inode, dentry, mode, dev->devt);
if (!err) {
struct iattr newattrs;
newattrs.ia_mode = mode;
newattrs.ia_uid = uid;
newattrs.ia_gid = gid;
newattrs.ia_valid = ATTR_MODE|ATTR_UID|ATTR_GID;
mutex_lock(&dentry->d_inode->i_mutex);
notify_change(dentry, &newattrs);
mutex_unlock(&dentry->d_inode->i_mutex);
/* mark as kernel-created inode */
dentry->d_inode->i_private = &thread;
}
done_path_create(&path, dentry);
return err;
}
static int dev_rmdir(const char *name)
{
struct path parent;
struct dentry *dentry;
int err;
dentry = kern_path_locked(name, &parent);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
if (dentry->d_inode) {
if (dentry->d_inode->i_private == &thread)
err = vfs_rmdir(parent.dentry->d_inode, dentry);
else
err = -EPERM;
} else {
err = -ENOENT;
}
dput(dentry);
mutex_unlock(&parent.dentry->d_inode->i_mutex);
path_put(&parent);
return err;
}
static int delete_path(const char *nodepath)
{
const char *path;
int err = 0;
path = kstrdup(nodepath, GFP_KERNEL);
if (!path)
return -ENOMEM;
for (;;) {
char *base;
base = strrchr(path, '/');
if (!base)
break;
base[0] = '\0';
err = dev_rmdir(path);
if (err)
break;
}
kfree(path);
return err;
}
static int dev_mynode(struct device *dev, struct inode *inode, struct kstat *stat)
{
/* did we create it */
if (inode->i_private != &thread)
return 0;
/* does the dev_t match */
if (is_blockdev(dev)) {
if (!S_ISBLK(stat->mode))
return 0;
} else {
if (!S_ISCHR(stat->mode))
return 0;
}
if (stat->rdev != dev->devt)
return 0;
/* ours */
return 1;
}
static int handle_remove(const char *nodename, struct device *dev)
{
struct path parent;
struct dentry *dentry;
int deleted = 1;
int err;
dentry = kern_path_locked(nodename, &parent);
if (IS_ERR(dentry))
return PTR_ERR(dentry);
if (dentry->d_inode) {
struct kstat stat;
struct path p = {.mnt = parent.mnt, .dentry = dentry};
err = vfs_getattr(&p, &stat);
if (!err && dev_mynode(dev, dentry->d_inode, &stat)) {
struct iattr newattrs;
/*
* before unlinking this node, reset permissions
* of possible references like hardlinks
*/
newattrs.ia_uid = GLOBAL_ROOT_UID;
newattrs.ia_gid = GLOBAL_ROOT_GID;
newattrs.ia_mode = stat.mode & ~0777;
newattrs.ia_valid =
ATTR_UID|ATTR_GID|ATTR_MODE;
mutex_lock(&dentry->d_inode->i_mutex);
notify_change(dentry, &newattrs);
mutex_unlock(&dentry->d_inode->i_mutex);
err = vfs_unlink(parent.dentry->d_inode, dentry);
if (!err || err == -ENOENT)
deleted = 1;
}
} else {
err = -ENOENT;
}
dput(dentry);
mutex_unlock(&parent.dentry->d_inode->i_mutex);
path_put(&parent);
if (deleted && strchr(nodename, '/'))
delete_path(nodename);
return err;
}
/*
* If configured, or requested by the commandline, devtmpfs will be
* auto-mounted after the kernel mounted the root filesystem.
*/
int devtmpfs_mount(const char *mntdir)
{
int err;
if (!mount_dev)
return 0;
if (!thread)
return 0;
err = sys_mount("devtmpfs", (char *)mntdir, "devtmpfs", MS_SILENT, NULL);
if (err)
printk(KERN_INFO "devtmpfs: error mounting %i\n", err);
else
printk(KERN_INFO "devtmpfs: mounted\n");
return err;
}
static DECLARE_COMPLETION(setup_done);
static int handle(const char *name, umode_t mode, kuid_t uid, kgid_t gid,
struct device *dev)
{
if (mode)
return handle_create(name, mode, uid, gid, dev);
else
return handle_remove(name, dev);
}
static int devtmpfsd(void *p)
{
char options[] = "mode=0755";
int *err = p;
*err = sys_unshare(CLONE_NEWNS);
if (*err)
goto out;
*err = sys_mount("devtmpfs", "/", "devtmpfs", MS_SILENT, options);
if (*err)
goto out;
sys_chdir("/.."); /* will traverse into overmounted root */
sys_chroot(".");
complete(&setup_done);
while (1) {
spin_lock(&req_lock);
while (requests) {
struct req *req = requests;
requests = NULL;
spin_unlock(&req_lock);
while (req) {
struct req *next = req->next;
req->err = handle(req->name, req->mode,
req->uid, req->gid, req->dev);
complete(&req->done);
req = next;
}
spin_lock(&req_lock);
}
__set_current_state(TASK_INTERRUPTIBLE);
spin_unlock(&req_lock);
schedule();
}
return 0;
out:
complete(&setup_done);
return *err;
}
/*
* Create devtmpfs instance, driver-core devices will add their device
* nodes here.
*/
int __init devtmpfs_init(void)
{
int err = register_filesystem(&dev_fs_type);
if (err) {
printk(KERN_ERR "devtmpfs: unable to register devtmpfs "
"type %i\n", err);
return err;
}
thread = kthread_run(devtmpfsd, &err, "kdevtmpfs");
if (!IS_ERR(thread)) {
wait_for_completion(&setup_done);
} else {
err = PTR_ERR(thread);
thread = NULL;
}
if (err) {
printk(KERN_ERR "devtmpfs: unable to create devtmpfs %i\n", err);
unregister_filesystem(&dev_fs_type);
return err;
}
printk(KERN_INFO "devtmpfs: initialized\n");
return 0;
}
| gpl-2.0 |
ColDReaVeR/android_kernel_samsung_coriplus | drivers/cpufreq/cpufreq_conservative.c | 2485 | 16766 | /*
* drivers/cpufreq/cpufreq_conservative.c
*
* Copyright (C) 2001 Russell King
* (C) 2003 Venkatesh Pallipadi <venkatesh.pallipadi@intel.com>.
* Jun Nakajima <jun.nakajima@intel.com>
* (C) 2009 Alexander Clouter <alex@digriz.org.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/cpufreq.h>
#include <linux/cpu.h>
#include <linux/jiffies.h>
#include <linux/kernel_stat.h>
#include <linux/mutex.h>
#include <linux/hrtimer.h>
#include <linux/tick.h>
#include <linux/ktime.h>
#include <linux/sched.h>
/*
* dbs is used in this file as a shortform for demandbased switching
* It helps to keep variable names smaller, simpler
*/
#define DEF_FREQUENCY_UP_THRESHOLD (80)
#define DEF_FREQUENCY_DOWN_THRESHOLD (20)
/*
* The polling frequency of this governor depends on the capability of
* the processor. Default polling frequency is 1000 times the transition
* latency of the processor. The governor will work on any processor with
* transition latency <= 10mS, using appropriate sampling
* rate.
* For CPUs with transition latency > 10mS (mostly drivers with CPUFREQ_ETERNAL)
* this governor will not work.
* All times here are in uS.
*/
#define MIN_SAMPLING_RATE_RATIO (2)
static unsigned int min_sampling_rate;
#define LATENCY_MULTIPLIER (1000)
#define MIN_LATENCY_MULTIPLIER (100)
#define DEF_SAMPLING_DOWN_FACTOR (1)
#define MAX_SAMPLING_DOWN_FACTOR (10)
#define TRANSITION_LATENCY_LIMIT (10 * 1000 * 1000)
static void do_dbs_timer(struct work_struct *work);
struct cpu_dbs_info_s {
cputime64_t prev_cpu_idle;
cputime64_t prev_cpu_wall;
cputime64_t prev_cpu_nice;
struct cpufreq_policy *cur_policy;
struct delayed_work work;
unsigned int down_skip;
unsigned int requested_freq;
int cpu;
unsigned int enable:1;
/*
* percpu mutex that serializes governor limit change with
* do_dbs_timer invocation. We do not want do_dbs_timer to run
* when user is changing the governor or limits.
*/
struct mutex timer_mutex;
};
static DEFINE_PER_CPU(struct cpu_dbs_info_s, cs_cpu_dbs_info);
static unsigned int dbs_enable; /* number of CPUs using this policy */
/*
* dbs_mutex protects dbs_enable in governor start/stop.
*/
static DEFINE_MUTEX(dbs_mutex);
static struct dbs_tuners {
unsigned int sampling_rate;
unsigned int sampling_down_factor;
unsigned int up_threshold;
unsigned int down_threshold;
unsigned int ignore_nice;
unsigned int freq_step;
} dbs_tuners_ins = {
.up_threshold = DEF_FREQUENCY_UP_THRESHOLD,
.down_threshold = DEF_FREQUENCY_DOWN_THRESHOLD,
.sampling_down_factor = DEF_SAMPLING_DOWN_FACTOR,
.ignore_nice = 0,
.freq_step = 5,
};
static inline cputime64_t get_cpu_idle_time_jiffy(unsigned int cpu,
cputime64_t *wall)
{
cputime64_t idle_time;
cputime64_t cur_wall_time;
cputime64_t busy_time;
cur_wall_time = jiffies64_to_cputime64(get_jiffies_64());
busy_time = cputime64_add(kstat_cpu(cpu).cpustat.user,
kstat_cpu(cpu).cpustat.system);
busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.irq);
busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.softirq);
busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.steal);
busy_time = cputime64_add(busy_time, kstat_cpu(cpu).cpustat.nice);
idle_time = cputime64_sub(cur_wall_time, busy_time);
if (wall)
*wall = (cputime64_t)jiffies_to_usecs(cur_wall_time);
return (cputime64_t)jiffies_to_usecs(idle_time);
}
static inline cputime64_t get_cpu_idle_time(unsigned int cpu, cputime64_t *wall)
{
u64 idle_time = get_cpu_idle_time_us(cpu, wall);
if (idle_time == -1ULL)
return get_cpu_idle_time_jiffy(cpu, wall);
return idle_time;
}
/* keep track of frequency transitions */
static int
dbs_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
void *data)
{
struct cpufreq_freqs *freq = data;
struct cpu_dbs_info_s *this_dbs_info = &per_cpu(cs_cpu_dbs_info,
freq->cpu);
struct cpufreq_policy *policy;
if (!this_dbs_info->enable)
return 0;
policy = this_dbs_info->cur_policy;
/*
* we only care if our internally tracked freq moves outside
* the 'valid' ranges of freqency available to us otherwise
* we do not change it
*/
if (this_dbs_info->requested_freq > policy->max
|| this_dbs_info->requested_freq < policy->min)
this_dbs_info->requested_freq = freq->new;
return 0;
}
static struct notifier_block dbs_cpufreq_notifier_block = {
.notifier_call = dbs_cpufreq_notifier
};
/************************** sysfs interface ************************/
static ssize_t show_sampling_rate_min(struct kobject *kobj,
struct attribute *attr, char *buf)
{
return sprintf(buf, "%u\n", min_sampling_rate);
}
define_one_global_ro(sampling_rate_min);
/* cpufreq_conservative Governor Tunables */
#define show_one(file_name, object) \
static ssize_t show_##file_name \
(struct kobject *kobj, struct attribute *attr, char *buf) \
{ \
return sprintf(buf, "%u\n", dbs_tuners_ins.object); \
}
show_one(sampling_rate, sampling_rate);
show_one(sampling_down_factor, sampling_down_factor);
show_one(up_threshold, up_threshold);
show_one(down_threshold, down_threshold);
show_one(ignore_nice_load, ignore_nice);
show_one(freq_step, freq_step);
static ssize_t store_sampling_down_factor(struct kobject *a,
struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > MAX_SAMPLING_DOWN_FACTOR || input < 1)
return -EINVAL;
dbs_tuners_ins.sampling_down_factor = input;
return count;
}
static ssize_t store_sampling_rate(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1)
return -EINVAL;
dbs_tuners_ins.sampling_rate = max(input, min_sampling_rate);
return count;
}
static ssize_t store_up_threshold(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1 || input > 100 ||
input <= dbs_tuners_ins.down_threshold)
return -EINVAL;
dbs_tuners_ins.up_threshold = input;
return count;
}
static ssize_t store_down_threshold(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
/* cannot be lower than 11 otherwise freq will not fall */
if (ret != 1 || input < 11 || input > 100 ||
input >= dbs_tuners_ins.up_threshold)
return -EINVAL;
dbs_tuners_ins.down_threshold = input;
return count;
}
static ssize_t store_ignore_nice_load(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
unsigned int j;
ret = sscanf(buf, "%u", &input);
if (ret != 1)
return -EINVAL;
if (input > 1)
input = 1;
if (input == dbs_tuners_ins.ignore_nice) /* nothing to do */
return count;
dbs_tuners_ins.ignore_nice = input;
/* we need to re-evaluate prev_cpu_idle */
for_each_online_cpu(j) {
struct cpu_dbs_info_s *dbs_info;
dbs_info = &per_cpu(cs_cpu_dbs_info, j);
dbs_info->prev_cpu_idle = get_cpu_idle_time(j,
&dbs_info->prev_cpu_wall);
if (dbs_tuners_ins.ignore_nice)
dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice;
}
return count;
}
static ssize_t store_freq_step(struct kobject *a, struct attribute *b,
const char *buf, size_t count)
{
unsigned int input;
int ret;
ret = sscanf(buf, "%u", &input);
if (ret != 1)
return -EINVAL;
if (input > 100)
input = 100;
/* no need to test here if freq_step is zero as the user might actually
* want this, they would be crazy though :) */
dbs_tuners_ins.freq_step = input;
return count;
}
define_one_global_rw(sampling_rate);
define_one_global_rw(sampling_down_factor);
define_one_global_rw(up_threshold);
define_one_global_rw(down_threshold);
define_one_global_rw(ignore_nice_load);
define_one_global_rw(freq_step);
static struct attribute *dbs_attributes[] = {
&sampling_rate_min.attr,
&sampling_rate.attr,
&sampling_down_factor.attr,
&up_threshold.attr,
&down_threshold.attr,
&ignore_nice_load.attr,
&freq_step.attr,
NULL
};
static struct attribute_group dbs_attr_group = {
.attrs = dbs_attributes,
.name = "conservative",
};
/************************** sysfs end ************************/
static void dbs_check_cpu(struct cpu_dbs_info_s *this_dbs_info)
{
unsigned int load = 0;
unsigned int max_load = 0;
unsigned int freq_target;
struct cpufreq_policy *policy;
unsigned int j;
policy = this_dbs_info->cur_policy;
/*
* Every sampling_rate, we check, if current idle time is less
* than 20% (default), then we try to increase frequency
* Every sampling_rate*sampling_down_factor, we check, if current
* idle time is more than 80%, then we try to decrease frequency
*
* Any frequency increase takes it to the maximum frequency.
* Frequency reduction happens at minimum steps of
* 5% (default) of maximum frequency
*/
/* Get Absolute Load */
for_each_cpu(j, policy->cpus) {
struct cpu_dbs_info_s *j_dbs_info;
cputime64_t cur_wall_time, cur_idle_time;
unsigned int idle_time, wall_time;
j_dbs_info = &per_cpu(cs_cpu_dbs_info, j);
cur_idle_time = get_cpu_idle_time(j, &cur_wall_time);
wall_time = (unsigned int) cputime64_sub(cur_wall_time,
j_dbs_info->prev_cpu_wall);
j_dbs_info->prev_cpu_wall = cur_wall_time;
idle_time = (unsigned int) cputime64_sub(cur_idle_time,
j_dbs_info->prev_cpu_idle);
j_dbs_info->prev_cpu_idle = cur_idle_time;
if (dbs_tuners_ins.ignore_nice) {
cputime64_t cur_nice;
unsigned long cur_nice_jiffies;
cur_nice = cputime64_sub(kstat_cpu(j).cpustat.nice,
j_dbs_info->prev_cpu_nice);
/*
* Assumption: nice time between sampling periods will
* be less than 2^32 jiffies for 32 bit sys
*/
cur_nice_jiffies = (unsigned long)
cputime64_to_jiffies64(cur_nice);
j_dbs_info->prev_cpu_nice = kstat_cpu(j).cpustat.nice;
idle_time += jiffies_to_usecs(cur_nice_jiffies);
}
if (unlikely(!wall_time || wall_time < idle_time))
continue;
load = 100 * (wall_time - idle_time) / wall_time;
if (load > max_load)
max_load = load;
}
/*
* break out if we 'cannot' reduce the speed as the user might
* want freq_step to be zero
*/
if (dbs_tuners_ins.freq_step == 0)
return;
/* Check for frequency increase */
if (max_load > dbs_tuners_ins.up_threshold) {
this_dbs_info->down_skip = 0;
/* if we are already at full speed then break out early */
if (this_dbs_info->requested_freq == policy->max)
return;
freq_target = (dbs_tuners_ins.freq_step * policy->max) / 100;
/* max freq cannot be less than 100. But who knows.... */
if (unlikely(freq_target == 0))
freq_target = 5;
this_dbs_info->requested_freq += freq_target;
if (this_dbs_info->requested_freq > policy->max)
this_dbs_info->requested_freq = policy->max;
__cpufreq_driver_target(policy, this_dbs_info->requested_freq,
CPUFREQ_RELATION_H);
return;
}
/*
* The optimal frequency is the frequency that is the lowest that
* can support the current CPU usage without triggering the up
* policy. To be safe, we focus 10 points under the threshold.
*/
if (max_load < (dbs_tuners_ins.down_threshold - 10)) {
freq_target = (dbs_tuners_ins.freq_step * policy->max) / 100;
this_dbs_info->requested_freq -= freq_target;
if (this_dbs_info->requested_freq < policy->min)
this_dbs_info->requested_freq = policy->min;
/*
* if we cannot reduce the frequency anymore, break out early
*/
if (policy->cur == policy->min)
return;
__cpufreq_driver_target(policy, this_dbs_info->requested_freq,
CPUFREQ_RELATION_H);
return;
}
}
static void do_dbs_timer(struct work_struct *work)
{
struct cpu_dbs_info_s *dbs_info =
container_of(work, struct cpu_dbs_info_s, work.work);
unsigned int cpu = dbs_info->cpu;
/* We want all CPUs to do sampling nearly on same jiffy */
int delay = usecs_to_jiffies(dbs_tuners_ins.sampling_rate);
delay -= jiffies % delay;
mutex_lock(&dbs_info->timer_mutex);
dbs_check_cpu(dbs_info);
schedule_delayed_work_on(cpu, &dbs_info->work, delay);
mutex_unlock(&dbs_info->timer_mutex);
}
static inline void dbs_timer_init(struct cpu_dbs_info_s *dbs_info)
{
/* We want all CPUs to do sampling nearly on same jiffy */
int delay = usecs_to_jiffies(dbs_tuners_ins.sampling_rate);
delay -= jiffies % delay;
dbs_info->enable = 1;
INIT_DELAYED_WORK_DEFERRABLE(&dbs_info->work, do_dbs_timer);
schedule_delayed_work_on(dbs_info->cpu, &dbs_info->work, delay);
}
static inline void dbs_timer_exit(struct cpu_dbs_info_s *dbs_info)
{
dbs_info->enable = 0;
cancel_delayed_work_sync(&dbs_info->work);
}
static int cpufreq_governor_dbs(struct cpufreq_policy *policy,
unsigned int event)
{
unsigned int cpu = policy->cpu;
struct cpu_dbs_info_s *this_dbs_info;
unsigned int j;
int rc;
this_dbs_info = &per_cpu(cs_cpu_dbs_info, cpu);
switch (event) {
case CPUFREQ_GOV_START:
if ((!cpu_online(cpu)) || (!policy->cur))
return -EINVAL;
mutex_lock(&dbs_mutex);
for_each_cpu(j, policy->cpus) {
struct cpu_dbs_info_s *j_dbs_info;
j_dbs_info = &per_cpu(cs_cpu_dbs_info, j);
j_dbs_info->cur_policy = policy;
j_dbs_info->prev_cpu_idle = get_cpu_idle_time(j,
&j_dbs_info->prev_cpu_wall);
if (dbs_tuners_ins.ignore_nice) {
j_dbs_info->prev_cpu_nice =
kstat_cpu(j).cpustat.nice;
}
}
this_dbs_info->down_skip = 0;
this_dbs_info->requested_freq = policy->cur;
mutex_init(&this_dbs_info->timer_mutex);
dbs_enable++;
/*
* Start the timerschedule work, when this governor
* is used for first time
*/
if (dbs_enable == 1) {
unsigned int latency;
/* policy latency is in nS. Convert it to uS first */
latency = policy->cpuinfo.transition_latency / 1000;
if (latency == 0)
latency = 1;
rc = sysfs_create_group(cpufreq_global_kobject,
&dbs_attr_group);
if (rc) {
mutex_unlock(&dbs_mutex);
return rc;
}
/*
* conservative does not implement micro like ondemand
* governor, thus we are bound to jiffes/HZ
*/
min_sampling_rate =
MIN_SAMPLING_RATE_RATIO * jiffies_to_usecs(10);
/* Bring kernel and HW constraints together */
min_sampling_rate = max(min_sampling_rate,
MIN_LATENCY_MULTIPLIER * latency);
dbs_tuners_ins.sampling_rate =
max(min_sampling_rate,
latency * LATENCY_MULTIPLIER);
cpufreq_register_notifier(
&dbs_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
}
mutex_unlock(&dbs_mutex);
dbs_timer_init(this_dbs_info);
break;
case CPUFREQ_GOV_STOP:
dbs_timer_exit(this_dbs_info);
mutex_lock(&dbs_mutex);
dbs_enable--;
mutex_destroy(&this_dbs_info->timer_mutex);
/*
* Stop the timerschedule work, when this governor
* is used for first time
*/
if (dbs_enable == 0)
cpufreq_unregister_notifier(
&dbs_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
mutex_unlock(&dbs_mutex);
if (!dbs_enable)
sysfs_remove_group(cpufreq_global_kobject,
&dbs_attr_group);
break;
case CPUFREQ_GOV_LIMITS:
mutex_lock(&this_dbs_info->timer_mutex);
if (policy->max < this_dbs_info->cur_policy->cur)
__cpufreq_driver_target(
this_dbs_info->cur_policy,
policy->max, CPUFREQ_RELATION_H);
else if (policy->min > this_dbs_info->cur_policy->cur)
__cpufreq_driver_target(
this_dbs_info->cur_policy,
policy->min, CPUFREQ_RELATION_L);
mutex_unlock(&this_dbs_info->timer_mutex);
break;
}
return 0;
}
#ifndef CONFIG_CPU_FREQ_DEFAULT_GOV_CONSERVATIVE
static
#endif
struct cpufreq_governor cpufreq_gov_conservative = {
.name = "conservative",
.governor = cpufreq_governor_dbs,
.max_transition_latency = TRANSITION_LATENCY_LIMIT,
.owner = THIS_MODULE,
};
static int __init cpufreq_gov_dbs_init(void)
{
return cpufreq_register_governor(&cpufreq_gov_conservative);
}
static void __exit cpufreq_gov_dbs_exit(void)
{
cpufreq_unregister_governor(&cpufreq_gov_conservative);
}
MODULE_AUTHOR("Alexander Clouter <alex@digriz.org.uk>");
MODULE_DESCRIPTION("'cpufreq_conservative' - A dynamic cpufreq governor for "
"Low Latency Frequency Transition capable processors "
"optimised for use in a battery environment");
MODULE_LICENSE("GPL");
#ifdef CONFIG_CPU_FREQ_DEFAULT_GOV_CONSERVATIVE
fs_initcall(cpufreq_gov_dbs_init);
#else
module_init(cpufreq_gov_dbs_init);
#endif
module_exit(cpufreq_gov_dbs_exit);
| gpl-2.0 |
mostafa-z/Gabriel_LG_LP_Kernel | drivers/tty/serial/imx.c | 3253 | 41742 | /*
* Driver for Motorola IMX serial ports
*
* Based on drivers/char/serial.c, by Linus Torvalds, Theodore Ts'o.
*
* Author: Sascha Hauer <sascha@saschahauer.de>
* Copyright (C) 2004 Pengutronix
*
* Copyright (C) 2009 emlix GmbH
* Author: Fabian Godehardt (added IrDA support for iMX)
*
* 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
*
* [29-Mar-2005] Mike Lee
* Added hardware handshake
*/
#if defined(CONFIG_SERIAL_IMX_CONSOLE) && defined(CONFIG_MAGIC_SYSRQ)
#define SUPPORT_SYSRQ
#endif
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/console.h>
#include <linux/sysrq.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/clk.h>
#include <linux/delay.h>
#include <linux/rational.h>
#include <linux/slab.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <mach/imx-uart.h>
/* Register definitions */
#define URXD0 0x0 /* Receiver Register */
#define URTX0 0x40 /* Transmitter Register */
#define UCR1 0x80 /* Control Register 1 */
#define UCR2 0x84 /* Control Register 2 */
#define UCR3 0x88 /* Control Register 3 */
#define UCR4 0x8c /* Control Register 4 */
#define UFCR 0x90 /* FIFO Control Register */
#define USR1 0x94 /* Status Register 1 */
#define USR2 0x98 /* Status Register 2 */
#define UESC 0x9c /* Escape Character Register */
#define UTIM 0xa0 /* Escape Timer Register */
#define UBIR 0xa4 /* BRM Incremental Register */
#define UBMR 0xa8 /* BRM Modulator Register */
#define UBRC 0xac /* Baud Rate Count Register */
#define IMX21_ONEMS 0xb0 /* One Millisecond register */
#define IMX1_UTS 0xd0 /* UART Test Register on i.mx1 */
#define IMX21_UTS 0xb4 /* UART Test Register on all other i.mx*/
/* UART Control Register Bit Fields.*/
#define URXD_CHARRDY (1<<15)
#define URXD_ERR (1<<14)
#define URXD_OVRRUN (1<<13)
#define URXD_FRMERR (1<<12)
#define URXD_BRK (1<<11)
#define URXD_PRERR (1<<10)
#define UCR1_ADEN (1<<15) /* Auto detect interrupt */
#define UCR1_ADBR (1<<14) /* Auto detect baud rate */
#define UCR1_TRDYEN (1<<13) /* Transmitter ready interrupt enable */
#define UCR1_IDEN (1<<12) /* Idle condition interrupt */
#define UCR1_RRDYEN (1<<9) /* Recv ready interrupt enable */
#define UCR1_RDMAEN (1<<8) /* Recv ready DMA enable */
#define UCR1_IREN (1<<7) /* Infrared interface enable */
#define UCR1_TXMPTYEN (1<<6) /* Transimitter empty interrupt enable */
#define UCR1_RTSDEN (1<<5) /* RTS delta interrupt enable */
#define UCR1_SNDBRK (1<<4) /* Send break */
#define UCR1_TDMAEN (1<<3) /* Transmitter ready DMA enable */
#define IMX1_UCR1_UARTCLKEN (1<<2) /* UART clock enabled, i.mx1 only */
#define UCR1_DOZE (1<<1) /* Doze */
#define UCR1_UARTEN (1<<0) /* UART enabled */
#define UCR2_ESCI (1<<15) /* Escape seq interrupt enable */
#define UCR2_IRTS (1<<14) /* Ignore RTS pin */
#define UCR2_CTSC (1<<13) /* CTS pin control */
#define UCR2_CTS (1<<12) /* Clear to send */
#define UCR2_ESCEN (1<<11) /* Escape enable */
#define UCR2_PREN (1<<8) /* Parity enable */
#define UCR2_PROE (1<<7) /* Parity odd/even */
#define UCR2_STPB (1<<6) /* Stop */
#define UCR2_WS (1<<5) /* Word size */
#define UCR2_RTSEN (1<<4) /* Request to send interrupt enable */
#define UCR2_ATEN (1<<3) /* Aging Timer Enable */
#define UCR2_TXEN (1<<2) /* Transmitter enabled */
#define UCR2_RXEN (1<<1) /* Receiver enabled */
#define UCR2_SRST (1<<0) /* SW reset */
#define UCR3_DTREN (1<<13) /* DTR interrupt enable */
#define UCR3_PARERREN (1<<12) /* Parity enable */
#define UCR3_FRAERREN (1<<11) /* Frame error interrupt enable */
#define UCR3_DSR (1<<10) /* Data set ready */
#define UCR3_DCD (1<<9) /* Data carrier detect */
#define UCR3_RI (1<<8) /* Ring indicator */
#define UCR3_TIMEOUTEN (1<<7) /* Timeout interrupt enable */
#define UCR3_RXDSEN (1<<6) /* Receive status interrupt enable */
#define UCR3_AIRINTEN (1<<5) /* Async IR wake interrupt enable */
#define UCR3_AWAKEN (1<<4) /* Async wake interrupt enable */
#define IMX21_UCR3_RXDMUXSEL (1<<2) /* RXD Muxed Input Select */
#define UCR3_INVT (1<<1) /* Inverted Infrared transmission */
#define UCR3_BPEN (1<<0) /* Preset registers enable */
#define UCR4_CTSTL_SHF 10 /* CTS trigger level shift */
#define UCR4_CTSTL_MASK 0x3F /* CTS trigger is 6 bits wide */
#define UCR4_INVR (1<<9) /* Inverted infrared reception */
#define UCR4_ENIRI (1<<8) /* Serial infrared interrupt enable */
#define UCR4_WKEN (1<<7) /* Wake interrupt enable */
#define UCR4_REF16 (1<<6) /* Ref freq 16 MHz */
#define UCR4_IRSC (1<<5) /* IR special case */
#define UCR4_TCEN (1<<3) /* Transmit complete interrupt enable */
#define UCR4_BKEN (1<<2) /* Break condition interrupt enable */
#define UCR4_OREN (1<<1) /* Receiver overrun interrupt enable */
#define UCR4_DREN (1<<0) /* Recv data ready interrupt enable */
#define UFCR_RXTL_SHF 0 /* Receiver trigger level shift */
#define UFCR_RFDIV (7<<7) /* Reference freq divider mask */
#define UFCR_RFDIV_REG(x) (((x) < 7 ? 6 - (x) : 6) << 7)
#define UFCR_TXTL_SHF 10 /* Transmitter trigger level shift */
#define USR1_PARITYERR (1<<15) /* Parity error interrupt flag */
#define USR1_RTSS (1<<14) /* RTS pin status */
#define USR1_TRDY (1<<13) /* Transmitter ready interrupt/dma flag */
#define USR1_RTSD (1<<12) /* RTS delta */
#define USR1_ESCF (1<<11) /* Escape seq interrupt flag */
#define USR1_FRAMERR (1<<10) /* Frame error interrupt flag */
#define USR1_RRDY (1<<9) /* Receiver ready interrupt/dma flag */
#define USR1_TIMEOUT (1<<7) /* Receive timeout interrupt status */
#define USR1_RXDS (1<<6) /* Receiver idle interrupt flag */
#define USR1_AIRINT (1<<5) /* Async IR wake interrupt flag */
#define USR1_AWAKE (1<<4) /* Aysnc wake interrupt flag */
#define USR2_ADET (1<<15) /* Auto baud rate detect complete */
#define USR2_TXFE (1<<14) /* Transmit buffer FIFO empty */
#define USR2_DTRF (1<<13) /* DTR edge interrupt flag */
#define USR2_IDLE (1<<12) /* Idle condition */
#define USR2_IRINT (1<<8) /* Serial infrared interrupt flag */
#define USR2_WAKE (1<<7) /* Wake */
#define USR2_RTSF (1<<4) /* RTS edge interrupt flag */
#define USR2_TXDC (1<<3) /* Transmitter complete */
#define USR2_BRCD (1<<2) /* Break condition */
#define USR2_ORE (1<<1) /* Overrun error */
#define USR2_RDR (1<<0) /* Recv data ready */
#define UTS_FRCPERR (1<<13) /* Force parity error */
#define UTS_LOOP (1<<12) /* Loop tx and rx */
#define UTS_TXEMPTY (1<<6) /* TxFIFO empty */
#define UTS_RXEMPTY (1<<5) /* RxFIFO empty */
#define UTS_TXFULL (1<<4) /* TxFIFO full */
#define UTS_RXFULL (1<<3) /* RxFIFO full */
#define UTS_SOFTRST (1<<0) /* Software reset */
/* We've been assigned a range on the "Low-density serial ports" major */
#define SERIAL_IMX_MAJOR 207
#define MINOR_START 16
#define DEV_NAME "ttymxc"
#define MAX_INTERNAL_IRQ MXC_INTERNAL_IRQS
/*
* This determines how often we check the modem status signals
* for any change. They generally aren't connected to an IRQ
* so we have to poll them. We also check immediately before
* filling the TX fifo incase CTS has been dropped.
*/
#define MCTRL_TIMEOUT (250*HZ/1000)
#define DRIVER_NAME "IMX-uart"
#define UART_NR 8
/* i.mx21 type uart runs on all i.mx except i.mx1 */
enum imx_uart_type {
IMX1_UART,
IMX21_UART,
};
/* device type dependent stuff */
struct imx_uart_data {
unsigned uts_reg;
enum imx_uart_type devtype;
};
struct imx_port {
struct uart_port port;
struct timer_list timer;
unsigned int old_status;
int txirq,rxirq,rtsirq;
unsigned int have_rtscts:1;
unsigned int use_irda:1;
unsigned int irda_inv_rx:1;
unsigned int irda_inv_tx:1;
unsigned short trcv_delay; /* transceiver delay */
struct clk *clk;
struct imx_uart_data *devdata;
};
struct imx_port_ucrs {
unsigned int ucr1;
unsigned int ucr2;
unsigned int ucr3;
};
#ifdef CONFIG_IRDA
#define USE_IRDA(sport) ((sport)->use_irda)
#else
#define USE_IRDA(sport) (0)
#endif
static struct imx_uart_data imx_uart_devdata[] = {
[IMX1_UART] = {
.uts_reg = IMX1_UTS,
.devtype = IMX1_UART,
},
[IMX21_UART] = {
.uts_reg = IMX21_UTS,
.devtype = IMX21_UART,
},
};
static struct platform_device_id imx_uart_devtype[] = {
{
.name = "imx1-uart",
.driver_data = (kernel_ulong_t) &imx_uart_devdata[IMX1_UART],
}, {
.name = "imx21-uart",
.driver_data = (kernel_ulong_t) &imx_uart_devdata[IMX21_UART],
}, {
/* sentinel */
}
};
MODULE_DEVICE_TABLE(platform, imx_uart_devtype);
static struct of_device_id imx_uart_dt_ids[] = {
{ .compatible = "fsl,imx1-uart", .data = &imx_uart_devdata[IMX1_UART], },
{ .compatible = "fsl,imx21-uart", .data = &imx_uart_devdata[IMX21_UART], },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, imx_uart_dt_ids);
static inline unsigned uts_reg(struct imx_port *sport)
{
return sport->devdata->uts_reg;
}
static inline int is_imx1_uart(struct imx_port *sport)
{
return sport->devdata->devtype == IMX1_UART;
}
static inline int is_imx21_uart(struct imx_port *sport)
{
return sport->devdata->devtype == IMX21_UART;
}
/*
* Save and restore functions for UCR1, UCR2 and UCR3 registers
*/
static void imx_port_ucrs_save(struct uart_port *port,
struct imx_port_ucrs *ucr)
{
/* save control registers */
ucr->ucr1 = readl(port->membase + UCR1);
ucr->ucr2 = readl(port->membase + UCR2);
ucr->ucr3 = readl(port->membase + UCR3);
}
static void imx_port_ucrs_restore(struct uart_port *port,
struct imx_port_ucrs *ucr)
{
/* restore control registers */
writel(ucr->ucr1, port->membase + UCR1);
writel(ucr->ucr2, port->membase + UCR2);
writel(ucr->ucr3, port->membase + UCR3);
}
/*
* Handle any change of modem status signal since we were last called.
*/
static void imx_mctrl_check(struct imx_port *sport)
{
unsigned int status, changed;
status = sport->port.ops->get_mctrl(&sport->port);
changed = status ^ sport->old_status;
if (changed == 0)
return;
sport->old_status = status;
if (changed & TIOCM_RI)
sport->port.icount.rng++;
if (changed & TIOCM_DSR)
sport->port.icount.dsr++;
if (changed & TIOCM_CAR)
uart_handle_dcd_change(&sport->port, status & TIOCM_CAR);
if (changed & TIOCM_CTS)
uart_handle_cts_change(&sport->port, status & TIOCM_CTS);
wake_up_interruptible(&sport->port.state->port.delta_msr_wait);
}
/*
* This is our per-port timeout handler, for checking the
* modem status signals.
*/
static void imx_timeout(unsigned long data)
{
struct imx_port *sport = (struct imx_port *)data;
unsigned long flags;
if (sport->port.state) {
spin_lock_irqsave(&sport->port.lock, flags);
imx_mctrl_check(sport);
spin_unlock_irqrestore(&sport->port.lock, flags);
mod_timer(&sport->timer, jiffies + MCTRL_TIMEOUT);
}
}
/*
* interrupts disabled on entry
*/
static void imx_stop_tx(struct uart_port *port)
{
struct imx_port *sport = (struct imx_port *)port;
unsigned long temp;
if (USE_IRDA(sport)) {
/* half duplex - wait for end of transmission */
int n = 256;
while ((--n > 0) &&
!(readl(sport->port.membase + USR2) & USR2_TXDC)) {
udelay(5);
barrier();
}
/*
* irda transceiver - wait a bit more to avoid
* cutoff, hardware dependent
*/
udelay(sport->trcv_delay);
/*
* half duplex - reactivate receive mode,
* flush receive pipe echo crap
*/
if (readl(sport->port.membase + USR2) & USR2_TXDC) {
temp = readl(sport->port.membase + UCR1);
temp &= ~(UCR1_TXMPTYEN | UCR1_TRDYEN);
writel(temp, sport->port.membase + UCR1);
temp = readl(sport->port.membase + UCR4);
temp &= ~(UCR4_TCEN);
writel(temp, sport->port.membase + UCR4);
while (readl(sport->port.membase + URXD0) &
URXD_CHARRDY)
barrier();
temp = readl(sport->port.membase + UCR1);
temp |= UCR1_RRDYEN;
writel(temp, sport->port.membase + UCR1);
temp = readl(sport->port.membase + UCR4);
temp |= UCR4_DREN;
writel(temp, sport->port.membase + UCR4);
}
return;
}
temp = readl(sport->port.membase + UCR1);
writel(temp & ~UCR1_TXMPTYEN, sport->port.membase + UCR1);
}
/*
* interrupts disabled on entry
*/
static void imx_stop_rx(struct uart_port *port)
{
struct imx_port *sport = (struct imx_port *)port;
unsigned long temp;
temp = readl(sport->port.membase + UCR2);
writel(temp &~ UCR2_RXEN, sport->port.membase + UCR2);
}
/*
* Set the modem control timer to fire immediately.
*/
static void imx_enable_ms(struct uart_port *port)
{
struct imx_port *sport = (struct imx_port *)port;
mod_timer(&sport->timer, jiffies);
}
static inline void imx_transmit_buffer(struct imx_port *sport)
{
struct circ_buf *xmit = &sport->port.state->xmit;
while (!uart_circ_empty(xmit) &&
!(readl(sport->port.membase + uts_reg(sport))
& UTS_TXFULL)) {
/* send xmit->buf[xmit->tail]
* out the port here */
writel(xmit->buf[xmit->tail], sport->port.membase + URTX0);
xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
sport->port.icount.tx++;
}
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(&sport->port);
if (uart_circ_empty(xmit))
imx_stop_tx(&sport->port);
}
/*
* interrupts disabled on entry
*/
static void imx_start_tx(struct uart_port *port)
{
struct imx_port *sport = (struct imx_port *)port;
unsigned long temp;
if (USE_IRDA(sport)) {
/* half duplex in IrDA mode; have to disable receive mode */
temp = readl(sport->port.membase + UCR4);
temp &= ~(UCR4_DREN);
writel(temp, sport->port.membase + UCR4);
temp = readl(sport->port.membase + UCR1);
temp &= ~(UCR1_RRDYEN);
writel(temp, sport->port.membase + UCR1);
}
temp = readl(sport->port.membase + UCR1);
writel(temp | UCR1_TXMPTYEN, sport->port.membase + UCR1);
if (USE_IRDA(sport)) {
temp = readl(sport->port.membase + UCR1);
temp |= UCR1_TRDYEN;
writel(temp, sport->port.membase + UCR1);
temp = readl(sport->port.membase + UCR4);
temp |= UCR4_TCEN;
writel(temp, sport->port.membase + UCR4);
}
if (readl(sport->port.membase + uts_reg(sport)) & UTS_TXEMPTY)
imx_transmit_buffer(sport);
}
static irqreturn_t imx_rtsint(int irq, void *dev_id)
{
struct imx_port *sport = dev_id;
unsigned int val;
unsigned long flags;
spin_lock_irqsave(&sport->port.lock, flags);
writel(USR1_RTSD, sport->port.membase + USR1);
val = readl(sport->port.membase + USR1) & USR1_RTSS;
uart_handle_cts_change(&sport->port, !!val);
wake_up_interruptible(&sport->port.state->port.delta_msr_wait);
spin_unlock_irqrestore(&sport->port.lock, flags);
return IRQ_HANDLED;
}
static irqreturn_t imx_txint(int irq, void *dev_id)
{
struct imx_port *sport = dev_id;
struct circ_buf *xmit = &sport->port.state->xmit;
unsigned long flags;
spin_lock_irqsave(&sport->port.lock,flags);
if (sport->port.x_char)
{
/* Send next char */
writel(sport->port.x_char, sport->port.membase + URTX0);
goto out;
}
if (uart_circ_empty(xmit) || uart_tx_stopped(&sport->port)) {
imx_stop_tx(&sport->port);
goto out;
}
imx_transmit_buffer(sport);
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
uart_write_wakeup(&sport->port);
out:
spin_unlock_irqrestore(&sport->port.lock,flags);
return IRQ_HANDLED;
}
static irqreturn_t imx_rxint(int irq, void *dev_id)
{
struct imx_port *sport = dev_id;
unsigned int rx,flg,ignored = 0;
struct tty_struct *tty = sport->port.state->port.tty;
unsigned long flags, temp;
spin_lock_irqsave(&sport->port.lock,flags);
while (readl(sport->port.membase + USR2) & USR2_RDR) {
flg = TTY_NORMAL;
sport->port.icount.rx++;
rx = readl(sport->port.membase + URXD0);
temp = readl(sport->port.membase + USR2);
if (temp & USR2_BRCD) {
writel(USR2_BRCD, sport->port.membase + USR2);
if (uart_handle_break(&sport->port))
continue;
}
if (uart_handle_sysrq_char(&sport->port, (unsigned char)rx))
continue;
if (unlikely(rx & URXD_ERR)) {
if (rx & URXD_BRK)
sport->port.icount.brk++;
else if (rx & URXD_PRERR)
sport->port.icount.parity++;
else if (rx & URXD_FRMERR)
sport->port.icount.frame++;
if (rx & URXD_OVRRUN)
sport->port.icount.overrun++;
if (rx & sport->port.ignore_status_mask) {
if (++ignored > 100)
goto out;
continue;
}
rx &= sport->port.read_status_mask;
if (rx & URXD_BRK)
flg = TTY_BREAK;
else if (rx & URXD_PRERR)
flg = TTY_PARITY;
else if (rx & URXD_FRMERR)
flg = TTY_FRAME;
if (rx & URXD_OVRRUN)
flg = TTY_OVERRUN;
#ifdef SUPPORT_SYSRQ
sport->port.sysrq = 0;
#endif
}
tty_insert_flip_char(tty, rx, flg);
}
out:
spin_unlock_irqrestore(&sport->port.lock,flags);
tty_flip_buffer_push(tty);
return IRQ_HANDLED;
}
static irqreturn_t imx_int(int irq, void *dev_id)
{
struct imx_port *sport = dev_id;
unsigned int sts;
sts = readl(sport->port.membase + USR1);
if (sts & USR1_RRDY)
imx_rxint(irq, dev_id);
if (sts & USR1_TRDY &&
readl(sport->port.membase + UCR1) & UCR1_TXMPTYEN)
imx_txint(irq, dev_id);
if (sts & USR1_RTSD)
imx_rtsint(irq, dev_id);
if (sts & USR1_AWAKE)
writel(USR1_AWAKE, sport->port.membase + USR1);
return IRQ_HANDLED;
}
/*
* Return TIOCSER_TEMT when transmitter is not busy.
*/
static unsigned int imx_tx_empty(struct uart_port *port)
{
struct imx_port *sport = (struct imx_port *)port;
return (readl(sport->port.membase + USR2) & USR2_TXDC) ? TIOCSER_TEMT : 0;
}
/*
* We have a modem side uart, so the meanings of RTS and CTS are inverted.
*/
static unsigned int imx_get_mctrl(struct uart_port *port)
{
struct imx_port *sport = (struct imx_port *)port;
unsigned int tmp = TIOCM_DSR | TIOCM_CAR;
if (readl(sport->port.membase + USR1) & USR1_RTSS)
tmp |= TIOCM_CTS;
if (readl(sport->port.membase + UCR2) & UCR2_CTS)
tmp |= TIOCM_RTS;
return tmp;
}
static void imx_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
struct imx_port *sport = (struct imx_port *)port;
unsigned long temp;
temp = readl(sport->port.membase + UCR2) & ~UCR2_CTS;
if (mctrl & TIOCM_RTS)
temp |= UCR2_CTS;
writel(temp, sport->port.membase + UCR2);
}
/*
* Interrupts always disabled.
*/
static void imx_break_ctl(struct uart_port *port, int break_state)
{
struct imx_port *sport = (struct imx_port *)port;
unsigned long flags, temp;
spin_lock_irqsave(&sport->port.lock, flags);
temp = readl(sport->port.membase + UCR1) & ~UCR1_SNDBRK;
if ( break_state != 0 )
temp |= UCR1_SNDBRK;
writel(temp, sport->port.membase + UCR1);
spin_unlock_irqrestore(&sport->port.lock, flags);
}
#define TXTL 2 /* reset default */
#define RXTL 1 /* reset default */
static int imx_setup_ufcr(struct imx_port *sport, unsigned int mode)
{
unsigned int val;
unsigned int ufcr_rfdiv;
/* set receiver / transmitter trigger level.
* RFDIV is set such way to satisfy requested uartclk value
*/
val = TXTL << 10 | RXTL;
ufcr_rfdiv = (clk_get_rate(sport->clk) + sport->port.uartclk / 2)
/ sport->port.uartclk;
if(!ufcr_rfdiv)
ufcr_rfdiv = 1;
val |= UFCR_RFDIV_REG(ufcr_rfdiv);
writel(val, sport->port.membase + UFCR);
return 0;
}
/* half the RX buffer size */
#define CTSTL 16
static int imx_startup(struct uart_port *port)
{
struct imx_port *sport = (struct imx_port *)port;
int retval;
unsigned long flags, temp;
imx_setup_ufcr(sport, 0);
/* disable the DREN bit (Data Ready interrupt enable) before
* requesting IRQs
*/
temp = readl(sport->port.membase + UCR4);
if (USE_IRDA(sport))
temp |= UCR4_IRSC;
/* set the trigger level for CTS */
temp &= ~(UCR4_CTSTL_MASK<< UCR4_CTSTL_SHF);
temp |= CTSTL<< UCR4_CTSTL_SHF;
writel(temp & ~UCR4_DREN, sport->port.membase + UCR4);
if (USE_IRDA(sport)) {
/* reset fifo's and state machines */
int i = 100;
temp = readl(sport->port.membase + UCR2);
temp &= ~UCR2_SRST;
writel(temp, sport->port.membase + UCR2);
while (!(readl(sport->port.membase + UCR2) & UCR2_SRST) &&
(--i > 0)) {
udelay(1);
}
}
/*
* Allocate the IRQ(s) i.MX1 has three interrupts whereas later
* chips only have one interrupt.
*/
if (sport->txirq > 0) {
retval = request_irq(sport->rxirq, imx_rxint, 0,
DRIVER_NAME, sport);
if (retval)
goto error_out1;
retval = request_irq(sport->txirq, imx_txint, 0,
DRIVER_NAME, sport);
if (retval)
goto error_out2;
/* do not use RTS IRQ on IrDA */
if (!USE_IRDA(sport)) {
retval = request_irq(sport->rtsirq, imx_rtsint,
(sport->rtsirq < MAX_INTERNAL_IRQ) ? 0 :
IRQF_TRIGGER_FALLING |
IRQF_TRIGGER_RISING,
DRIVER_NAME, sport);
if (retval)
goto error_out3;
}
} else {
retval = request_irq(sport->port.irq, imx_int, 0,
DRIVER_NAME, sport);
if (retval) {
free_irq(sport->port.irq, sport);
goto error_out1;
}
}
/*
* Finally, clear and enable interrupts
*/
writel(USR1_RTSD, sport->port.membase + USR1);
temp = readl(sport->port.membase + UCR1);
temp |= UCR1_RRDYEN | UCR1_RTSDEN | UCR1_UARTEN;
if (USE_IRDA(sport)) {
temp |= UCR1_IREN;
temp &= ~(UCR1_RTSDEN);
}
writel(temp, sport->port.membase + UCR1);
temp = readl(sport->port.membase + UCR2);
temp |= (UCR2_RXEN | UCR2_TXEN);
writel(temp, sport->port.membase + UCR2);
if (USE_IRDA(sport)) {
/* clear RX-FIFO */
int i = 64;
while ((--i > 0) &&
(readl(sport->port.membase + URXD0) & URXD_CHARRDY)) {
barrier();
}
}
if (is_imx21_uart(sport)) {
temp = readl(sport->port.membase + UCR3);
temp |= IMX21_UCR3_RXDMUXSEL;
writel(temp, sport->port.membase + UCR3);
}
if (USE_IRDA(sport)) {
temp = readl(sport->port.membase + UCR4);
if (sport->irda_inv_rx)
temp |= UCR4_INVR;
else
temp &= ~(UCR4_INVR);
writel(temp | UCR4_DREN, sport->port.membase + UCR4);
temp = readl(sport->port.membase + UCR3);
if (sport->irda_inv_tx)
temp |= UCR3_INVT;
else
temp &= ~(UCR3_INVT);
writel(temp, sport->port.membase + UCR3);
}
/*
* Enable modem status interrupts
*/
spin_lock_irqsave(&sport->port.lock,flags);
imx_enable_ms(&sport->port);
spin_unlock_irqrestore(&sport->port.lock,flags);
if (USE_IRDA(sport)) {
struct imxuart_platform_data *pdata;
pdata = sport->port.dev->platform_data;
sport->irda_inv_rx = pdata->irda_inv_rx;
sport->irda_inv_tx = pdata->irda_inv_tx;
sport->trcv_delay = pdata->transceiver_delay;
if (pdata->irda_enable)
pdata->irda_enable(1);
}
return 0;
error_out3:
if (sport->txirq)
free_irq(sport->txirq, sport);
error_out2:
if (sport->rxirq)
free_irq(sport->rxirq, sport);
error_out1:
return retval;
}
static void imx_shutdown(struct uart_port *port)
{
struct imx_port *sport = (struct imx_port *)port;
unsigned long temp;
temp = readl(sport->port.membase + UCR2);
temp &= ~(UCR2_TXEN);
writel(temp, sport->port.membase + UCR2);
if (USE_IRDA(sport)) {
struct imxuart_platform_data *pdata;
pdata = sport->port.dev->platform_data;
if (pdata->irda_enable)
pdata->irda_enable(0);
}
/*
* Stop our timer.
*/
del_timer_sync(&sport->timer);
/*
* Free the interrupts
*/
if (sport->txirq > 0) {
if (!USE_IRDA(sport))
free_irq(sport->rtsirq, sport);
free_irq(sport->txirq, sport);
free_irq(sport->rxirq, sport);
} else
free_irq(sport->port.irq, sport);
/*
* Disable all interrupts, port and break condition.
*/
temp = readl(sport->port.membase + UCR1);
temp &= ~(UCR1_TXMPTYEN | UCR1_RRDYEN | UCR1_RTSDEN | UCR1_UARTEN);
if (USE_IRDA(sport))
temp &= ~(UCR1_IREN);
writel(temp, sport->port.membase + UCR1);
}
static void
imx_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
struct imx_port *sport = (struct imx_port *)port;
unsigned long flags;
unsigned int ucr2, old_ucr1, old_txrxen, baud, quot;
unsigned int old_csize = old ? old->c_cflag & CSIZE : CS8;
unsigned int div, ufcr;
unsigned long num, denom;
uint64_t tdiv64;
/*
* If we don't support modem control lines, don't allow
* these to be set.
*/
if (0) {
termios->c_cflag &= ~(HUPCL | CRTSCTS | CMSPAR);
termios->c_cflag |= CLOCAL;
}
/*
* We only support CS7 and CS8.
*/
while ((termios->c_cflag & CSIZE) != CS7 &&
(termios->c_cflag & CSIZE) != CS8) {
termios->c_cflag &= ~CSIZE;
termios->c_cflag |= old_csize;
old_csize = CS8;
}
if ((termios->c_cflag & CSIZE) == CS8)
ucr2 = UCR2_WS | UCR2_SRST | UCR2_IRTS;
else
ucr2 = UCR2_SRST | UCR2_IRTS;
if (termios->c_cflag & CRTSCTS) {
if( sport->have_rtscts ) {
ucr2 &= ~UCR2_IRTS;
ucr2 |= UCR2_CTSC;
} else {
termios->c_cflag &= ~CRTSCTS;
}
}
if (termios->c_cflag & CSTOPB)
ucr2 |= UCR2_STPB;
if (termios->c_cflag & PARENB) {
ucr2 |= UCR2_PREN;
if (termios->c_cflag & PARODD)
ucr2 |= UCR2_PROE;
}
del_timer_sync(&sport->timer);
/*
* Ask the core to calculate the divisor for us.
*/
baud = uart_get_baud_rate(port, termios, old, 50, port->uartclk / 16);
quot = uart_get_divisor(port, baud);
spin_lock_irqsave(&sport->port.lock, flags);
sport->port.read_status_mask = 0;
if (termios->c_iflag & INPCK)
sport->port.read_status_mask |= (URXD_FRMERR | URXD_PRERR);
if (termios->c_iflag & (BRKINT | PARMRK))
sport->port.read_status_mask |= URXD_BRK;
/*
* Characters to ignore
*/
sport->port.ignore_status_mask = 0;
if (termios->c_iflag & IGNPAR)
sport->port.ignore_status_mask |= URXD_PRERR;
if (termios->c_iflag & IGNBRK) {
sport->port.ignore_status_mask |= URXD_BRK;
/*
* If we're ignoring parity and break indicators,
* ignore overruns too (for real raw support).
*/
if (termios->c_iflag & IGNPAR)
sport->port.ignore_status_mask |= URXD_OVRRUN;
}
/*
* Update the per-port timeout.
*/
uart_update_timeout(port, termios->c_cflag, baud);
/*
* disable interrupts and drain transmitter
*/
old_ucr1 = readl(sport->port.membase + UCR1);
writel(old_ucr1 & ~(UCR1_TXMPTYEN | UCR1_RRDYEN | UCR1_RTSDEN),
sport->port.membase + UCR1);
while ( !(readl(sport->port.membase + USR2) & USR2_TXDC))
barrier();
/* then, disable everything */
old_txrxen = readl(sport->port.membase + UCR2);
writel(old_txrxen & ~( UCR2_TXEN | UCR2_RXEN),
sport->port.membase + UCR2);
old_txrxen &= (UCR2_TXEN | UCR2_RXEN);
if (USE_IRDA(sport)) {
/*
* use maximum available submodule frequency to
* avoid missing short pulses due to low sampling rate
*/
div = 1;
} else {
div = sport->port.uartclk / (baud * 16);
if (div > 7)
div = 7;
if (!div)
div = 1;
}
rational_best_approximation(16 * div * baud, sport->port.uartclk,
1 << 16, 1 << 16, &num, &denom);
tdiv64 = sport->port.uartclk;
tdiv64 *= num;
do_div(tdiv64, denom * 16 * div);
tty_termios_encode_baud_rate(termios,
(speed_t)tdiv64, (speed_t)tdiv64);
num -= 1;
denom -= 1;
ufcr = readl(sport->port.membase + UFCR);
ufcr = (ufcr & (~UFCR_RFDIV)) | UFCR_RFDIV_REG(div);
writel(ufcr, sport->port.membase + UFCR);
writel(num, sport->port.membase + UBIR);
writel(denom, sport->port.membase + UBMR);
if (is_imx21_uart(sport))
writel(sport->port.uartclk / div / 1000,
sport->port.membase + IMX21_ONEMS);
writel(old_ucr1, sport->port.membase + UCR1);
/* set the parity, stop bits and data size */
writel(ucr2 | old_txrxen, sport->port.membase + UCR2);
if (UART_ENABLE_MS(&sport->port, termios->c_cflag))
imx_enable_ms(&sport->port);
spin_unlock_irqrestore(&sport->port.lock, flags);
}
static const char *imx_type(struct uart_port *port)
{
struct imx_port *sport = (struct imx_port *)port;
return sport->port.type == PORT_IMX ? "IMX" : NULL;
}
/*
* Release the memory region(s) being used by 'port'.
*/
static void imx_release_port(struct uart_port *port)
{
struct platform_device *pdev = to_platform_device(port->dev);
struct resource *mmres;
mmres = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(mmres->start, resource_size(mmres));
}
/*
* Request the memory region(s) being used by 'port'.
*/
static int imx_request_port(struct uart_port *port)
{
struct platform_device *pdev = to_platform_device(port->dev);
struct resource *mmres;
void *ret;
mmres = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mmres)
return -ENODEV;
ret = request_mem_region(mmres->start, resource_size(mmres), "imx-uart");
return ret ? 0 : -EBUSY;
}
/*
* Configure/autoconfigure the port.
*/
static void imx_config_port(struct uart_port *port, int flags)
{
struct imx_port *sport = (struct imx_port *)port;
if (flags & UART_CONFIG_TYPE &&
imx_request_port(&sport->port) == 0)
sport->port.type = PORT_IMX;
}
/*
* Verify the new serial_struct (for TIOCSSERIAL).
* The only change we allow are to the flags and type, and
* even then only between PORT_IMX and PORT_UNKNOWN
*/
static int
imx_verify_port(struct uart_port *port, struct serial_struct *ser)
{
struct imx_port *sport = (struct imx_port *)port;
int ret = 0;
if (ser->type != PORT_UNKNOWN && ser->type != PORT_IMX)
ret = -EINVAL;
if (sport->port.irq != ser->irq)
ret = -EINVAL;
if (ser->io_type != UPIO_MEM)
ret = -EINVAL;
if (sport->port.uartclk / 16 != ser->baud_base)
ret = -EINVAL;
if ((void *)sport->port.mapbase != ser->iomem_base)
ret = -EINVAL;
if (sport->port.iobase != ser->port)
ret = -EINVAL;
if (ser->hub6 != 0)
ret = -EINVAL;
return ret;
}
#if defined(CONFIG_CONSOLE_POLL)
static int imx_poll_get_char(struct uart_port *port)
{
struct imx_port_ucrs old_ucr;
unsigned int status;
unsigned char c;
/* save control registers */
imx_port_ucrs_save(port, &old_ucr);
/* disable interrupts */
writel(UCR1_UARTEN, port->membase + UCR1);
writel(old_ucr.ucr2 & ~(UCR2_ATEN | UCR2_RTSEN | UCR2_ESCI),
port->membase + UCR2);
writel(old_ucr.ucr3 & ~(UCR3_DCD | UCR3_RI | UCR3_DTREN),
port->membase + UCR3);
/* poll */
do {
status = readl(port->membase + USR2);
} while (~status & USR2_RDR);
/* read */
c = readl(port->membase + URXD0);
/* restore control registers */
imx_port_ucrs_restore(port, &old_ucr);
return c;
}
static void imx_poll_put_char(struct uart_port *port, unsigned char c)
{
struct imx_port_ucrs old_ucr;
unsigned int status;
/* save control registers */
imx_port_ucrs_save(port, &old_ucr);
/* disable interrupts */
writel(UCR1_UARTEN, port->membase + UCR1);
writel(old_ucr.ucr2 & ~(UCR2_ATEN | UCR2_RTSEN | UCR2_ESCI),
port->membase + UCR2);
writel(old_ucr.ucr3 & ~(UCR3_DCD | UCR3_RI | UCR3_DTREN),
port->membase + UCR3);
/* drain */
do {
status = readl(port->membase + USR1);
} while (~status & USR1_TRDY);
/* write */
writel(c, port->membase + URTX0);
/* flush */
do {
status = readl(port->membase + USR2);
} while (~status & USR2_TXDC);
/* restore control registers */
imx_port_ucrs_restore(port, &old_ucr);
}
#endif
static struct uart_ops imx_pops = {
.tx_empty = imx_tx_empty,
.set_mctrl = imx_set_mctrl,
.get_mctrl = imx_get_mctrl,
.stop_tx = imx_stop_tx,
.start_tx = imx_start_tx,
.stop_rx = imx_stop_rx,
.enable_ms = imx_enable_ms,
.break_ctl = imx_break_ctl,
.startup = imx_startup,
.shutdown = imx_shutdown,
.set_termios = imx_set_termios,
.type = imx_type,
.release_port = imx_release_port,
.request_port = imx_request_port,
.config_port = imx_config_port,
.verify_port = imx_verify_port,
#if defined(CONFIG_CONSOLE_POLL)
.poll_get_char = imx_poll_get_char,
.poll_put_char = imx_poll_put_char,
#endif
};
static struct imx_port *imx_ports[UART_NR];
#ifdef CONFIG_SERIAL_IMX_CONSOLE
static void imx_console_putchar(struct uart_port *port, int ch)
{
struct imx_port *sport = (struct imx_port *)port;
while (readl(sport->port.membase + uts_reg(sport)) & UTS_TXFULL)
barrier();
writel(ch, sport->port.membase + URTX0);
}
/*
* Interrupts are disabled on entering
*/
static void
imx_console_write(struct console *co, const char *s, unsigned int count)
{
struct imx_port *sport = imx_ports[co->index];
struct imx_port_ucrs old_ucr;
unsigned int ucr1;
/*
* First, save UCR1/2/3 and then disable interrupts
*/
imx_port_ucrs_save(&sport->port, &old_ucr);
ucr1 = old_ucr.ucr1;
if (is_imx1_uart(sport))
ucr1 |= IMX1_UCR1_UARTCLKEN;
ucr1 |= UCR1_UARTEN;
ucr1 &= ~(UCR1_TXMPTYEN | UCR1_RRDYEN | UCR1_RTSDEN);
writel(ucr1, sport->port.membase + UCR1);
writel(old_ucr.ucr2 | UCR2_TXEN, sport->port.membase + UCR2);
uart_console_write(&sport->port, s, count, imx_console_putchar);
/*
* Finally, wait for transmitter to become empty
* and restore UCR1/2/3
*/
while (!(readl(sport->port.membase + USR2) & USR2_TXDC));
imx_port_ucrs_restore(&sport->port, &old_ucr);
}
/*
* If the port was already initialised (eg, by a boot loader),
* try to determine the current setup.
*/
static void __init
imx_console_get_options(struct imx_port *sport, int *baud,
int *parity, int *bits)
{
if (readl(sport->port.membase + UCR1) & UCR1_UARTEN) {
/* ok, the port was enabled */
unsigned int ucr2, ubir,ubmr, uartclk;
unsigned int baud_raw;
unsigned int ucfr_rfdiv;
ucr2 = readl(sport->port.membase + UCR2);
*parity = 'n';
if (ucr2 & UCR2_PREN) {
if (ucr2 & UCR2_PROE)
*parity = 'o';
else
*parity = 'e';
}
if (ucr2 & UCR2_WS)
*bits = 8;
else
*bits = 7;
ubir = readl(sport->port.membase + UBIR) & 0xffff;
ubmr = readl(sport->port.membase + UBMR) & 0xffff;
ucfr_rfdiv = (readl(sport->port.membase + UFCR) & UFCR_RFDIV) >> 7;
if (ucfr_rfdiv == 6)
ucfr_rfdiv = 7;
else
ucfr_rfdiv = 6 - ucfr_rfdiv;
uartclk = clk_get_rate(sport->clk);
uartclk /= ucfr_rfdiv;
{ /*
* The next code provides exact computation of
* baud_raw = round(((uartclk/16) * (ubir + 1)) / (ubmr + 1))
* without need of float support or long long division,
* which would be required to prevent 32bit arithmetic overflow
*/
unsigned int mul = ubir + 1;
unsigned int div = 16 * (ubmr + 1);
unsigned int rem = uartclk % div;
baud_raw = (uartclk / div) * mul;
baud_raw += (rem * mul + div / 2) / div;
*baud = (baud_raw + 50) / 100 * 100;
}
if(*baud != baud_raw)
printk(KERN_INFO "Serial: Console IMX rounded baud rate from %d to %d\n",
baud_raw, *baud);
}
}
static int __init
imx_console_setup(struct console *co, char *options)
{
struct imx_port *sport;
int baud = 9600;
int bits = 8;
int parity = 'n';
int flow = 'n';
/*
* Check whether an invalid uart number has been specified, and
* if so, search for the first available port that does have
* console support.
*/
if (co->index == -1 || co->index >= ARRAY_SIZE(imx_ports))
co->index = 0;
sport = imx_ports[co->index];
if(sport == NULL)
return -ENODEV;
if (options)
uart_parse_options(options, &baud, &parity, &bits, &flow);
else
imx_console_get_options(sport, &baud, &parity, &bits);
imx_setup_ufcr(sport, 0);
return uart_set_options(&sport->port, co, baud, parity, bits, flow);
}
static struct uart_driver imx_reg;
static struct console imx_console = {
.name = DEV_NAME,
.write = imx_console_write,
.device = uart_console_device,
.setup = imx_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &imx_reg,
};
#define IMX_CONSOLE &imx_console
#else
#define IMX_CONSOLE NULL
#endif
static struct uart_driver imx_reg = {
.owner = THIS_MODULE,
.driver_name = DRIVER_NAME,
.dev_name = DEV_NAME,
.major = SERIAL_IMX_MAJOR,
.minor = MINOR_START,
.nr = ARRAY_SIZE(imx_ports),
.cons = IMX_CONSOLE,
};
static int serial_imx_suspend(struct platform_device *dev, pm_message_t state)
{
struct imx_port *sport = platform_get_drvdata(dev);
unsigned int val;
/* enable wakeup from i.MX UART */
val = readl(sport->port.membase + UCR3);
val |= UCR3_AWAKEN;
writel(val, sport->port.membase + UCR3);
if (sport)
uart_suspend_port(&imx_reg, &sport->port);
return 0;
}
static int serial_imx_resume(struct platform_device *dev)
{
struct imx_port *sport = platform_get_drvdata(dev);
unsigned int val;
/* disable wakeup from i.MX UART */
val = readl(sport->port.membase + UCR3);
val &= ~UCR3_AWAKEN;
writel(val, sport->port.membase + UCR3);
if (sport)
uart_resume_port(&imx_reg, &sport->port);
return 0;
}
#ifdef CONFIG_OF
/*
* This function returns 1 iff pdev isn't a device instatiated by dt, 0 iff it
* could successfully get all information from dt or a negative errno.
*/
static int serial_imx_probe_dt(struct imx_port *sport,
struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
const struct of_device_id *of_id =
of_match_device(imx_uart_dt_ids, &pdev->dev);
int ret;
if (!np)
/* no device tree device */
return 1;
ret = of_alias_get_id(np, "serial");
if (ret < 0) {
dev_err(&pdev->dev, "failed to get alias id, errno %d\n", ret);
return ret;
}
sport->port.line = ret;
if (of_get_property(np, "fsl,uart-has-rtscts", NULL))
sport->have_rtscts = 1;
if (of_get_property(np, "fsl,irda-mode", NULL))
sport->use_irda = 1;
sport->devdata = of_id->data;
return 0;
}
#else
static inline int serial_imx_probe_dt(struct imx_port *sport,
struct platform_device *pdev)
{
return 1;
}
#endif
static void serial_imx_probe_pdata(struct imx_port *sport,
struct platform_device *pdev)
{
struct imxuart_platform_data *pdata = pdev->dev.platform_data;
sport->port.line = pdev->id;
sport->devdata = (struct imx_uart_data *) pdev->id_entry->driver_data;
if (!pdata)
return;
if (pdata->flags & IMXUART_HAVE_RTSCTS)
sport->have_rtscts = 1;
if (pdata->flags & IMXUART_IRDA)
sport->use_irda = 1;
}
static int serial_imx_probe(struct platform_device *pdev)
{
struct imx_port *sport;
struct imxuart_platform_data *pdata;
void __iomem *base;
int ret = 0;
struct resource *res;
sport = kzalloc(sizeof(*sport), GFP_KERNEL);
if (!sport)
return -ENOMEM;
ret = serial_imx_probe_dt(sport, pdev);
if (ret > 0)
serial_imx_probe_pdata(sport, pdev);
else if (ret < 0)
goto free;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
goto free;
}
base = ioremap(res->start, PAGE_SIZE);
if (!base) {
ret = -ENOMEM;
goto free;
}
sport->port.dev = &pdev->dev;
sport->port.mapbase = res->start;
sport->port.membase = base;
sport->port.type = PORT_IMX,
sport->port.iotype = UPIO_MEM;
sport->port.irq = platform_get_irq(pdev, 0);
sport->rxirq = platform_get_irq(pdev, 0);
sport->txirq = platform_get_irq(pdev, 1);
sport->rtsirq = platform_get_irq(pdev, 2);
sport->port.fifosize = 32;
sport->port.ops = &imx_pops;
sport->port.flags = UPF_BOOT_AUTOCONF;
init_timer(&sport->timer);
sport->timer.function = imx_timeout;
sport->timer.data = (unsigned long)sport;
sport->clk = clk_get(&pdev->dev, "uart");
if (IS_ERR(sport->clk)) {
ret = PTR_ERR(sport->clk);
goto unmap;
}
clk_prepare_enable(sport->clk);
sport->port.uartclk = clk_get_rate(sport->clk);
imx_ports[sport->port.line] = sport;
pdata = pdev->dev.platform_data;
if (pdata && pdata->init) {
ret = pdata->init(pdev);
if (ret)
goto clkput;
}
ret = uart_add_one_port(&imx_reg, &sport->port);
if (ret)
goto deinit;
platform_set_drvdata(pdev, &sport->port);
return 0;
deinit:
if (pdata && pdata->exit)
pdata->exit(pdev);
clkput:
clk_disable_unprepare(sport->clk);
clk_put(sport->clk);
unmap:
iounmap(sport->port.membase);
free:
kfree(sport);
return ret;
}
static int serial_imx_remove(struct platform_device *pdev)
{
struct imxuart_platform_data *pdata;
struct imx_port *sport = platform_get_drvdata(pdev);
pdata = pdev->dev.platform_data;
platform_set_drvdata(pdev, NULL);
if (sport) {
uart_remove_one_port(&imx_reg, &sport->port);
clk_disable_unprepare(sport->clk);
clk_put(sport->clk);
}
if (pdata && pdata->exit)
pdata->exit(pdev);
iounmap(sport->port.membase);
kfree(sport);
return 0;
}
static struct platform_driver serial_imx_driver = {
.probe = serial_imx_probe,
.remove = serial_imx_remove,
.suspend = serial_imx_suspend,
.resume = serial_imx_resume,
.id_table = imx_uart_devtype,
.driver = {
.name = "imx-uart",
.owner = THIS_MODULE,
.of_match_table = imx_uart_dt_ids,
},
};
static int __init imx_serial_init(void)
{
int ret;
printk(KERN_INFO "Serial: IMX driver\n");
ret = uart_register_driver(&imx_reg);
if (ret)
return ret;
ret = platform_driver_register(&serial_imx_driver);
if (ret != 0)
uart_unregister_driver(&imx_reg);
return ret;
}
static void __exit imx_serial_exit(void)
{
platform_driver_unregister(&serial_imx_driver);
uart_unregister_driver(&imx_reg);
}
module_init(imx_serial_init);
module_exit(imx_serial_exit);
MODULE_AUTHOR("Sascha Hauer");
MODULE_DESCRIPTION("IMX generic serial port driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:imx-uart");
| gpl-2.0 |
rujelus22/The-Kuban-Kernel | sound/pci/emu10k1/emu10k1.c | 3509 | 9019 | /*
* The driver for the EMU10K1 (SB Live!) based soundcards
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
* Copyright (c) by James Courtier-Dutton <James@superbug.demon.co.uk>
* Added support for Audigy 2 Value.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
*/
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/time.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/emu10k1.h>
#include <sound/initval.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_DESCRIPTION("EMU10K1");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Creative Labs,SB Live!/PCI512/E-mu APS},"
"{Creative Labs,SB Audigy}}");
#if defined(CONFIG_SND_SEQUENCER) || (defined(MODULE) && defined(CONFIG_SND_SEQUENCER_MODULE))
#define ENABLE_SYNTH
#include <sound/emu10k1_synth.h>
#endif
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable this card */
static int extin[SNDRV_CARDS];
static int extout[SNDRV_CARDS];
static int seq_ports[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 4};
static int max_synth_voices[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 64};
static int max_buffer_size[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 128};
static int enable_ir[SNDRV_CARDS];
static uint subsystem[SNDRV_CARDS]; /* Force card subsystem model */
static uint delay_pcm_irq[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 2};
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for the EMU10K1 soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for the EMU10K1 soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable the EMU10K1 soundcard.");
module_param_array(extin, int, NULL, 0444);
MODULE_PARM_DESC(extin, "Available external inputs for FX8010. Zero=default.");
module_param_array(extout, int, NULL, 0444);
MODULE_PARM_DESC(extout, "Available external outputs for FX8010. Zero=default.");
module_param_array(seq_ports, int, NULL, 0444);
MODULE_PARM_DESC(seq_ports, "Allocated sequencer ports for internal synthesizer.");
module_param_array(max_synth_voices, int, NULL, 0444);
MODULE_PARM_DESC(max_synth_voices, "Maximum number of voices for WaveTable.");
module_param_array(max_buffer_size, int, NULL, 0444);
MODULE_PARM_DESC(max_buffer_size, "Maximum sample buffer size in MB.");
module_param_array(enable_ir, bool, NULL, 0444);
MODULE_PARM_DESC(enable_ir, "Enable IR.");
module_param_array(subsystem, uint, NULL, 0444);
MODULE_PARM_DESC(subsystem, "Force card subsystem model.");
module_param_array(delay_pcm_irq, uint, NULL, 0444);
MODULE_PARM_DESC(delay_pcm_irq, "Delay PCM interrupt by specified number of samples (default 0).");
/*
* Class 0401: 1102:0008 (rev 00) Subsystem: 1102:1001 -> Audigy2 Value Model:SB0400
*/
static DEFINE_PCI_DEVICE_TABLE(snd_emu10k1_ids) = {
{ PCI_VDEVICE(CREATIVE, 0x0002), 0 }, /* EMU10K1 */
{ PCI_VDEVICE(CREATIVE, 0x0004), 1 }, /* Audigy */
{ PCI_VDEVICE(CREATIVE, 0x0008), 1 }, /* Audigy 2 Value SB0400 */
{ 0, }
};
/*
* Audigy 2 Value notes:
* A_IOCFG Input (GPIO)
* 0x400 = Front analog jack plugged in. (Green socket)
* 0x1000 = Read analog jack plugged in. (Black socket)
* 0x2000 = Center/LFE analog jack plugged in. (Orange socket)
* A_IOCFG Output (GPIO)
* 0x60 = Sound out of front Left.
* Win sets it to 0xXX61
*/
MODULE_DEVICE_TABLE(pci, snd_emu10k1_ids);
static int __devinit snd_card_emu10k1_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct snd_emu10k1 *emu;
#ifdef ENABLE_SYNTH
struct snd_seq_device *wave = NULL;
#endif
int err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
if (max_buffer_size[dev] < 32)
max_buffer_size[dev] = 32;
else if (max_buffer_size[dev] > 1024)
max_buffer_size[dev] = 1024;
if ((err = snd_emu10k1_create(card, pci, extin[dev], extout[dev],
(long)max_buffer_size[dev] * 1024 * 1024,
enable_ir[dev], subsystem[dev],
&emu)) < 0)
goto error;
card->private_data = emu;
emu->delay_pcm_irq = delay_pcm_irq[dev] & 0x1f;
if ((err = snd_emu10k1_pcm(emu, 0, NULL)) < 0)
goto error;
if ((err = snd_emu10k1_pcm_mic(emu, 1, NULL)) < 0)
goto error;
if ((err = snd_emu10k1_pcm_efx(emu, 2, NULL)) < 0)
goto error;
/* This stores the periods table. */
if (emu->card_capabilities->ca0151_chip) { /* P16V */
if ((err = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci),
1024, &emu->p16v_buffer)) < 0)
goto error;
}
if ((err = snd_emu10k1_mixer(emu, 0, 3)) < 0)
goto error;
if ((err = snd_emu10k1_timer(emu, 0)) < 0)
goto error;
if ((err = snd_emu10k1_pcm_multi(emu, 3, NULL)) < 0)
goto error;
if (emu->card_capabilities->ca0151_chip) { /* P16V */
if ((err = snd_p16v_pcm(emu, 4, NULL)) < 0)
goto error;
}
if (emu->audigy) {
if ((err = snd_emu10k1_audigy_midi(emu)) < 0)
goto error;
} else {
if ((err = snd_emu10k1_midi(emu)) < 0)
goto error;
}
if ((err = snd_emu10k1_fx8010_new(emu, 0, NULL)) < 0)
goto error;
#ifdef ENABLE_SYNTH
if (snd_seq_device_new(card, 1, SNDRV_SEQ_DEV_ID_EMU10K1_SYNTH,
sizeof(struct snd_emu10k1_synth_arg), &wave) < 0 ||
wave == NULL) {
snd_printk(KERN_WARNING "can't initialize Emu10k1 wavetable synth\n");
} else {
struct snd_emu10k1_synth_arg *arg;
arg = SNDRV_SEQ_DEVICE_ARGPTR(wave);
strcpy(wave->name, "Emu-10k1 Synth");
arg->hwptr = emu;
arg->index = 1;
arg->seq_ports = seq_ports[dev];
arg->max_voices = max_synth_voices[dev];
}
#endif
strcpy(card->driver, emu->card_capabilities->driver);
strcpy(card->shortname, emu->card_capabilities->name);
snprintf(card->longname, sizeof(card->longname),
"%s (rev.%d, serial:0x%x) at 0x%lx, irq %i",
card->shortname, emu->revision, emu->serial, emu->port, emu->irq);
if ((err = snd_card_register(card)) < 0)
goto error;
pci_set_drvdata(pci, card);
dev++;
return 0;
error:
snd_card_free(card);
return err;
}
static void __devexit snd_card_emu10k1_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
#ifdef CONFIG_PM
static int snd_emu10k1_suspend(struct pci_dev *pci, pm_message_t state)
{
struct snd_card *card = pci_get_drvdata(pci);
struct snd_emu10k1 *emu = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(emu->pcm);
snd_pcm_suspend_all(emu->pcm_mic);
snd_pcm_suspend_all(emu->pcm_efx);
snd_pcm_suspend_all(emu->pcm_multi);
snd_pcm_suspend_all(emu->pcm_p16v);
snd_ac97_suspend(emu->ac97);
snd_emu10k1_efx_suspend(emu);
snd_emu10k1_suspend_regs(emu);
if (emu->card_capabilities->ca0151_chip)
snd_p16v_suspend(emu);
snd_emu10k1_done(emu);
pci_disable_device(pci);
pci_save_state(pci);
pci_set_power_state(pci, pci_choose_state(pci, state));
return 0;
}
static int snd_emu10k1_resume(struct pci_dev *pci)
{
struct snd_card *card = pci_get_drvdata(pci);
struct snd_emu10k1 *emu = card->private_data;
pci_set_power_state(pci, PCI_D0);
pci_restore_state(pci);
if (pci_enable_device(pci) < 0) {
printk(KERN_ERR "emu10k1: pci_enable_device failed, "
"disabling device\n");
snd_card_disconnect(card);
return -EIO;
}
pci_set_master(pci);
snd_emu10k1_resume_init(emu);
snd_emu10k1_efx_resume(emu);
snd_ac97_resume(emu->ac97);
snd_emu10k1_resume_regs(emu);
if (emu->card_capabilities->ca0151_chip)
snd_p16v_resume(emu);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif
static struct pci_driver driver = {
.name = "EMU10K1_Audigy",
.id_table = snd_emu10k1_ids,
.probe = snd_card_emu10k1_probe,
.remove = __devexit_p(snd_card_emu10k1_remove),
#ifdef CONFIG_PM
.suspend = snd_emu10k1_suspend,
.resume = snd_emu10k1_resume,
#endif
};
static int __init alsa_card_emu10k1_init(void)
{
return pci_register_driver(&driver);
}
static void __exit alsa_card_emu10k1_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(alsa_card_emu10k1_init)
module_exit(alsa_card_emu10k1_exit)
| gpl-2.0 |
haoyangw/android_kernel_xiaomi_dior | drivers/gpio/devres.c | 4533 | 2411 | /*
* drivers/gpio/devres.c - managed gpio resources
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* This file is based on kernel/irq/devres.c
*
* Copyright (c) 2011 John Crispin <blogic@openwrt.org>
*/
#include <linux/module.h>
#include <linux/gpio.h>
#include <linux/device.h>
#include <linux/gfp.h>
static void devm_gpio_release(struct device *dev, void *res)
{
unsigned *gpio = res;
gpio_free(*gpio);
}
static int devm_gpio_match(struct device *dev, void *res, void *data)
{
unsigned *this = res, *gpio = data;
return *this == *gpio;
}
/**
* devm_gpio_request - request a gpio for a managed device
* @dev: device to request the gpio for
* @gpio: gpio to allocate
* @label: the name of the requested gpio
*
* Except for the extra @dev argument, this function takes the
* same arguments and performs the same function as
* gpio_request(). GPIOs requested with this function will be
* automatically freed on driver detach.
*
* If an GPIO allocated with this function needs to be freed
* separately, devm_gpio_free() must be used.
*/
int devm_gpio_request(struct device *dev, unsigned gpio, const char *label)
{
unsigned *dr;
int rc;
dr = devres_alloc(devm_gpio_release, sizeof(unsigned), GFP_KERNEL);
if (!dr)
return -ENOMEM;
rc = gpio_request(gpio, label);
if (rc) {
devres_free(dr);
return rc;
}
*dr = gpio;
devres_add(dev, dr);
return 0;
}
EXPORT_SYMBOL(devm_gpio_request);
/**
* devm_gpio_free - free an interrupt
* @dev: device to free gpio for
* @gpio: gpio to free
*
* Except for the extra @dev argument, this function takes the
* same arguments and performs the same function as gpio_free().
* This function instead of gpio_free() should be used to manually
* free GPIOs allocated with devm_gpio_request().
*/
void devm_gpio_free(struct device *dev, unsigned int gpio)
{
WARN_ON(devres_destroy(dev, devm_gpio_release, devm_gpio_match,
&gpio));
gpio_free(gpio);
}
EXPORT_SYMBOL(devm_gpio_free);
| gpl-2.0 |
jorik041/KTSGS5 | drivers/acpi/acpica/exoparg6.c | 5045 | 9917 |
/******************************************************************************
*
* Module Name: exoparg6 - AML execution - opcodes with 6 arguments
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2012, Intel Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions, and the following disclaimer,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acinterp.h"
#include "acparser.h"
#include "amlcode.h"
#define _COMPONENT ACPI_EXECUTER
ACPI_MODULE_NAME("exoparg6")
/*!
* Naming convention for AML interpreter execution routines.
*
* The routines that begin execution of AML opcodes are named with a common
* convention based upon the number of arguments, the number of target operands,
* and whether or not a value is returned:
*
* AcpiExOpcode_xA_yT_zR
*
* Where:
*
* xA - ARGUMENTS: The number of arguments (input operands) that are
* required for this opcode type (1 through 6 args).
* yT - TARGETS: The number of targets (output operands) that are required
* for this opcode type (0, 1, or 2 targets).
* zR - RETURN VALUE: Indicates whether this opcode type returns a value
* as the function return (0 or 1).
*
* The AcpiExOpcode* functions are called via the Dispatcher component with
* fully resolved operands.
!*/
/* Local prototypes */
static u8
acpi_ex_do_match(u32 match_op,
union acpi_operand_object *package_obj,
union acpi_operand_object *match_obj);
/*******************************************************************************
*
* FUNCTION: acpi_ex_do_match
*
* PARAMETERS: match_op - The AML match operand
* package_obj - Object from the target package
* match_obj - Object to be matched
*
* RETURN: TRUE if the match is successful, FALSE otherwise
*
* DESCRIPTION: Implements the low-level match for the ASL Match operator.
* Package elements will be implicitly converted to the type of
* the match object (Integer/Buffer/String).
*
******************************************************************************/
static u8
acpi_ex_do_match(u32 match_op,
union acpi_operand_object *package_obj,
union acpi_operand_object *match_obj)
{
u8 logical_result = TRUE;
acpi_status status;
/*
* Note: Since the package_obj/match_obj ordering is opposite to that of
* the standard logical operators, we have to reverse them when we call
* do_logical_op in order to make the implicit conversion rules work
* correctly. However, this means we have to flip the entire equation
* also. A bit ugly perhaps, but overall, better than fussing the
* parameters around at runtime, over and over again.
*
* Below, P[i] refers to the package element, M refers to the Match object.
*/
switch (match_op) {
case MATCH_MTR:
/* Always true */
break;
case MATCH_MEQ:
/*
* True if equal: (P[i] == M)
* Change to: (M == P[i])
*/
status =
acpi_ex_do_logical_op(AML_LEQUAL_OP, match_obj, package_obj,
&logical_result);
if (ACPI_FAILURE(status)) {
return (FALSE);
}
break;
case MATCH_MLE:
/*
* True if less than or equal: (P[i] <= M) (P[i] not_greater than M)
* Change to: (M >= P[i]) (M not_less than P[i])
*/
status =
acpi_ex_do_logical_op(AML_LLESS_OP, match_obj, package_obj,
&logical_result);
if (ACPI_FAILURE(status)) {
return (FALSE);
}
logical_result = (u8) ! logical_result;
break;
case MATCH_MLT:
/*
* True if less than: (P[i] < M)
* Change to: (M > P[i])
*/
status =
acpi_ex_do_logical_op(AML_LGREATER_OP, match_obj,
package_obj, &logical_result);
if (ACPI_FAILURE(status)) {
return (FALSE);
}
break;
case MATCH_MGE:
/*
* True if greater than or equal: (P[i] >= M) (P[i] not_less than M)
* Change to: (M <= P[i]) (M not_greater than P[i])
*/
status =
acpi_ex_do_logical_op(AML_LGREATER_OP, match_obj,
package_obj, &logical_result);
if (ACPI_FAILURE(status)) {
return (FALSE);
}
logical_result = (u8) ! logical_result;
break;
case MATCH_MGT:
/*
* True if greater than: (P[i] > M)
* Change to: (M < P[i])
*/
status =
acpi_ex_do_logical_op(AML_LLESS_OP, match_obj, package_obj,
&logical_result);
if (ACPI_FAILURE(status)) {
return (FALSE);
}
break;
default:
/* Undefined */
return (FALSE);
}
return logical_result;
}
/*******************************************************************************
*
* FUNCTION: acpi_ex_opcode_6A_0T_1R
*
* PARAMETERS: walk_state - Current walk state
*
* RETURN: Status
*
* DESCRIPTION: Execute opcode with 6 arguments, no target, and a return value
*
******************************************************************************/
acpi_status acpi_ex_opcode_6A_0T_1R(struct acpi_walk_state * walk_state)
{
union acpi_operand_object **operand = &walk_state->operands[0];
union acpi_operand_object *return_desc = NULL;
acpi_status status = AE_OK;
u64 index;
union acpi_operand_object *this_element;
ACPI_FUNCTION_TRACE_STR(ex_opcode_6A_0T_1R,
acpi_ps_get_opcode_name(walk_state->opcode));
switch (walk_state->opcode) {
case AML_MATCH_OP:
/*
* Match (search_pkg[0], match_op1[1], match_obj1[2],
* match_op2[3], match_obj2[4], start_index[5])
*/
/* Validate both Match Term Operators (MTR, MEQ, etc.) */
if ((operand[1]->integer.value > MAX_MATCH_OPERATOR) ||
(operand[3]->integer.value > MAX_MATCH_OPERATOR)) {
ACPI_ERROR((AE_INFO, "Match operator out of range"));
status = AE_AML_OPERAND_VALUE;
goto cleanup;
}
/* Get the package start_index, validate against the package length */
index = operand[5]->integer.value;
if (index >= operand[0]->package.count) {
ACPI_ERROR((AE_INFO,
"Index (0x%8.8X%8.8X) beyond package end (0x%X)",
ACPI_FORMAT_UINT64(index),
operand[0]->package.count));
status = AE_AML_PACKAGE_LIMIT;
goto cleanup;
}
/* Create an integer for the return value */
/* Default return value is ACPI_UINT64_MAX if no match found */
return_desc = acpi_ut_create_integer_object(ACPI_UINT64_MAX);
if (!return_desc) {
status = AE_NO_MEMORY;
goto cleanup;
}
/*
* Examine each element until a match is found. Both match conditions
* must be satisfied for a match to occur. Within the loop,
* "continue" signifies that the current element does not match
* and the next should be examined.
*
* Upon finding a match, the loop will terminate via "break" at
* the bottom. If it terminates "normally", match_value will be
* ACPI_UINT64_MAX (Ones) (its initial value) indicating that no
* match was found.
*/
for (; index < operand[0]->package.count; index++) {
/* Get the current package element */
this_element = operand[0]->package.elements[index];
/* Treat any uninitialized (NULL) elements as non-matching */
if (!this_element) {
continue;
}
/*
* Both match conditions must be satisfied. Execution of a continue
* (proceed to next iteration of enclosing for loop) signifies a
* non-match.
*/
if (!acpi_ex_do_match((u32) operand[1]->integer.value,
this_element, operand[2])) {
continue;
}
if (!acpi_ex_do_match((u32) operand[3]->integer.value,
this_element, operand[4])) {
continue;
}
/* Match found: Index is the return value */
return_desc->integer.value = index;
break;
}
break;
case AML_LOAD_TABLE_OP:
status = acpi_ex_load_table_op(walk_state, &return_desc);
break;
default:
ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X",
walk_state->opcode));
status = AE_AML_BAD_OPCODE;
goto cleanup;
}
cleanup:
/* Delete return object on error */
if (ACPI_FAILURE(status)) {
acpi_ut_remove_reference(return_desc);
}
/* Save return object on success */
else {
walk_state->result_obj = return_desc;
}
return_ACPI_STATUS(status);
}
| gpl-2.0 |
RenderBroken/OPO-CAF-kernel | arch/cris/arch-v32/drivers/mach-a3/nandflash.c | 8885 | 4205 | /*
* arch/cris/arch-v32/drivers/nandflash.c
*
* Copyright (c) 2007
*
* Derived from drivers/mtd/nand/spia.c
* Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.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/slab.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <arch/memmap.h>
#include <hwregs/reg_map.h>
#include <hwregs/reg_rdwr.h>
#include <hwregs/pio_defs.h>
#include <pinmux.h>
#include <asm/io.h>
#define MANUAL_ALE_CLE_CONTROL 1
#define regf_ALE a0
#define regf_CLE a1
#define regf_NCE ce0_n
#define CLE_BIT 10
#define ALE_BIT 11
#define CE_BIT 12
struct mtd_info_wrapper {
struct mtd_info info;
struct nand_chip chip;
};
/* Bitmask for control pins */
#define PIN_BITMASK ((1 << CE_BIT) | (1 << CLE_BIT) | (1 << ALE_BIT))
static struct mtd_info *crisv32_mtd;
/*
* hardware specific access to control-lines
*/
static void crisv32_hwcontrol(struct mtd_info *mtd, int cmd,
unsigned int ctrl)
{
unsigned long flags;
reg_pio_rw_dout dout;
struct nand_chip *this = mtd->priv;
local_irq_save(flags);
/* control bits change */
if (ctrl & NAND_CTRL_CHANGE) {
dout = REG_RD(pio, regi_pio, rw_dout);
dout.regf_NCE = (ctrl & NAND_NCE) ? 0 : 1;
#if !MANUAL_ALE_CLE_CONTROL
if (ctrl & NAND_ALE) {
/* A0 = ALE high */
this->IO_ADDR_W = (void __iomem *)REG_ADDR(pio,
regi_pio, rw_io_access1);
} else if (ctrl & NAND_CLE) {
/* A1 = CLE high */
this->IO_ADDR_W = (void __iomem *)REG_ADDR(pio,
regi_pio, rw_io_access2);
} else {
/* A1 = CLE and A0 = ALE low */
this->IO_ADDR_W = (void __iomem *)REG_ADDR(pio,
regi_pio, rw_io_access0);
}
#else
dout.regf_CLE = (ctrl & NAND_CLE) ? 1 : 0;
dout.regf_ALE = (ctrl & NAND_ALE) ? 1 : 0;
#endif
REG_WR(pio, regi_pio, rw_dout, dout);
}
/* command to chip */
if (cmd != NAND_CMD_NONE)
writeb(cmd, this->IO_ADDR_W);
local_irq_restore(flags);
}
/*
* read device ready pin
*/
static int crisv32_device_ready(struct mtd_info *mtd)
{
reg_pio_r_din din = REG_RD(pio, regi_pio, r_din);
return din.rdy;
}
/*
* Main initialization routine
*/
struct mtd_info *__init crisv32_nand_flash_probe(void)
{
void __iomem *read_cs;
void __iomem *write_cs;
struct mtd_info_wrapper *wrapper;
struct nand_chip *this;
int err = 0;
reg_pio_rw_man_ctrl man_ctrl = {
.regf_NCE = regk_pio_yes,
#if MANUAL_ALE_CLE_CONTROL
.regf_ALE = regk_pio_yes,
.regf_CLE = regk_pio_yes
#endif
};
reg_pio_rw_oe oe = {
.regf_NCE = regk_pio_yes,
#if MANUAL_ALE_CLE_CONTROL
.regf_ALE = regk_pio_yes,
.regf_CLE = regk_pio_yes
#endif
};
reg_pio_rw_dout dout = { .regf_NCE = 1 };
/* Allocate pio pins to pio */
crisv32_pinmux_alloc_fixed(pinmux_pio);
/* Set up CE, ALE, CLE (ce0_n, a0, a1) for manual control and output */
REG_WR(pio, regi_pio, rw_man_ctrl, man_ctrl);
REG_WR(pio, regi_pio, rw_dout, dout);
REG_WR(pio, regi_pio, rw_oe, oe);
/* Allocate memory for MTD device structure and private data */
wrapper = kzalloc(sizeof(struct mtd_info_wrapper), GFP_KERNEL);
if (!wrapper) {
printk(KERN_ERR "Unable to allocate CRISv32 NAND MTD "
"device structure.\n");
err = -ENOMEM;
return NULL;
}
read_cs = write_cs = (void __iomem *)REG_ADDR(pio, regi_pio,
rw_io_access0);
/* Get pointer to private data */
this = &wrapper->chip;
crisv32_mtd = &wrapper->info;
/* Link the private data with the MTD structure */
crisv32_mtd->priv = this;
/* Set address of NAND IO lines */
this->IO_ADDR_R = read_cs;
this->IO_ADDR_W = write_cs;
this->cmd_ctrl = crisv32_hwcontrol;
this->dev_ready = crisv32_device_ready;
/* 20 us command delay time */
this->chip_delay = 20;
this->ecc.mode = NAND_ECC_SOFT;
/* Enable the following for a flash based bad block table */
/* this->bbt_options = NAND_BBT_USE_FLASH; */
/* Scan to find existence of the device */
if (nand_scan(crisv32_mtd, 1)) {
err = -ENXIO;
goto out_mtd;
}
return crisv32_mtd;
out_mtd:
kfree(wrapper);
return NULL;
}
| gpl-2.0 |
DirtyUnicorns/android_kernel_oppo_msm8974 | arch/powerpc/platforms/83xx/mpc831x_rdb.c | 8885 | 1572 | /*
* arch/powerpc/platforms/83xx/mpc831x_rdb.c
*
* Description: MPC831x RDB board specific routines.
* This file is based on mpc834x_sys.c
* Author: Lo Wlison <r43300@freescale.com>
*
* Copyright (C) Freescale Semiconductor, Inc. 2006. 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.
*/
#include <linux/pci.h>
#include <linux/of_platform.h>
#include <asm/time.h>
#include <asm/ipic.h>
#include <asm/udbg.h>
#include <sysdev/fsl_pci.h>
#include "mpc83xx.h"
/*
* Setup the architecture
*/
static void __init mpc831x_rdb_setup_arch(void)
{
if (ppc_md.progress)
ppc_md.progress("mpc831x_rdb_setup_arch()", 0);
mpc83xx_setup_pci();
mpc831x_usb_cfg();
}
static const char *board[] __initdata = {
"MPC8313ERDB",
"fsl,mpc8315erdb",
NULL
};
/*
* Called very early, MMU is off, device-tree isn't unflattened
*/
static int __init mpc831x_rdb_probe(void)
{
return of_flat_dt_match(of_get_flat_dt_root(), board);
}
machine_device_initcall(mpc831x_rdb, mpc83xx_declare_of_platform_devices);
define_machine(mpc831x_rdb) {
.name = "MPC831x RDB",
.probe = mpc831x_rdb_probe,
.setup_arch = mpc831x_rdb_setup_arch,
.init_IRQ = mpc83xx_ipic_init_IRQ,
.get_irq = ipic_get_irq,
.restart = mpc83xx_restart,
.time_init = mpc83xx_time_init,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
};
| gpl-2.0 |
AndyLavr/Aspire-SW5-012_Kernel_4.8 | arch/sh/boards/mach-se/7780/irq.c | 13237 | 1962 | /*
* linux/arch/sh/boards/se/7780/irq.c
*
* Copyright (C) 2006,2007 Nobuhiro Iwamatsu
*
* Hitachi UL SolutionEngine 7780 Support.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <mach-se/mach/se7780.h>
#define INTC_BASE 0xffd00000
#define INTC_ICR1 (INTC_BASE+0x1c)
/*
* Initialize IRQ setting
*/
void __init init_se7780_IRQ(void)
{
/* enable all interrupt at FPGA */
__raw_writew(0, FPGA_INTMSK1);
/* mask SM501 interrupt */
__raw_writew((__raw_readw(FPGA_INTMSK1) | 0x0002), FPGA_INTMSK1);
/* enable all interrupt at FPGA */
__raw_writew(0, FPGA_INTMSK2);
/* set FPGA INTSEL register */
/* FPGA + 0x06 */
__raw_writew( ((IRQPIN_SM501 << IRQPOS_SM501) |
(IRQPIN_SMC91CX << IRQPOS_SMC91CX)), FPGA_INTSEL1);
/* FPGA + 0x08 */
__raw_writew(((IRQPIN_EXTINT4 << IRQPOS_EXTINT4) |
(IRQPIN_EXTINT3 << IRQPOS_EXTINT3) |
(IRQPIN_EXTINT2 << IRQPOS_EXTINT2) |
(IRQPIN_EXTINT1 << IRQPOS_EXTINT1)), FPGA_INTSEL2);
/* FPGA + 0x0A */
__raw_writew((IRQPIN_PCCPW << IRQPOS_PCCPW), FPGA_INTSEL3);
plat_irq_setup_pins(IRQ_MODE_IRQ); /* install handlers for IRQ0-7 */
/* ICR1: detect low level(for 2ndcut) */
__raw_writel(0xAAAA0000, INTC_ICR1);
/*
* FPGA PCISEL register initialize
*
* CPU || SLOT1 | SLOT2 | S-ATA | USB
* -------------------------------------
* INTA || INTA | INTD | -- | INTB
* -------------------------------------
* INTB || INTB | INTA | -- | INTC
* -------------------------------------
* INTC || INTC | INTB | INTA | --
* -------------------------------------
* INTD || INTD | INTC | -- | INTA
* -------------------------------------
*/
__raw_writew(0x0013, FPGA_PCI_INTSEL1);
__raw_writew(0xE402, FPGA_PCI_INTSEL2);
}
| gpl-2.0 |
Spork-Schivago/gcc-4.9.0-PS3 | gcc/testsuite/gfortran.dg/list_read_4.f90 | 182 | 1552 | ! { dg-do run }
! Test of gfortran list directed read> check delimiters are correctly
! treated. Written in f77 so that g77 will run for comparison.
!
! f , e and i edit reads are terminated separately by read_real.c
!
! PThomas Jan 2005
! BDavis
program list_read_4
integer i(10),l(10),k,j
real x(10),y(10)
! expected results
data y / 1.0,2.0,3.0,-1.0,-1.0,-1.0,4.0,4.0,99.0,99.0 /
data l /1,2,3,-1,-1,-1,4,4,99,99/
! put them in a file
open (10,status="scratch")
write (10,*) " 1.0, 2.0 , 3.0,, 2* , 2*4.0 , 5*99.0"
write (10,*) " 1.0e0, 2.0e0 , 3.0e0,, 2* , 2*4.0e0 , 5*99.0e0"
write (10,*) " 1, 2 , 3,, 2* , 2*4 , 5*99"
write (10,*) " 1, 2 , 3,, 2* , 2*4 , 5*99"
rewind (10)
!
do k = 1,10
x(k) = -1.0
enddo
read (10,*,iostat=ier) x
if (ier.ne.0) call abort
do k = 1,10
if (x(k).ne.y(k)) call abort
x(k) = -1
end do
READ(10,*,iostat=ier) x
if (ier.ne.0) call abort
do k = 1,10
if (x(k).ne.y(k)) call abort
x(k) = -1
end do
READ(10,*,iostat=ier) x
if (ier.ne.0) call abort
do k = 1,10
if (x(k).ne.y(k)) call abort
x(k) = -1
end do
! integer
do k = 1,10
i(k) = -1
end do
READ(10,*,iostat=ier) (i(j),j=1,10)
if (ier.ne.0) call abort
do k = 1,10
if (i(k).ne.y(k)) call abort
i(k) = -1
end do
end
| gpl-2.0 |
greg-pe/platform_kernel_omap | drivers/cpufreq/cpufreq_performance.c | 1974 | 1553 | /*
* linux/drivers/cpufreq/cpufreq_performance.c
*
* Copyright (C) 2002 - 2003 Dominik Brodowski <linux@brodo.de>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/cpufreq.h>
#include <linux/init.h>
#define dprintk(msg...) \
cpufreq_debug_printk(CPUFREQ_DEBUG_GOVERNOR, "performance", msg)
static int cpufreq_governor_performance(struct cpufreq_policy *policy,
unsigned int event)
{
switch (event) {
case CPUFREQ_GOV_START:
case CPUFREQ_GOV_LIMITS:
dprintk("setting to %u kHz because of event %u\n",
policy->max, event);
__cpufreq_driver_target(policy, policy->max,
CPUFREQ_RELATION_H);
break;
default:
break;
}
return 0;
}
#ifdef CONFIG_CPU_FREQ_GOV_PERFORMANCE_MODULE
static
#endif
struct cpufreq_governor cpufreq_gov_performance = {
.name = "performance",
.governor = cpufreq_governor_performance,
.owner = THIS_MODULE,
};
static int __init cpufreq_gov_performance_init(void)
{
return cpufreq_register_governor(&cpufreq_gov_performance);
}
static void __exit cpufreq_gov_performance_exit(void)
{
cpufreq_unregister_governor(&cpufreq_gov_performance);
}
MODULE_AUTHOR("Dominik Brodowski <linux@brodo.de>");
MODULE_DESCRIPTION("CPUfreq policy governor 'performance'");
MODULE_LICENSE("GPL");
fs_initcall(cpufreq_gov_performance_init);
module_exit(cpufreq_gov_performance_exit);
| gpl-2.0 |
voodik/android_kernel_hardkernel_odroidxu3 | drivers/extcon/extcon-adc-jack.c | 1974 | 5069 | /*
* drivers/extcon/extcon-adc-jack.c
*
* Analog Jack extcon driver with ADC-based detection capability.
*
* Copyright (C) 2012 Samsung Electronics
* MyungJoo Ham <myungjoo.ham@samsung.com>
*
* Modified for calling to IIO to get adc by <anish.singh@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/iio/consumer.h>
#include <linux/extcon/extcon-adc-jack.h>
#include <linux/extcon.h>
/**
* struct adc_jack_data - internal data for adc_jack device driver
* @edev - extcon device.
* @cable_names - list of supported cables.
* @num_cables - size of cable_names.
* @adc_conditions - list of adc value conditions.
* @num_conditions - size of adc_conditions.
* @irq - irq number of attach/detach event (0 if not exist).
* @handling_delay - interrupt handler will schedule extcon event
* handling at handling_delay jiffies.
* @handler - extcon event handler called by interrupt handler.
* @chan - iio channel being queried.
*/
struct adc_jack_data {
struct extcon_dev edev;
const char **cable_names;
int num_cables;
struct adc_jack_cond *adc_conditions;
int num_conditions;
int irq;
unsigned long handling_delay; /* in jiffies */
struct delayed_work handler;
struct iio_channel *chan;
};
static void adc_jack_handler(struct work_struct *work)
{
struct adc_jack_data *data = container_of(to_delayed_work(work),
struct adc_jack_data,
handler);
u32 state = 0;
int ret, adc_val;
int i;
ret = iio_read_channel_raw(data->chan, &adc_val);
if (ret < 0) {
dev_err(data->edev.dev, "read channel() error: %d\n", ret);
return;
}
/* Get state from adc value with adc_conditions */
for (i = 0; i < data->num_conditions; i++) {
struct adc_jack_cond *def = &data->adc_conditions[i];
if (!def->state)
break;
if (def->min_adc <= adc_val && def->max_adc >= adc_val) {
state = def->state;
break;
}
}
/* if no def has met, it means state = 0 (no cables attached) */
extcon_set_state(&data->edev, state);
}
static irqreturn_t adc_jack_irq_thread(int irq, void *_data)
{
struct adc_jack_data *data = _data;
schedule_delayed_work(&data->handler, data->handling_delay);
return IRQ_HANDLED;
}
static int adc_jack_probe(struct platform_device *pdev)
{
struct adc_jack_data *data;
struct adc_jack_pdata *pdata = pdev->dev.platform_data;
int i, err = 0;
data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->edev.name = pdata->name;
if (!pdata->cable_names) {
err = -EINVAL;
dev_err(&pdev->dev, "error: cable_names not defined.\n");
goto out;
}
data->edev.supported_cable = pdata->cable_names;
/* Check the length of array and set num_cables */
for (i = 0; data->edev.supported_cable[i]; i++)
;
if (i == 0 || i > SUPPORTED_CABLE_MAX) {
err = -EINVAL;
dev_err(&pdev->dev, "error: pdata->cable_names size = %d\n",
i - 1);
goto out;
}
data->num_cables = i;
if (!pdata->adc_conditions ||
!pdata->adc_conditions[0].state) {
err = -EINVAL;
dev_err(&pdev->dev, "error: adc_conditions not defined.\n");
goto out;
}
data->adc_conditions = pdata->adc_conditions;
/* Check the length of array and set num_conditions */
for (i = 0; data->adc_conditions[i].state; i++)
;
data->num_conditions = i;
data->chan = iio_channel_get(&pdev->dev, pdata->consumer_channel);
if (IS_ERR(data->chan)) {
err = PTR_ERR(data->chan);
goto out;
}
data->handling_delay = msecs_to_jiffies(pdata->handling_delay_ms);
INIT_DEFERRABLE_WORK(&data->handler, adc_jack_handler);
platform_set_drvdata(pdev, data);
err = extcon_dev_register(&data->edev, &pdev->dev);
if (err)
goto out;
data->irq = platform_get_irq(pdev, 0);
if (!data->irq) {
dev_err(&pdev->dev, "platform_get_irq failed\n");
err = -ENODEV;
goto err_irq;
}
err = request_any_context_irq(data->irq, adc_jack_irq_thread,
pdata->irq_flags, pdata->name, data);
if (err < 0) {
dev_err(&pdev->dev, "error: irq %d\n", data->irq);
goto err_irq;
}
return 0;
err_irq:
extcon_dev_unregister(&data->edev);
out:
return err;
}
static int adc_jack_remove(struct platform_device *pdev)
{
struct adc_jack_data *data = platform_get_drvdata(pdev);
free_irq(data->irq, data);
cancel_work_sync(&data->handler.work);
extcon_dev_unregister(&data->edev);
return 0;
}
static struct platform_driver adc_jack_driver = {
.probe = adc_jack_probe,
.remove = adc_jack_remove,
.driver = {
.name = "adc-jack",
.owner = THIS_MODULE,
},
};
module_platform_driver(adc_jack_driver);
MODULE_AUTHOR("MyungJoo Ham <myungjoo.ham@samsung.com>");
MODULE_DESCRIPTION("ADC Jack extcon driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
t0mm13b/CAF-Zte-Blade-Android-MSM-2.6.35 | drivers/cpufreq/cpufreq_performance.c | 1974 | 1553 | /*
* linux/drivers/cpufreq/cpufreq_performance.c
*
* Copyright (C) 2002 - 2003 Dominik Brodowski <linux@brodo.de>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/cpufreq.h>
#include <linux/init.h>
#define dprintk(msg...) \
cpufreq_debug_printk(CPUFREQ_DEBUG_GOVERNOR, "performance", msg)
static int cpufreq_governor_performance(struct cpufreq_policy *policy,
unsigned int event)
{
switch (event) {
case CPUFREQ_GOV_START:
case CPUFREQ_GOV_LIMITS:
dprintk("setting to %u kHz because of event %u\n",
policy->max, event);
__cpufreq_driver_target(policy, policy->max,
CPUFREQ_RELATION_H);
break;
default:
break;
}
return 0;
}
#ifdef CONFIG_CPU_FREQ_GOV_PERFORMANCE_MODULE
static
#endif
struct cpufreq_governor cpufreq_gov_performance = {
.name = "performance",
.governor = cpufreq_governor_performance,
.owner = THIS_MODULE,
};
static int __init cpufreq_gov_performance_init(void)
{
return cpufreq_register_governor(&cpufreq_gov_performance);
}
static void __exit cpufreq_gov_performance_exit(void)
{
cpufreq_unregister_governor(&cpufreq_gov_performance);
}
MODULE_AUTHOR("Dominik Brodowski <linux@brodo.de>");
MODULE_DESCRIPTION("CPUfreq policy governor 'performance'");
MODULE_LICENSE("GPL");
fs_initcall(cpufreq_gov_performance_init);
module_exit(cpufreq_gov_performance_exit);
| gpl-2.0 |
idl3r/P8000-Kernel | arch/ia64/kernel/ptrace.c | 2742 | 57987 | /*
* Kernel support for the ptrace() and syscall tracing interfaces.
*
* Copyright (C) 1999-2005 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
* Copyright (C) 2006 Intel Co
* 2006-08-12 - IA64 Native Utrace implementation support added by
* Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>
*
* Derived from the x86 and Alpha versions.
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/ptrace.h>
#include <linux/user.h>
#include <linux/security.h>
#include <linux/audit.h>
#include <linux/signal.h>
#include <linux/regset.h>
#include <linux/elf.h>
#include <linux/tracehook.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/ptrace_offsets.h>
#include <asm/rse.h>
#include <asm/uaccess.h>
#include <asm/unwind.h>
#ifdef CONFIG_PERFMON
#include <asm/perfmon.h>
#endif
#include "entry.h"
/*
* Bits in the PSR that we allow ptrace() to change:
* be, up, ac, mfl, mfh (the user mask; five bits total)
* db (debug breakpoint fault; one bit)
* id (instruction debug fault disable; one bit)
* dd (data debug fault disable; one bit)
* ri (restart instruction; two bits)
* is (instruction set; one bit)
*/
#define IPSR_MASK (IA64_PSR_UM | IA64_PSR_DB | IA64_PSR_IS \
| IA64_PSR_ID | IA64_PSR_DD | IA64_PSR_RI)
#define MASK(nbits) ((1UL << (nbits)) - 1) /* mask with NBITS bits set */
#define PFM_MASK MASK(38)
#define PTRACE_DEBUG 0
#if PTRACE_DEBUG
# define dprintk(format...) printk(format)
# define inline
#else
# define dprintk(format...)
#endif
/* Return TRUE if PT was created due to kernel-entry via a system-call. */
static inline int
in_syscall (struct pt_regs *pt)
{
return (long) pt->cr_ifs >= 0;
}
/*
* Collect the NaT bits for r1-r31 from scratch_unat and return a NaT
* bitset where bit i is set iff the NaT bit of register i is set.
*/
unsigned long
ia64_get_scratch_nat_bits (struct pt_regs *pt, unsigned long scratch_unat)
{
# define GET_BITS(first, last, unat) \
({ \
unsigned long bit = ia64_unat_pos(&pt->r##first); \
unsigned long nbits = (last - first + 1); \
unsigned long mask = MASK(nbits) << first; \
unsigned long dist; \
if (bit < first) \
dist = 64 + bit - first; \
else \
dist = bit - first; \
ia64_rotr(unat, dist) & mask; \
})
unsigned long val;
/*
* Registers that are stored consecutively in struct pt_regs
* can be handled in parallel. If the register order in
* struct_pt_regs changes, this code MUST be updated.
*/
val = GET_BITS( 1, 1, scratch_unat);
val |= GET_BITS( 2, 3, scratch_unat);
val |= GET_BITS(12, 13, scratch_unat);
val |= GET_BITS(14, 14, scratch_unat);
val |= GET_BITS(15, 15, scratch_unat);
val |= GET_BITS( 8, 11, scratch_unat);
val |= GET_BITS(16, 31, scratch_unat);
return val;
# undef GET_BITS
}
/*
* Set the NaT bits for the scratch registers according to NAT and
* return the resulting unat (assuming the scratch registers are
* stored in PT).
*/
unsigned long
ia64_put_scratch_nat_bits (struct pt_regs *pt, unsigned long nat)
{
# define PUT_BITS(first, last, nat) \
({ \
unsigned long bit = ia64_unat_pos(&pt->r##first); \
unsigned long nbits = (last - first + 1); \
unsigned long mask = MASK(nbits) << first; \
long dist; \
if (bit < first) \
dist = 64 + bit - first; \
else \
dist = bit - first; \
ia64_rotl(nat & mask, dist); \
})
unsigned long scratch_unat;
/*
* Registers that are stored consecutively in struct pt_regs
* can be handled in parallel. If the register order in
* struct_pt_regs changes, this code MUST be updated.
*/
scratch_unat = PUT_BITS( 1, 1, nat);
scratch_unat |= PUT_BITS( 2, 3, nat);
scratch_unat |= PUT_BITS(12, 13, nat);
scratch_unat |= PUT_BITS(14, 14, nat);
scratch_unat |= PUT_BITS(15, 15, nat);
scratch_unat |= PUT_BITS( 8, 11, nat);
scratch_unat |= PUT_BITS(16, 31, nat);
return scratch_unat;
# undef PUT_BITS
}
#define IA64_MLX_TEMPLATE 0x2
#define IA64_MOVL_OPCODE 6
void
ia64_increment_ip (struct pt_regs *regs)
{
unsigned long w0, ri = ia64_psr(regs)->ri + 1;
if (ri > 2) {
ri = 0;
regs->cr_iip += 16;
} else if (ri == 2) {
get_user(w0, (char __user *) regs->cr_iip + 0);
if (((w0 >> 1) & 0xf) == IA64_MLX_TEMPLATE) {
/*
* rfi'ing to slot 2 of an MLX bundle causes
* an illegal operation fault. We don't want
* that to happen...
*/
ri = 0;
regs->cr_iip += 16;
}
}
ia64_psr(regs)->ri = ri;
}
void
ia64_decrement_ip (struct pt_regs *regs)
{
unsigned long w0, ri = ia64_psr(regs)->ri - 1;
if (ia64_psr(regs)->ri == 0) {
regs->cr_iip -= 16;
ri = 2;
get_user(w0, (char __user *) regs->cr_iip + 0);
if (((w0 >> 1) & 0xf) == IA64_MLX_TEMPLATE) {
/*
* rfi'ing to slot 2 of an MLX bundle causes
* an illegal operation fault. We don't want
* that to happen...
*/
ri = 1;
}
}
ia64_psr(regs)->ri = ri;
}
/*
* This routine is used to read an rnat bits that are stored on the
* kernel backing store. Since, in general, the alignment of the user
* and kernel are different, this is not completely trivial. In
* essence, we need to construct the user RNAT based on up to two
* kernel RNAT values and/or the RNAT value saved in the child's
* pt_regs.
*
* user rbs
*
* +--------+ <-- lowest address
* | slot62 |
* +--------+
* | rnat | 0x....1f8
* +--------+
* | slot00 | \
* +--------+ |
* | slot01 | > child_regs->ar_rnat
* +--------+ |
* | slot02 | / kernel rbs
* +--------+ +--------+
* <- child_regs->ar_bspstore | slot61 | <-- krbs
* +- - - - + +--------+
* | slot62 |
* +- - - - + +--------+
* | rnat |
* +- - - - + +--------+
* vrnat | slot00 |
* +- - - - + +--------+
* = =
* +--------+
* | slot00 | \
* +--------+ |
* | slot01 | > child_stack->ar_rnat
* +--------+ |
* | slot02 | /
* +--------+
* <--- child_stack->ar_bspstore
*
* The way to think of this code is as follows: bit 0 in the user rnat
* corresponds to some bit N (0 <= N <= 62) in one of the kernel rnat
* value. The kernel rnat value holding this bit is stored in
* variable rnat0. rnat1 is loaded with the kernel rnat value that
* form the upper bits of the user rnat value.
*
* Boundary cases:
*
* o when reading the rnat "below" the first rnat slot on the kernel
* backing store, rnat0/rnat1 are set to 0 and the low order bits are
* merged in from pt->ar_rnat.
*
* o when reading the rnat "above" the last rnat slot on the kernel
* backing store, rnat0/rnat1 gets its value from sw->ar_rnat.
*/
static unsigned long
get_rnat (struct task_struct *task, struct switch_stack *sw,
unsigned long *krbs, unsigned long *urnat_addr,
unsigned long *urbs_end)
{
unsigned long rnat0 = 0, rnat1 = 0, urnat = 0, *slot0_kaddr;
unsigned long umask = 0, mask, m;
unsigned long *kbsp, *ubspstore, *rnat0_kaddr, *rnat1_kaddr, shift;
long num_regs, nbits;
struct pt_regs *pt;
pt = task_pt_regs(task);
kbsp = (unsigned long *) sw->ar_bspstore;
ubspstore = (unsigned long *) pt->ar_bspstore;
if (urbs_end < urnat_addr)
nbits = ia64_rse_num_regs(urnat_addr - 63, urbs_end);
else
nbits = 63;
mask = MASK(nbits);
/*
* First, figure out which bit number slot 0 in user-land maps
* to in the kernel rnat. Do this by figuring out how many
* register slots we're beyond the user's backingstore and
* then computing the equivalent address in kernel space.
*/
num_regs = ia64_rse_num_regs(ubspstore, urnat_addr + 1);
slot0_kaddr = ia64_rse_skip_regs(krbs, num_regs);
shift = ia64_rse_slot_num(slot0_kaddr);
rnat1_kaddr = ia64_rse_rnat_addr(slot0_kaddr);
rnat0_kaddr = rnat1_kaddr - 64;
if (ubspstore + 63 > urnat_addr) {
/* some bits need to be merged in from pt->ar_rnat */
umask = MASK(ia64_rse_slot_num(ubspstore)) & mask;
urnat = (pt->ar_rnat & umask);
mask &= ~umask;
if (!mask)
return urnat;
}
m = mask << shift;
if (rnat0_kaddr >= kbsp)
rnat0 = sw->ar_rnat;
else if (rnat0_kaddr > krbs)
rnat0 = *rnat0_kaddr;
urnat |= (rnat0 & m) >> shift;
m = mask >> (63 - shift);
if (rnat1_kaddr >= kbsp)
rnat1 = sw->ar_rnat;
else if (rnat1_kaddr > krbs)
rnat1 = *rnat1_kaddr;
urnat |= (rnat1 & m) << (63 - shift);
return urnat;
}
/*
* The reverse of get_rnat.
*/
static void
put_rnat (struct task_struct *task, struct switch_stack *sw,
unsigned long *krbs, unsigned long *urnat_addr, unsigned long urnat,
unsigned long *urbs_end)
{
unsigned long rnat0 = 0, rnat1 = 0, *slot0_kaddr, umask = 0, mask, m;
unsigned long *kbsp, *ubspstore, *rnat0_kaddr, *rnat1_kaddr, shift;
long num_regs, nbits;
struct pt_regs *pt;
unsigned long cfm, *urbs_kargs;
pt = task_pt_regs(task);
kbsp = (unsigned long *) sw->ar_bspstore;
ubspstore = (unsigned long *) pt->ar_bspstore;
urbs_kargs = urbs_end;
if (in_syscall(pt)) {
/*
* If entered via syscall, don't allow user to set rnat bits
* for syscall args.
*/
cfm = pt->cr_ifs;
urbs_kargs = ia64_rse_skip_regs(urbs_end, -(cfm & 0x7f));
}
if (urbs_kargs >= urnat_addr)
nbits = 63;
else {
if ((urnat_addr - 63) >= urbs_kargs)
return;
nbits = ia64_rse_num_regs(urnat_addr - 63, urbs_kargs);
}
mask = MASK(nbits);
/*
* First, figure out which bit number slot 0 in user-land maps
* to in the kernel rnat. Do this by figuring out how many
* register slots we're beyond the user's backingstore and
* then computing the equivalent address in kernel space.
*/
num_regs = ia64_rse_num_regs(ubspstore, urnat_addr + 1);
slot0_kaddr = ia64_rse_skip_regs(krbs, num_regs);
shift = ia64_rse_slot_num(slot0_kaddr);
rnat1_kaddr = ia64_rse_rnat_addr(slot0_kaddr);
rnat0_kaddr = rnat1_kaddr - 64;
if (ubspstore + 63 > urnat_addr) {
/* some bits need to be place in pt->ar_rnat: */
umask = MASK(ia64_rse_slot_num(ubspstore)) & mask;
pt->ar_rnat = (pt->ar_rnat & ~umask) | (urnat & umask);
mask &= ~umask;
if (!mask)
return;
}
/*
* Note: Section 11.1 of the EAS guarantees that bit 63 of an
* rnat slot is ignored. so we don't have to clear it here.
*/
rnat0 = (urnat << shift);
m = mask << shift;
if (rnat0_kaddr >= kbsp)
sw->ar_rnat = (sw->ar_rnat & ~m) | (rnat0 & m);
else if (rnat0_kaddr > krbs)
*rnat0_kaddr = ((*rnat0_kaddr & ~m) | (rnat0 & m));
rnat1 = (urnat >> (63 - shift));
m = mask >> (63 - shift);
if (rnat1_kaddr >= kbsp)
sw->ar_rnat = (sw->ar_rnat & ~m) | (rnat1 & m);
else if (rnat1_kaddr > krbs)
*rnat1_kaddr = ((*rnat1_kaddr & ~m) | (rnat1 & m));
}
static inline int
on_kernel_rbs (unsigned long addr, unsigned long bspstore,
unsigned long urbs_end)
{
unsigned long *rnat_addr = ia64_rse_rnat_addr((unsigned long *)
urbs_end);
return (addr >= bspstore && addr <= (unsigned long) rnat_addr);
}
/*
* Read a word from the user-level backing store of task CHILD. ADDR
* is the user-level address to read the word from, VAL a pointer to
* the return value, and USER_BSP gives the end of the user-level
* backing store (i.e., it's the address that would be in ar.bsp after
* the user executed a "cover" instruction).
*
* This routine takes care of accessing the kernel register backing
* store for those registers that got spilled there. It also takes
* care of calculating the appropriate RNaT collection words.
*/
long
ia64_peek (struct task_struct *child, struct switch_stack *child_stack,
unsigned long user_rbs_end, unsigned long addr, long *val)
{
unsigned long *bspstore, *krbs, regnum, *laddr, *urbs_end, *rnat_addr;
struct pt_regs *child_regs;
size_t copied;
long ret;
urbs_end = (long *) user_rbs_end;
laddr = (unsigned long *) addr;
child_regs = task_pt_regs(child);
bspstore = (unsigned long *) child_regs->ar_bspstore;
krbs = (unsigned long *) child + IA64_RBS_OFFSET/8;
if (on_kernel_rbs(addr, (unsigned long) bspstore,
(unsigned long) urbs_end))
{
/*
* Attempt to read the RBS in an area that's actually
* on the kernel RBS => read the corresponding bits in
* the kernel RBS.
*/
rnat_addr = ia64_rse_rnat_addr(laddr);
ret = get_rnat(child, child_stack, krbs, rnat_addr, urbs_end);
if (laddr == rnat_addr) {
/* return NaT collection word itself */
*val = ret;
return 0;
}
if (((1UL << ia64_rse_slot_num(laddr)) & ret) != 0) {
/*
* It is implementation dependent whether the
* data portion of a NaT value gets saved on a
* st8.spill or RSE spill (e.g., see EAS 2.6,
* 4.4.4.6 Register Spill and Fill). To get
* consistent behavior across all possible
* IA-64 implementations, we return zero in
* this case.
*/
*val = 0;
return 0;
}
if (laddr < urbs_end) {
/*
* The desired word is on the kernel RBS and
* is not a NaT.
*/
regnum = ia64_rse_num_regs(bspstore, laddr);
*val = *ia64_rse_skip_regs(krbs, regnum);
return 0;
}
}
copied = access_process_vm(child, addr, &ret, sizeof(ret), 0);
if (copied != sizeof(ret))
return -EIO;
*val = ret;
return 0;
}
long
ia64_poke (struct task_struct *child, struct switch_stack *child_stack,
unsigned long user_rbs_end, unsigned long addr, long val)
{
unsigned long *bspstore, *krbs, regnum, *laddr;
unsigned long *urbs_end = (long *) user_rbs_end;
struct pt_regs *child_regs;
laddr = (unsigned long *) addr;
child_regs = task_pt_regs(child);
bspstore = (unsigned long *) child_regs->ar_bspstore;
krbs = (unsigned long *) child + IA64_RBS_OFFSET/8;
if (on_kernel_rbs(addr, (unsigned long) bspstore,
(unsigned long) urbs_end))
{
/*
* Attempt to write the RBS in an area that's actually
* on the kernel RBS => write the corresponding bits
* in the kernel RBS.
*/
if (ia64_rse_is_rnat_slot(laddr))
put_rnat(child, child_stack, krbs, laddr, val,
urbs_end);
else {
if (laddr < urbs_end) {
regnum = ia64_rse_num_regs(bspstore, laddr);
*ia64_rse_skip_regs(krbs, regnum) = val;
}
}
} else if (access_process_vm(child, addr, &val, sizeof(val), 1)
!= sizeof(val))
return -EIO;
return 0;
}
/*
* Calculate the address of the end of the user-level register backing
* store. This is the address that would have been stored in ar.bsp
* if the user had executed a "cover" instruction right before
* entering the kernel. If CFMP is not NULL, it is used to return the
* "current frame mask" that was active at the time the kernel was
* entered.
*/
unsigned long
ia64_get_user_rbs_end (struct task_struct *child, struct pt_regs *pt,
unsigned long *cfmp)
{
unsigned long *krbs, *bspstore, cfm = pt->cr_ifs;
long ndirty;
krbs = (unsigned long *) child + IA64_RBS_OFFSET/8;
bspstore = (unsigned long *) pt->ar_bspstore;
ndirty = ia64_rse_num_regs(krbs, krbs + (pt->loadrs >> 19));
if (in_syscall(pt))
ndirty += (cfm & 0x7f);
else
cfm &= ~(1UL << 63); /* clear valid bit */
if (cfmp)
*cfmp = cfm;
return (unsigned long) ia64_rse_skip_regs(bspstore, ndirty);
}
/*
* Synchronize (i.e, write) the RSE backing store living in kernel
* space to the VM of the CHILD task. SW and PT are the pointers to
* the switch_stack and pt_regs structures, respectively.
* USER_RBS_END is the user-level address at which the backing store
* ends.
*/
long
ia64_sync_user_rbs (struct task_struct *child, struct switch_stack *sw,
unsigned long user_rbs_start, unsigned long user_rbs_end)
{
unsigned long addr, val;
long ret;
/* now copy word for word from kernel rbs to user rbs: */
for (addr = user_rbs_start; addr < user_rbs_end; addr += 8) {
ret = ia64_peek(child, sw, user_rbs_end, addr, &val);
if (ret < 0)
return ret;
if (access_process_vm(child, addr, &val, sizeof(val), 1)
!= sizeof(val))
return -EIO;
}
return 0;
}
static long
ia64_sync_kernel_rbs (struct task_struct *child, struct switch_stack *sw,
unsigned long user_rbs_start, unsigned long user_rbs_end)
{
unsigned long addr, val;
long ret;
/* now copy word for word from user rbs to kernel rbs: */
for (addr = user_rbs_start; addr < user_rbs_end; addr += 8) {
if (access_process_vm(child, addr, &val, sizeof(val), 0)
!= sizeof(val))
return -EIO;
ret = ia64_poke(child, sw, user_rbs_end, addr, val);
if (ret < 0)
return ret;
}
return 0;
}
typedef long (*syncfunc_t)(struct task_struct *, struct switch_stack *,
unsigned long, unsigned long);
static void do_sync_rbs(struct unw_frame_info *info, void *arg)
{
struct pt_regs *pt;
unsigned long urbs_end;
syncfunc_t fn = arg;
if (unw_unwind_to_user(info) < 0)
return;
pt = task_pt_regs(info->task);
urbs_end = ia64_get_user_rbs_end(info->task, pt, NULL);
fn(info->task, info->sw, pt->ar_bspstore, urbs_end);
}
/*
* when a thread is stopped (ptraced), debugger might change thread's user
* stack (change memory directly), and we must avoid the RSE stored in kernel
* to override user stack (user space's RSE is newer than kernel's in the
* case). To workaround the issue, we copy kernel RSE to user RSE before the
* task is stopped, so user RSE has updated data. we then copy user RSE to
* kernel after the task is resummed from traced stop and kernel will use the
* newer RSE to return to user. TIF_RESTORE_RSE is the flag to indicate we need
* synchronize user RSE to kernel.
*/
void ia64_ptrace_stop(void)
{
if (test_and_set_tsk_thread_flag(current, TIF_RESTORE_RSE))
return;
set_notify_resume(current);
unw_init_running(do_sync_rbs, ia64_sync_user_rbs);
}
/*
* This is called to read back the register backing store.
*/
void ia64_sync_krbs(void)
{
clear_tsk_thread_flag(current, TIF_RESTORE_RSE);
unw_init_running(do_sync_rbs, ia64_sync_kernel_rbs);
}
/*
* After PTRACE_ATTACH, a thread's register backing store area in user
* space is assumed to contain correct data whenever the thread is
* stopped. arch_ptrace_stop takes care of this on tracing stops.
* But if the child was already stopped for job control when we attach
* to it, then it might not ever get into ptrace_stop by the time we
* want to examine the user memory containing the RBS.
*/
void
ptrace_attach_sync_user_rbs (struct task_struct *child)
{
int stopped = 0;
struct unw_frame_info info;
/*
* If the child is in TASK_STOPPED, we need to change that to
* TASK_TRACED momentarily while we operate on it. This ensures
* that the child won't be woken up and return to user mode while
* we are doing the sync. (It can only be woken up for SIGKILL.)
*/
read_lock(&tasklist_lock);
if (child->sighand) {
spin_lock_irq(&child->sighand->siglock);
if (child->state == TASK_STOPPED &&
!test_and_set_tsk_thread_flag(child, TIF_RESTORE_RSE)) {
set_notify_resume(child);
child->state = TASK_TRACED;
stopped = 1;
}
spin_unlock_irq(&child->sighand->siglock);
}
read_unlock(&tasklist_lock);
if (!stopped)
return;
unw_init_from_blocked_task(&info, child);
do_sync_rbs(&info, ia64_sync_user_rbs);
/*
* Now move the child back into TASK_STOPPED if it should be in a
* job control stop, so that SIGCONT can be used to wake it up.
*/
read_lock(&tasklist_lock);
if (child->sighand) {
spin_lock_irq(&child->sighand->siglock);
if (child->state == TASK_TRACED &&
(child->signal->flags & SIGNAL_STOP_STOPPED)) {
child->state = TASK_STOPPED;
}
spin_unlock_irq(&child->sighand->siglock);
}
read_unlock(&tasklist_lock);
}
/*
* Write f32-f127 back to task->thread.fph if it has been modified.
*/
inline void
ia64_flush_fph (struct task_struct *task)
{
struct ia64_psr *psr = ia64_psr(task_pt_regs(task));
/*
* Prevent migrating this task while
* we're fiddling with the FPU state
*/
preempt_disable();
if (ia64_is_local_fpu_owner(task) && psr->mfh) {
psr->mfh = 0;
task->thread.flags |= IA64_THREAD_FPH_VALID;
ia64_save_fpu(&task->thread.fph[0]);
}
preempt_enable();
}
/*
* Sync the fph state of the task so that it can be manipulated
* through thread.fph. If necessary, f32-f127 are written back to
* thread.fph or, if the fph state hasn't been used before, thread.fph
* is cleared to zeroes. Also, access to f32-f127 is disabled to
* ensure that the task picks up the state from thread.fph when it
* executes again.
*/
void
ia64_sync_fph (struct task_struct *task)
{
struct ia64_psr *psr = ia64_psr(task_pt_regs(task));
ia64_flush_fph(task);
if (!(task->thread.flags & IA64_THREAD_FPH_VALID)) {
task->thread.flags |= IA64_THREAD_FPH_VALID;
memset(&task->thread.fph, 0, sizeof(task->thread.fph));
}
ia64_drop_fpu(task);
psr->dfh = 1;
}
/*
* Change the machine-state of CHILD such that it will return via the normal
* kernel exit-path, rather than the syscall-exit path.
*/
static void
convert_to_non_syscall (struct task_struct *child, struct pt_regs *pt,
unsigned long cfm)
{
struct unw_frame_info info, prev_info;
unsigned long ip, sp, pr;
unw_init_from_blocked_task(&info, child);
while (1) {
prev_info = info;
if (unw_unwind(&info) < 0)
return;
unw_get_sp(&info, &sp);
if ((long)((unsigned long)child + IA64_STK_OFFSET - sp)
< IA64_PT_REGS_SIZE) {
dprintk("ptrace.%s: ran off the top of the kernel "
"stack\n", __func__);
return;
}
if (unw_get_pr (&prev_info, &pr) < 0) {
unw_get_rp(&prev_info, &ip);
dprintk("ptrace.%s: failed to read "
"predicate register (ip=0x%lx)\n",
__func__, ip);
return;
}
if (unw_is_intr_frame(&info)
&& (pr & (1UL << PRED_USER_STACK)))
break;
}
/*
* Note: at the time of this call, the target task is blocked
* in notify_resume_user() and by clearling PRED_LEAVE_SYSCALL
* (aka, "pLvSys") we redirect execution from
* .work_pending_syscall_end to .work_processed_kernel.
*/
unw_get_pr(&prev_info, &pr);
pr &= ~((1UL << PRED_SYSCALL) | (1UL << PRED_LEAVE_SYSCALL));
pr |= (1UL << PRED_NON_SYSCALL);
unw_set_pr(&prev_info, pr);
pt->cr_ifs = (1UL << 63) | cfm;
/*
* Clear the memory that is NOT written on syscall-entry to
* ensure we do not leak kernel-state to user when execution
* resumes.
*/
pt->r2 = 0;
pt->r3 = 0;
pt->r14 = 0;
memset(&pt->r16, 0, 16*8); /* clear r16-r31 */
memset(&pt->f6, 0, 6*16); /* clear f6-f11 */
pt->b7 = 0;
pt->ar_ccv = 0;
pt->ar_csd = 0;
pt->ar_ssd = 0;
}
static int
access_nat_bits (struct task_struct *child, struct pt_regs *pt,
struct unw_frame_info *info,
unsigned long *data, int write_access)
{
unsigned long regnum, nat_bits, scratch_unat, dummy = 0;
char nat = 0;
if (write_access) {
nat_bits = *data;
scratch_unat = ia64_put_scratch_nat_bits(pt, nat_bits);
if (unw_set_ar(info, UNW_AR_UNAT, scratch_unat) < 0) {
dprintk("ptrace: failed to set ar.unat\n");
return -1;
}
for (regnum = 4; regnum <= 7; ++regnum) {
unw_get_gr(info, regnum, &dummy, &nat);
unw_set_gr(info, regnum, dummy,
(nat_bits >> regnum) & 1);
}
} else {
if (unw_get_ar(info, UNW_AR_UNAT, &scratch_unat) < 0) {
dprintk("ptrace: failed to read ar.unat\n");
return -1;
}
nat_bits = ia64_get_scratch_nat_bits(pt, scratch_unat);
for (regnum = 4; regnum <= 7; ++regnum) {
unw_get_gr(info, regnum, &dummy, &nat);
nat_bits |= (nat != 0) << regnum;
}
*data = nat_bits;
}
return 0;
}
static int
access_uarea (struct task_struct *child, unsigned long addr,
unsigned long *data, int write_access);
static long
ptrace_getregs (struct task_struct *child, struct pt_all_user_regs __user *ppr)
{
unsigned long psr, ec, lc, rnat, bsp, cfm, nat_bits, val;
struct unw_frame_info info;
struct ia64_fpreg fpval;
struct switch_stack *sw;
struct pt_regs *pt;
long ret, retval = 0;
char nat = 0;
int i;
if (!access_ok(VERIFY_WRITE, ppr, sizeof(struct pt_all_user_regs)))
return -EIO;
pt = task_pt_regs(child);
sw = (struct switch_stack *) (child->thread.ksp + 16);
unw_init_from_blocked_task(&info, child);
if (unw_unwind_to_user(&info) < 0) {
return -EIO;
}
if (((unsigned long) ppr & 0x7) != 0) {
dprintk("ptrace:unaligned register address %p\n", ppr);
return -EIO;
}
if (access_uarea(child, PT_CR_IPSR, &psr, 0) < 0
|| access_uarea(child, PT_AR_EC, &ec, 0) < 0
|| access_uarea(child, PT_AR_LC, &lc, 0) < 0
|| access_uarea(child, PT_AR_RNAT, &rnat, 0) < 0
|| access_uarea(child, PT_AR_BSP, &bsp, 0) < 0
|| access_uarea(child, PT_CFM, &cfm, 0)
|| access_uarea(child, PT_NAT_BITS, &nat_bits, 0))
return -EIO;
/* control regs */
retval |= __put_user(pt->cr_iip, &ppr->cr_iip);
retval |= __put_user(psr, &ppr->cr_ipsr);
/* app regs */
retval |= __put_user(pt->ar_pfs, &ppr->ar[PT_AUR_PFS]);
retval |= __put_user(pt->ar_rsc, &ppr->ar[PT_AUR_RSC]);
retval |= __put_user(pt->ar_bspstore, &ppr->ar[PT_AUR_BSPSTORE]);
retval |= __put_user(pt->ar_unat, &ppr->ar[PT_AUR_UNAT]);
retval |= __put_user(pt->ar_ccv, &ppr->ar[PT_AUR_CCV]);
retval |= __put_user(pt->ar_fpsr, &ppr->ar[PT_AUR_FPSR]);
retval |= __put_user(ec, &ppr->ar[PT_AUR_EC]);
retval |= __put_user(lc, &ppr->ar[PT_AUR_LC]);
retval |= __put_user(rnat, &ppr->ar[PT_AUR_RNAT]);
retval |= __put_user(bsp, &ppr->ar[PT_AUR_BSP]);
retval |= __put_user(cfm, &ppr->cfm);
/* gr1-gr3 */
retval |= __copy_to_user(&ppr->gr[1], &pt->r1, sizeof(long));
retval |= __copy_to_user(&ppr->gr[2], &pt->r2, sizeof(long) *2);
/* gr4-gr7 */
for (i = 4; i < 8; i++) {
if (unw_access_gr(&info, i, &val, &nat, 0) < 0)
return -EIO;
retval |= __put_user(val, &ppr->gr[i]);
}
/* gr8-gr11 */
retval |= __copy_to_user(&ppr->gr[8], &pt->r8, sizeof(long) * 4);
/* gr12-gr15 */
retval |= __copy_to_user(&ppr->gr[12], &pt->r12, sizeof(long) * 2);
retval |= __copy_to_user(&ppr->gr[14], &pt->r14, sizeof(long));
retval |= __copy_to_user(&ppr->gr[15], &pt->r15, sizeof(long));
/* gr16-gr31 */
retval |= __copy_to_user(&ppr->gr[16], &pt->r16, sizeof(long) * 16);
/* b0 */
retval |= __put_user(pt->b0, &ppr->br[0]);
/* b1-b5 */
for (i = 1; i < 6; i++) {
if (unw_access_br(&info, i, &val, 0) < 0)
return -EIO;
__put_user(val, &ppr->br[i]);
}
/* b6-b7 */
retval |= __put_user(pt->b6, &ppr->br[6]);
retval |= __put_user(pt->b7, &ppr->br[7]);
/* fr2-fr5 */
for (i = 2; i < 6; i++) {
if (unw_get_fr(&info, i, &fpval) < 0)
return -EIO;
retval |= __copy_to_user(&ppr->fr[i], &fpval, sizeof (fpval));
}
/* fr6-fr11 */
retval |= __copy_to_user(&ppr->fr[6], &pt->f6,
sizeof(struct ia64_fpreg) * 6);
/* fp scratch regs(12-15) */
retval |= __copy_to_user(&ppr->fr[12], &sw->f12,
sizeof(struct ia64_fpreg) * 4);
/* fr16-fr31 */
for (i = 16; i < 32; i++) {
if (unw_get_fr(&info, i, &fpval) < 0)
return -EIO;
retval |= __copy_to_user(&ppr->fr[i], &fpval, sizeof (fpval));
}
/* fph */
ia64_flush_fph(child);
retval |= __copy_to_user(&ppr->fr[32], &child->thread.fph,
sizeof(ppr->fr[32]) * 96);
/* preds */
retval |= __put_user(pt->pr, &ppr->pr);
/* nat bits */
retval |= __put_user(nat_bits, &ppr->nat);
ret = retval ? -EIO : 0;
return ret;
}
static long
ptrace_setregs (struct task_struct *child, struct pt_all_user_regs __user *ppr)
{
unsigned long psr, rsc, ec, lc, rnat, bsp, cfm, nat_bits, val = 0;
struct unw_frame_info info;
struct switch_stack *sw;
struct ia64_fpreg fpval;
struct pt_regs *pt;
long ret, retval = 0;
int i;
memset(&fpval, 0, sizeof(fpval));
if (!access_ok(VERIFY_READ, ppr, sizeof(struct pt_all_user_regs)))
return -EIO;
pt = task_pt_regs(child);
sw = (struct switch_stack *) (child->thread.ksp + 16);
unw_init_from_blocked_task(&info, child);
if (unw_unwind_to_user(&info) < 0) {
return -EIO;
}
if (((unsigned long) ppr & 0x7) != 0) {
dprintk("ptrace:unaligned register address %p\n", ppr);
return -EIO;
}
/* control regs */
retval |= __get_user(pt->cr_iip, &ppr->cr_iip);
retval |= __get_user(psr, &ppr->cr_ipsr);
/* app regs */
retval |= __get_user(pt->ar_pfs, &ppr->ar[PT_AUR_PFS]);
retval |= __get_user(rsc, &ppr->ar[PT_AUR_RSC]);
retval |= __get_user(pt->ar_bspstore, &ppr->ar[PT_AUR_BSPSTORE]);
retval |= __get_user(pt->ar_unat, &ppr->ar[PT_AUR_UNAT]);
retval |= __get_user(pt->ar_ccv, &ppr->ar[PT_AUR_CCV]);
retval |= __get_user(pt->ar_fpsr, &ppr->ar[PT_AUR_FPSR]);
retval |= __get_user(ec, &ppr->ar[PT_AUR_EC]);
retval |= __get_user(lc, &ppr->ar[PT_AUR_LC]);
retval |= __get_user(rnat, &ppr->ar[PT_AUR_RNAT]);
retval |= __get_user(bsp, &ppr->ar[PT_AUR_BSP]);
retval |= __get_user(cfm, &ppr->cfm);
/* gr1-gr3 */
retval |= __copy_from_user(&pt->r1, &ppr->gr[1], sizeof(long));
retval |= __copy_from_user(&pt->r2, &ppr->gr[2], sizeof(long) * 2);
/* gr4-gr7 */
for (i = 4; i < 8; i++) {
retval |= __get_user(val, &ppr->gr[i]);
/* NaT bit will be set via PT_NAT_BITS: */
if (unw_set_gr(&info, i, val, 0) < 0)
return -EIO;
}
/* gr8-gr11 */
retval |= __copy_from_user(&pt->r8, &ppr->gr[8], sizeof(long) * 4);
/* gr12-gr15 */
retval |= __copy_from_user(&pt->r12, &ppr->gr[12], sizeof(long) * 2);
retval |= __copy_from_user(&pt->r14, &ppr->gr[14], sizeof(long));
retval |= __copy_from_user(&pt->r15, &ppr->gr[15], sizeof(long));
/* gr16-gr31 */
retval |= __copy_from_user(&pt->r16, &ppr->gr[16], sizeof(long) * 16);
/* b0 */
retval |= __get_user(pt->b0, &ppr->br[0]);
/* b1-b5 */
for (i = 1; i < 6; i++) {
retval |= __get_user(val, &ppr->br[i]);
unw_set_br(&info, i, val);
}
/* b6-b7 */
retval |= __get_user(pt->b6, &ppr->br[6]);
retval |= __get_user(pt->b7, &ppr->br[7]);
/* fr2-fr5 */
for (i = 2; i < 6; i++) {
retval |= __copy_from_user(&fpval, &ppr->fr[i], sizeof(fpval));
if (unw_set_fr(&info, i, fpval) < 0)
return -EIO;
}
/* fr6-fr11 */
retval |= __copy_from_user(&pt->f6, &ppr->fr[6],
sizeof(ppr->fr[6]) * 6);
/* fp scratch regs(12-15) */
retval |= __copy_from_user(&sw->f12, &ppr->fr[12],
sizeof(ppr->fr[12]) * 4);
/* fr16-fr31 */
for (i = 16; i < 32; i++) {
retval |= __copy_from_user(&fpval, &ppr->fr[i],
sizeof(fpval));
if (unw_set_fr(&info, i, fpval) < 0)
return -EIO;
}
/* fph */
ia64_sync_fph(child);
retval |= __copy_from_user(&child->thread.fph, &ppr->fr[32],
sizeof(ppr->fr[32]) * 96);
/* preds */
retval |= __get_user(pt->pr, &ppr->pr);
/* nat bits */
retval |= __get_user(nat_bits, &ppr->nat);
retval |= access_uarea(child, PT_CR_IPSR, &psr, 1);
retval |= access_uarea(child, PT_AR_RSC, &rsc, 1);
retval |= access_uarea(child, PT_AR_EC, &ec, 1);
retval |= access_uarea(child, PT_AR_LC, &lc, 1);
retval |= access_uarea(child, PT_AR_RNAT, &rnat, 1);
retval |= access_uarea(child, PT_AR_BSP, &bsp, 1);
retval |= access_uarea(child, PT_CFM, &cfm, 1);
retval |= access_uarea(child, PT_NAT_BITS, &nat_bits, 1);
ret = retval ? -EIO : 0;
return ret;
}
void
user_enable_single_step (struct task_struct *child)
{
struct ia64_psr *child_psr = ia64_psr(task_pt_regs(child));
set_tsk_thread_flag(child, TIF_SINGLESTEP);
child_psr->ss = 1;
}
void
user_enable_block_step (struct task_struct *child)
{
struct ia64_psr *child_psr = ia64_psr(task_pt_regs(child));
set_tsk_thread_flag(child, TIF_SINGLESTEP);
child_psr->tb = 1;
}
void
user_disable_single_step (struct task_struct *child)
{
struct ia64_psr *child_psr = ia64_psr(task_pt_regs(child));
/* make sure the single step/taken-branch trap bits are not set: */
clear_tsk_thread_flag(child, TIF_SINGLESTEP);
child_psr->ss = 0;
child_psr->tb = 0;
}
/*
* Called by kernel/ptrace.c when detaching..
*
* Make sure the single step bit is not set.
*/
void
ptrace_disable (struct task_struct *child)
{
user_disable_single_step(child);
}
long
arch_ptrace (struct task_struct *child, long request,
unsigned long addr, unsigned long data)
{
switch (request) {
case PTRACE_PEEKTEXT:
case PTRACE_PEEKDATA:
/* read word at location addr */
if (access_process_vm(child, addr, &data, sizeof(data), 0)
!= sizeof(data))
return -EIO;
/* ensure return value is not mistaken for error code */
force_successful_syscall_return();
return data;
/* PTRACE_POKETEXT and PTRACE_POKEDATA is handled
* by the generic ptrace_request().
*/
case PTRACE_PEEKUSR:
/* read the word at addr in the USER area */
if (access_uarea(child, addr, &data, 0) < 0)
return -EIO;
/* ensure return value is not mistaken for error code */
force_successful_syscall_return();
return data;
case PTRACE_POKEUSR:
/* write the word at addr in the USER area */
if (access_uarea(child, addr, &data, 1) < 0)
return -EIO;
return 0;
case PTRACE_OLD_GETSIGINFO:
/* for backwards-compatibility */
return ptrace_request(child, PTRACE_GETSIGINFO, addr, data);
case PTRACE_OLD_SETSIGINFO:
/* for backwards-compatibility */
return ptrace_request(child, PTRACE_SETSIGINFO, addr, data);
case PTRACE_GETREGS:
return ptrace_getregs(child,
(struct pt_all_user_regs __user *) data);
case PTRACE_SETREGS:
return ptrace_setregs(child,
(struct pt_all_user_regs __user *) data);
default:
return ptrace_request(child, request, addr, data);
}
}
/* "asmlinkage" so the input arguments are preserved... */
asmlinkage long
syscall_trace_enter (long arg0, long arg1, long arg2, long arg3,
long arg4, long arg5, long arg6, long arg7,
struct pt_regs regs)
{
if (test_thread_flag(TIF_SYSCALL_TRACE))
if (tracehook_report_syscall_entry(®s))
return -ENOSYS;
/* copy user rbs to kernel rbs */
if (test_thread_flag(TIF_RESTORE_RSE))
ia64_sync_krbs();
audit_syscall_entry(AUDIT_ARCH_IA64, regs.r15, arg0, arg1, arg2, arg3);
return 0;
}
/* "asmlinkage" so the input arguments are preserved... */
asmlinkage void
syscall_trace_leave (long arg0, long arg1, long arg2, long arg3,
long arg4, long arg5, long arg6, long arg7,
struct pt_regs regs)
{
int step;
audit_syscall_exit(®s);
step = test_thread_flag(TIF_SINGLESTEP);
if (step || test_thread_flag(TIF_SYSCALL_TRACE))
tracehook_report_syscall_exit(®s, step);
/* copy user rbs to kernel rbs */
if (test_thread_flag(TIF_RESTORE_RSE))
ia64_sync_krbs();
}
/* Utrace implementation starts here */
struct regset_get {
void *kbuf;
void __user *ubuf;
};
struct regset_set {
const void *kbuf;
const void __user *ubuf;
};
struct regset_getset {
struct task_struct *target;
const struct user_regset *regset;
union {
struct regset_get get;
struct regset_set set;
} u;
unsigned int pos;
unsigned int count;
int ret;
};
static int
access_elf_gpreg(struct task_struct *target, struct unw_frame_info *info,
unsigned long addr, unsigned long *data, int write_access)
{
struct pt_regs *pt;
unsigned long *ptr = NULL;
int ret;
char nat = 0;
pt = task_pt_regs(target);
switch (addr) {
case ELF_GR_OFFSET(1):
ptr = &pt->r1;
break;
case ELF_GR_OFFSET(2):
case ELF_GR_OFFSET(3):
ptr = (void *)&pt->r2 + (addr - ELF_GR_OFFSET(2));
break;
case ELF_GR_OFFSET(4) ... ELF_GR_OFFSET(7):
if (write_access) {
/* read NaT bit first: */
unsigned long dummy;
ret = unw_get_gr(info, addr/8, &dummy, &nat);
if (ret < 0)
return ret;
}
return unw_access_gr(info, addr/8, data, &nat, write_access);
case ELF_GR_OFFSET(8) ... ELF_GR_OFFSET(11):
ptr = (void *)&pt->r8 + addr - ELF_GR_OFFSET(8);
break;
case ELF_GR_OFFSET(12):
case ELF_GR_OFFSET(13):
ptr = (void *)&pt->r12 + addr - ELF_GR_OFFSET(12);
break;
case ELF_GR_OFFSET(14):
ptr = &pt->r14;
break;
case ELF_GR_OFFSET(15):
ptr = &pt->r15;
}
if (write_access)
*ptr = *data;
else
*data = *ptr;
return 0;
}
static int
access_elf_breg(struct task_struct *target, struct unw_frame_info *info,
unsigned long addr, unsigned long *data, int write_access)
{
struct pt_regs *pt;
unsigned long *ptr = NULL;
pt = task_pt_regs(target);
switch (addr) {
case ELF_BR_OFFSET(0):
ptr = &pt->b0;
break;
case ELF_BR_OFFSET(1) ... ELF_BR_OFFSET(5):
return unw_access_br(info, (addr - ELF_BR_OFFSET(0))/8,
data, write_access);
case ELF_BR_OFFSET(6):
ptr = &pt->b6;
break;
case ELF_BR_OFFSET(7):
ptr = &pt->b7;
}
if (write_access)
*ptr = *data;
else
*data = *ptr;
return 0;
}
static int
access_elf_areg(struct task_struct *target, struct unw_frame_info *info,
unsigned long addr, unsigned long *data, int write_access)
{
struct pt_regs *pt;
unsigned long cfm, urbs_end;
unsigned long *ptr = NULL;
pt = task_pt_regs(target);
if (addr >= ELF_AR_RSC_OFFSET && addr <= ELF_AR_SSD_OFFSET) {
switch (addr) {
case ELF_AR_RSC_OFFSET:
/* force PL3 */
if (write_access)
pt->ar_rsc = *data | (3 << 2);
else
*data = pt->ar_rsc;
return 0;
case ELF_AR_BSP_OFFSET:
/*
* By convention, we use PT_AR_BSP to refer to
* the end of the user-level backing store.
* Use ia64_rse_skip_regs(PT_AR_BSP, -CFM.sof)
* to get the real value of ar.bsp at the time
* the kernel was entered.
*
* Furthermore, when changing the contents of
* PT_AR_BSP (or PT_CFM) while the task is
* blocked in a system call, convert the state
* so that the non-system-call exit
* path is used. This ensures that the proper
* state will be picked up when resuming
* execution. However, it *also* means that
* once we write PT_AR_BSP/PT_CFM, it won't be
* possible to modify the syscall arguments of
* the pending system call any longer. This
* shouldn't be an issue because modifying
* PT_AR_BSP/PT_CFM generally implies that
* we're either abandoning the pending system
* call or that we defer it's re-execution
* (e.g., due to GDB doing an inferior
* function call).
*/
urbs_end = ia64_get_user_rbs_end(target, pt, &cfm);
if (write_access) {
if (*data != urbs_end) {
if (in_syscall(pt))
convert_to_non_syscall(target,
pt,
cfm);
/*
* Simulate user-level write
* of ar.bsp:
*/
pt->loadrs = 0;
pt->ar_bspstore = *data;
}
} else
*data = urbs_end;
return 0;
case ELF_AR_BSPSTORE_OFFSET:
ptr = &pt->ar_bspstore;
break;
case ELF_AR_RNAT_OFFSET:
ptr = &pt->ar_rnat;
break;
case ELF_AR_CCV_OFFSET:
ptr = &pt->ar_ccv;
break;
case ELF_AR_UNAT_OFFSET:
ptr = &pt->ar_unat;
break;
case ELF_AR_FPSR_OFFSET:
ptr = &pt->ar_fpsr;
break;
case ELF_AR_PFS_OFFSET:
ptr = &pt->ar_pfs;
break;
case ELF_AR_LC_OFFSET:
return unw_access_ar(info, UNW_AR_LC, data,
write_access);
case ELF_AR_EC_OFFSET:
return unw_access_ar(info, UNW_AR_EC, data,
write_access);
case ELF_AR_CSD_OFFSET:
ptr = &pt->ar_csd;
break;
case ELF_AR_SSD_OFFSET:
ptr = &pt->ar_ssd;
}
} else if (addr >= ELF_CR_IIP_OFFSET && addr <= ELF_CR_IPSR_OFFSET) {
switch (addr) {
case ELF_CR_IIP_OFFSET:
ptr = &pt->cr_iip;
break;
case ELF_CFM_OFFSET:
urbs_end = ia64_get_user_rbs_end(target, pt, &cfm);
if (write_access) {
if (((cfm ^ *data) & PFM_MASK) != 0) {
if (in_syscall(pt))
convert_to_non_syscall(target,
pt,
cfm);
pt->cr_ifs = ((pt->cr_ifs & ~PFM_MASK)
| (*data & PFM_MASK));
}
} else
*data = cfm;
return 0;
case ELF_CR_IPSR_OFFSET:
if (write_access) {
unsigned long tmp = *data;
/* psr.ri==3 is a reserved value: SDM 2:25 */
if ((tmp & IA64_PSR_RI) == IA64_PSR_RI)
tmp &= ~IA64_PSR_RI;
pt->cr_ipsr = ((tmp & IPSR_MASK)
| (pt->cr_ipsr & ~IPSR_MASK));
} else
*data = (pt->cr_ipsr & IPSR_MASK);
return 0;
}
} else if (addr == ELF_NAT_OFFSET)
return access_nat_bits(target, pt, info,
data, write_access);
else if (addr == ELF_PR_OFFSET)
ptr = &pt->pr;
else
return -1;
if (write_access)
*ptr = *data;
else
*data = *ptr;
return 0;
}
static int
access_elf_reg(struct task_struct *target, struct unw_frame_info *info,
unsigned long addr, unsigned long *data, int write_access)
{
if (addr >= ELF_GR_OFFSET(1) && addr <= ELF_GR_OFFSET(15))
return access_elf_gpreg(target, info, addr, data, write_access);
else if (addr >= ELF_BR_OFFSET(0) && addr <= ELF_BR_OFFSET(7))
return access_elf_breg(target, info, addr, data, write_access);
else
return access_elf_areg(target, info, addr, data, write_access);
}
void do_gpregs_get(struct unw_frame_info *info, void *arg)
{
struct pt_regs *pt;
struct regset_getset *dst = arg;
elf_greg_t tmp[16];
unsigned int i, index, min_copy;
if (unw_unwind_to_user(info) < 0)
return;
/*
* coredump format:
* r0-r31
* NaT bits (for r0-r31; bit N == 1 iff rN is a NaT)
* predicate registers (p0-p63)
* b0-b7
* ip cfm user-mask
* ar.rsc ar.bsp ar.bspstore ar.rnat
* ar.ccv ar.unat ar.fpsr ar.pfs ar.lc ar.ec
*/
/* Skip r0 */
if (dst->count > 0 && dst->pos < ELF_GR_OFFSET(1)) {
dst->ret = user_regset_copyout_zero(&dst->pos, &dst->count,
&dst->u.get.kbuf,
&dst->u.get.ubuf,
0, ELF_GR_OFFSET(1));
if (dst->ret || dst->count == 0)
return;
}
/* gr1 - gr15 */
if (dst->count > 0 && dst->pos < ELF_GR_OFFSET(16)) {
index = (dst->pos - ELF_GR_OFFSET(1)) / sizeof(elf_greg_t);
min_copy = ELF_GR_OFFSET(16) > (dst->pos + dst->count) ?
(dst->pos + dst->count) : ELF_GR_OFFSET(16);
for (i = dst->pos; i < min_copy; i += sizeof(elf_greg_t),
index++)
if (access_elf_reg(dst->target, info, i,
&tmp[index], 0) < 0) {
dst->ret = -EIO;
return;
}
dst->ret = user_regset_copyout(&dst->pos, &dst->count,
&dst->u.get.kbuf, &dst->u.get.ubuf, tmp,
ELF_GR_OFFSET(1), ELF_GR_OFFSET(16));
if (dst->ret || dst->count == 0)
return;
}
/* r16-r31 */
if (dst->count > 0 && dst->pos < ELF_NAT_OFFSET) {
pt = task_pt_regs(dst->target);
dst->ret = user_regset_copyout(&dst->pos, &dst->count,
&dst->u.get.kbuf, &dst->u.get.ubuf, &pt->r16,
ELF_GR_OFFSET(16), ELF_NAT_OFFSET);
if (dst->ret || dst->count == 0)
return;
}
/* nat, pr, b0 - b7 */
if (dst->count > 0 && dst->pos < ELF_CR_IIP_OFFSET) {
index = (dst->pos - ELF_NAT_OFFSET) / sizeof(elf_greg_t);
min_copy = ELF_CR_IIP_OFFSET > (dst->pos + dst->count) ?
(dst->pos + dst->count) : ELF_CR_IIP_OFFSET;
for (i = dst->pos; i < min_copy; i += sizeof(elf_greg_t),
index++)
if (access_elf_reg(dst->target, info, i,
&tmp[index], 0) < 0) {
dst->ret = -EIO;
return;
}
dst->ret = user_regset_copyout(&dst->pos, &dst->count,
&dst->u.get.kbuf, &dst->u.get.ubuf, tmp,
ELF_NAT_OFFSET, ELF_CR_IIP_OFFSET);
if (dst->ret || dst->count == 0)
return;
}
/* ip cfm psr ar.rsc ar.bsp ar.bspstore ar.rnat
* ar.ccv ar.unat ar.fpsr ar.pfs ar.lc ar.ec ar.csd ar.ssd
*/
if (dst->count > 0 && dst->pos < (ELF_AR_END_OFFSET)) {
index = (dst->pos - ELF_CR_IIP_OFFSET) / sizeof(elf_greg_t);
min_copy = ELF_AR_END_OFFSET > (dst->pos + dst->count) ?
(dst->pos + dst->count) : ELF_AR_END_OFFSET;
for (i = dst->pos; i < min_copy; i += sizeof(elf_greg_t),
index++)
if (access_elf_reg(dst->target, info, i,
&tmp[index], 0) < 0) {
dst->ret = -EIO;
return;
}
dst->ret = user_regset_copyout(&dst->pos, &dst->count,
&dst->u.get.kbuf, &dst->u.get.ubuf, tmp,
ELF_CR_IIP_OFFSET, ELF_AR_END_OFFSET);
}
}
void do_gpregs_set(struct unw_frame_info *info, void *arg)
{
struct pt_regs *pt;
struct regset_getset *dst = arg;
elf_greg_t tmp[16];
unsigned int i, index;
if (unw_unwind_to_user(info) < 0)
return;
/* Skip r0 */
if (dst->count > 0 && dst->pos < ELF_GR_OFFSET(1)) {
dst->ret = user_regset_copyin_ignore(&dst->pos, &dst->count,
&dst->u.set.kbuf,
&dst->u.set.ubuf,
0, ELF_GR_OFFSET(1));
if (dst->ret || dst->count == 0)
return;
}
/* gr1-gr15 */
if (dst->count > 0 && dst->pos < ELF_GR_OFFSET(16)) {
i = dst->pos;
index = (dst->pos - ELF_GR_OFFSET(1)) / sizeof(elf_greg_t);
dst->ret = user_regset_copyin(&dst->pos, &dst->count,
&dst->u.set.kbuf, &dst->u.set.ubuf, tmp,
ELF_GR_OFFSET(1), ELF_GR_OFFSET(16));
if (dst->ret)
return;
for ( ; i < dst->pos; i += sizeof(elf_greg_t), index++)
if (access_elf_reg(dst->target, info, i,
&tmp[index], 1) < 0) {
dst->ret = -EIO;
return;
}
if (dst->count == 0)
return;
}
/* gr16-gr31 */
if (dst->count > 0 && dst->pos < ELF_NAT_OFFSET) {
pt = task_pt_regs(dst->target);
dst->ret = user_regset_copyin(&dst->pos, &dst->count,
&dst->u.set.kbuf, &dst->u.set.ubuf, &pt->r16,
ELF_GR_OFFSET(16), ELF_NAT_OFFSET);
if (dst->ret || dst->count == 0)
return;
}
/* nat, pr, b0 - b7 */
if (dst->count > 0 && dst->pos < ELF_CR_IIP_OFFSET) {
i = dst->pos;
index = (dst->pos - ELF_NAT_OFFSET) / sizeof(elf_greg_t);
dst->ret = user_regset_copyin(&dst->pos, &dst->count,
&dst->u.set.kbuf, &dst->u.set.ubuf, tmp,
ELF_NAT_OFFSET, ELF_CR_IIP_OFFSET);
if (dst->ret)
return;
for (; i < dst->pos; i += sizeof(elf_greg_t), index++)
if (access_elf_reg(dst->target, info, i,
&tmp[index], 1) < 0) {
dst->ret = -EIO;
return;
}
if (dst->count == 0)
return;
}
/* ip cfm psr ar.rsc ar.bsp ar.bspstore ar.rnat
* ar.ccv ar.unat ar.fpsr ar.pfs ar.lc ar.ec ar.csd ar.ssd
*/
if (dst->count > 0 && dst->pos < (ELF_AR_END_OFFSET)) {
i = dst->pos;
index = (dst->pos - ELF_CR_IIP_OFFSET) / sizeof(elf_greg_t);
dst->ret = user_regset_copyin(&dst->pos, &dst->count,
&dst->u.set.kbuf, &dst->u.set.ubuf, tmp,
ELF_CR_IIP_OFFSET, ELF_AR_END_OFFSET);
if (dst->ret)
return;
for ( ; i < dst->pos; i += sizeof(elf_greg_t), index++)
if (access_elf_reg(dst->target, info, i,
&tmp[index], 1) < 0) {
dst->ret = -EIO;
return;
}
}
}
#define ELF_FP_OFFSET(i) (i * sizeof(elf_fpreg_t))
void do_fpregs_get(struct unw_frame_info *info, void *arg)
{
struct regset_getset *dst = arg;
struct task_struct *task = dst->target;
elf_fpreg_t tmp[30];
int index, min_copy, i;
if (unw_unwind_to_user(info) < 0)
return;
/* Skip pos 0 and 1 */
if (dst->count > 0 && dst->pos < ELF_FP_OFFSET(2)) {
dst->ret = user_regset_copyout_zero(&dst->pos, &dst->count,
&dst->u.get.kbuf,
&dst->u.get.ubuf,
0, ELF_FP_OFFSET(2));
if (dst->count == 0 || dst->ret)
return;
}
/* fr2-fr31 */
if (dst->count > 0 && dst->pos < ELF_FP_OFFSET(32)) {
index = (dst->pos - ELF_FP_OFFSET(2)) / sizeof(elf_fpreg_t);
min_copy = min(((unsigned int)ELF_FP_OFFSET(32)),
dst->pos + dst->count);
for (i = dst->pos; i < min_copy; i += sizeof(elf_fpreg_t),
index++)
if (unw_get_fr(info, i / sizeof(elf_fpreg_t),
&tmp[index])) {
dst->ret = -EIO;
return;
}
dst->ret = user_regset_copyout(&dst->pos, &dst->count,
&dst->u.get.kbuf, &dst->u.get.ubuf, tmp,
ELF_FP_OFFSET(2), ELF_FP_OFFSET(32));
if (dst->count == 0 || dst->ret)
return;
}
/* fph */
if (dst->count > 0) {
ia64_flush_fph(dst->target);
if (task->thread.flags & IA64_THREAD_FPH_VALID)
dst->ret = user_regset_copyout(
&dst->pos, &dst->count,
&dst->u.get.kbuf, &dst->u.get.ubuf,
&dst->target->thread.fph,
ELF_FP_OFFSET(32), -1);
else
/* Zero fill instead. */
dst->ret = user_regset_copyout_zero(
&dst->pos, &dst->count,
&dst->u.get.kbuf, &dst->u.get.ubuf,
ELF_FP_OFFSET(32), -1);
}
}
void do_fpregs_set(struct unw_frame_info *info, void *arg)
{
struct regset_getset *dst = arg;
elf_fpreg_t fpreg, tmp[30];
int index, start, end;
if (unw_unwind_to_user(info) < 0)
return;
/* Skip pos 0 and 1 */
if (dst->count > 0 && dst->pos < ELF_FP_OFFSET(2)) {
dst->ret = user_regset_copyin_ignore(&dst->pos, &dst->count,
&dst->u.set.kbuf,
&dst->u.set.ubuf,
0, ELF_FP_OFFSET(2));
if (dst->count == 0 || dst->ret)
return;
}
/* fr2-fr31 */
if (dst->count > 0 && dst->pos < ELF_FP_OFFSET(32)) {
start = dst->pos;
end = min(((unsigned int)ELF_FP_OFFSET(32)),
dst->pos + dst->count);
dst->ret = user_regset_copyin(&dst->pos, &dst->count,
&dst->u.set.kbuf, &dst->u.set.ubuf, tmp,
ELF_FP_OFFSET(2), ELF_FP_OFFSET(32));
if (dst->ret)
return;
if (start & 0xF) { /* only write high part */
if (unw_get_fr(info, start / sizeof(elf_fpreg_t),
&fpreg)) {
dst->ret = -EIO;
return;
}
tmp[start / sizeof(elf_fpreg_t) - 2].u.bits[0]
= fpreg.u.bits[0];
start &= ~0xFUL;
}
if (end & 0xF) { /* only write low part */
if (unw_get_fr(info, end / sizeof(elf_fpreg_t),
&fpreg)) {
dst->ret = -EIO;
return;
}
tmp[end / sizeof(elf_fpreg_t) - 2].u.bits[1]
= fpreg.u.bits[1];
end = (end + 0xF) & ~0xFUL;
}
for ( ; start < end ; start += sizeof(elf_fpreg_t)) {
index = start / sizeof(elf_fpreg_t);
if (unw_set_fr(info, index, tmp[index - 2])) {
dst->ret = -EIO;
return;
}
}
if (dst->ret || dst->count == 0)
return;
}
/* fph */
if (dst->count > 0 && dst->pos < ELF_FP_OFFSET(128)) {
ia64_sync_fph(dst->target);
dst->ret = user_regset_copyin(&dst->pos, &dst->count,
&dst->u.set.kbuf,
&dst->u.set.ubuf,
&dst->target->thread.fph,
ELF_FP_OFFSET(32), -1);
}
}
static int
do_regset_call(void (*call)(struct unw_frame_info *, void *),
struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
struct regset_getset info = { .target = target, .regset = regset,
.pos = pos, .count = count,
.u.set = { .kbuf = kbuf, .ubuf = ubuf },
.ret = 0 };
if (target == current)
unw_init_running(call, &info);
else {
struct unw_frame_info ufi;
memset(&ufi, 0, sizeof(ufi));
unw_init_from_blocked_task(&ufi, target);
(*call)(&ufi, &info);
}
return info.ret;
}
static int
gpregs_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
return do_regset_call(do_gpregs_get, target, regset, pos, count,
kbuf, ubuf);
}
static int gpregs_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
return do_regset_call(do_gpregs_set, target, regset, pos, count,
kbuf, ubuf);
}
static void do_gpregs_writeback(struct unw_frame_info *info, void *arg)
{
do_sync_rbs(info, ia64_sync_user_rbs);
}
/*
* This is called to write back the register backing store.
* ptrace does this before it stops, so that a tracer reading the user
* memory after the thread stops will get the current register data.
*/
static int
gpregs_writeback(struct task_struct *target,
const struct user_regset *regset,
int now)
{
if (test_and_set_tsk_thread_flag(target, TIF_RESTORE_RSE))
return 0;
set_notify_resume(target);
return do_regset_call(do_gpregs_writeback, target, regset, 0, 0,
NULL, NULL);
}
static int
fpregs_active(struct task_struct *target, const struct user_regset *regset)
{
return (target->thread.flags & IA64_THREAD_FPH_VALID) ? 128 : 32;
}
static int fpregs_get(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
void *kbuf, void __user *ubuf)
{
return do_regset_call(do_fpregs_get, target, regset, pos, count,
kbuf, ubuf);
}
static int fpregs_set(struct task_struct *target,
const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
return do_regset_call(do_fpregs_set, target, regset, pos, count,
kbuf, ubuf);
}
static int
access_uarea(struct task_struct *child, unsigned long addr,
unsigned long *data, int write_access)
{
unsigned int pos = -1; /* an invalid value */
int ret;
unsigned long *ptr, regnum;
if ((addr & 0x7) != 0) {
dprintk("ptrace: unaligned register address 0x%lx\n", addr);
return -1;
}
if ((addr >= PT_NAT_BITS + 8 && addr < PT_F2) ||
(addr >= PT_R7 + 8 && addr < PT_B1) ||
(addr >= PT_AR_LC + 8 && addr < PT_CR_IPSR) ||
(addr >= PT_AR_SSD + 8 && addr < PT_DBR)) {
dprintk("ptrace: rejecting access to register "
"address 0x%lx\n", addr);
return -1;
}
switch (addr) {
case PT_F32 ... (PT_F127 + 15):
pos = addr - PT_F32 + ELF_FP_OFFSET(32);
break;
case PT_F2 ... (PT_F5 + 15):
pos = addr - PT_F2 + ELF_FP_OFFSET(2);
break;
case PT_F10 ... (PT_F31 + 15):
pos = addr - PT_F10 + ELF_FP_OFFSET(10);
break;
case PT_F6 ... (PT_F9 + 15):
pos = addr - PT_F6 + ELF_FP_OFFSET(6);
break;
}
if (pos != -1) {
if (write_access)
ret = fpregs_set(child, NULL, pos,
sizeof(unsigned long), data, NULL);
else
ret = fpregs_get(child, NULL, pos,
sizeof(unsigned long), data, NULL);
if (ret != 0)
return -1;
return 0;
}
switch (addr) {
case PT_NAT_BITS:
pos = ELF_NAT_OFFSET;
break;
case PT_R4 ... PT_R7:
pos = addr - PT_R4 + ELF_GR_OFFSET(4);
break;
case PT_B1 ... PT_B5:
pos = addr - PT_B1 + ELF_BR_OFFSET(1);
break;
case PT_AR_EC:
pos = ELF_AR_EC_OFFSET;
break;
case PT_AR_LC:
pos = ELF_AR_LC_OFFSET;
break;
case PT_CR_IPSR:
pos = ELF_CR_IPSR_OFFSET;
break;
case PT_CR_IIP:
pos = ELF_CR_IIP_OFFSET;
break;
case PT_CFM:
pos = ELF_CFM_OFFSET;
break;
case PT_AR_UNAT:
pos = ELF_AR_UNAT_OFFSET;
break;
case PT_AR_PFS:
pos = ELF_AR_PFS_OFFSET;
break;
case PT_AR_RSC:
pos = ELF_AR_RSC_OFFSET;
break;
case PT_AR_RNAT:
pos = ELF_AR_RNAT_OFFSET;
break;
case PT_AR_BSPSTORE:
pos = ELF_AR_BSPSTORE_OFFSET;
break;
case PT_PR:
pos = ELF_PR_OFFSET;
break;
case PT_B6:
pos = ELF_BR_OFFSET(6);
break;
case PT_AR_BSP:
pos = ELF_AR_BSP_OFFSET;
break;
case PT_R1 ... PT_R3:
pos = addr - PT_R1 + ELF_GR_OFFSET(1);
break;
case PT_R12 ... PT_R15:
pos = addr - PT_R12 + ELF_GR_OFFSET(12);
break;
case PT_R8 ... PT_R11:
pos = addr - PT_R8 + ELF_GR_OFFSET(8);
break;
case PT_R16 ... PT_R31:
pos = addr - PT_R16 + ELF_GR_OFFSET(16);
break;
case PT_AR_CCV:
pos = ELF_AR_CCV_OFFSET;
break;
case PT_AR_FPSR:
pos = ELF_AR_FPSR_OFFSET;
break;
case PT_B0:
pos = ELF_BR_OFFSET(0);
break;
case PT_B7:
pos = ELF_BR_OFFSET(7);
break;
case PT_AR_CSD:
pos = ELF_AR_CSD_OFFSET;
break;
case PT_AR_SSD:
pos = ELF_AR_SSD_OFFSET;
break;
}
if (pos != -1) {
if (write_access)
ret = gpregs_set(child, NULL, pos,
sizeof(unsigned long), data, NULL);
else
ret = gpregs_get(child, NULL, pos,
sizeof(unsigned long), data, NULL);
if (ret != 0)
return -1;
return 0;
}
/* access debug registers */
if (addr >= PT_IBR) {
regnum = (addr - PT_IBR) >> 3;
ptr = &child->thread.ibr[0];
} else {
regnum = (addr - PT_DBR) >> 3;
ptr = &child->thread.dbr[0];
}
if (regnum >= 8) {
dprintk("ptrace: rejecting access to register "
"address 0x%lx\n", addr);
return -1;
}
#ifdef CONFIG_PERFMON
/*
* Check if debug registers are used by perfmon. This
* test must be done once we know that we can do the
* operation, i.e. the arguments are all valid, but
* before we start modifying the state.
*
* Perfmon needs to keep a count of how many processes
* are trying to modify the debug registers for system
* wide monitoring sessions.
*
* We also include read access here, because they may
* cause the PMU-installed debug register state
* (dbr[], ibr[]) to be reset. The two arrays are also
* used by perfmon, but we do not use
* IA64_THREAD_DBG_VALID. The registers are restored
* by the PMU context switch code.
*/
if (pfm_use_debug_registers(child))
return -1;
#endif
if (!(child->thread.flags & IA64_THREAD_DBG_VALID)) {
child->thread.flags |= IA64_THREAD_DBG_VALID;
memset(child->thread.dbr, 0,
sizeof(child->thread.dbr));
memset(child->thread.ibr, 0,
sizeof(child->thread.ibr));
}
ptr += regnum;
if ((regnum & 1) && write_access) {
/* don't let the user set kernel-level breakpoints: */
*ptr = *data & ~(7UL << 56);
return 0;
}
if (write_access)
*ptr = *data;
else
*data = *ptr;
return 0;
}
static const struct user_regset native_regsets[] = {
{
.core_note_type = NT_PRSTATUS,
.n = ELF_NGREG,
.size = sizeof(elf_greg_t), .align = sizeof(elf_greg_t),
.get = gpregs_get, .set = gpregs_set,
.writeback = gpregs_writeback
},
{
.core_note_type = NT_PRFPREG,
.n = ELF_NFPREG,
.size = sizeof(elf_fpreg_t), .align = sizeof(elf_fpreg_t),
.get = fpregs_get, .set = fpregs_set, .active = fpregs_active
},
};
static const struct user_regset_view user_ia64_view = {
.name = "ia64",
.e_machine = EM_IA_64,
.regsets = native_regsets, .n = ARRAY_SIZE(native_regsets)
};
const struct user_regset_view *task_user_regset_view(struct task_struct *tsk)
{
return &user_ia64_view;
}
struct syscall_get_set_args {
unsigned int i;
unsigned int n;
unsigned long *args;
struct pt_regs *regs;
int rw;
};
static void syscall_get_set_args_cb(struct unw_frame_info *info, void *data)
{
struct syscall_get_set_args *args = data;
struct pt_regs *pt = args->regs;
unsigned long *krbs, cfm, ndirty;
int i, count;
if (unw_unwind_to_user(info) < 0)
return;
cfm = pt->cr_ifs;
krbs = (unsigned long *)info->task + IA64_RBS_OFFSET/8;
ndirty = ia64_rse_num_regs(krbs, krbs + (pt->loadrs >> 19));
count = 0;
if (in_syscall(pt))
count = min_t(int, args->n, cfm & 0x7f);
for (i = 0; i < count; i++) {
if (args->rw)
*ia64_rse_skip_regs(krbs, ndirty + i + args->i) =
args->args[i];
else
args->args[i] = *ia64_rse_skip_regs(krbs,
ndirty + i + args->i);
}
if (!args->rw) {
while (i < args->n) {
args->args[i] = 0;
i++;
}
}
}
void ia64_syscall_get_set_arguments(struct task_struct *task,
struct pt_regs *regs, unsigned int i, unsigned int n,
unsigned long *args, int rw)
{
struct syscall_get_set_args data = {
.i = i,
.n = n,
.args = args,
.regs = regs,
.rw = rw,
};
if (task == current)
unw_init_running(syscall_get_set_args_cb, &data);
else {
struct unw_frame_info ufi;
memset(&ufi, 0, sizeof(ufi));
unw_init_from_blocked_task(&ufi, task);
syscall_get_set_args_cb(&ufi, &data);
}
}
| gpl-2.0 |
loganakamatsu/kernel_asus_grouper | drivers/mmc/host/pxamci.c | 2998 | 21119 | /*
* linux/drivers/mmc/host/pxa.c - PXA MMCI driver
*
* Copyright (C) 2003 Russell King, All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This hardware is really sick:
* - No way to clear interrupts.
* - Have to turn off the clock whenever we touch the device.
* - Doesn't tell you how many data blocks were transferred.
* Yuck!
*
* 1 and 3 byte data transfers not supported
* max block length up to 1023
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/mmc/host.h>
#include <linux/io.h>
#include <linux/regulator/consumer.h>
#include <linux/gpio.h>
#include <linux/gfp.h>
#include <asm/sizes.h>
#include <mach/hardware.h>
#include <mach/dma.h>
#include <mach/mmc.h>
#include "pxamci.h"
#define DRIVER_NAME "pxa2xx-mci"
#define NR_SG 1
#define CLKRT_OFF (~0)
#define mmc_has_26MHz() (cpu_is_pxa300() || cpu_is_pxa310() \
|| cpu_is_pxa935())
struct pxamci_host {
struct mmc_host *mmc;
spinlock_t lock;
struct resource *res;
void __iomem *base;
struct clk *clk;
unsigned long clkrate;
int irq;
int dma;
unsigned int clkrt;
unsigned int cmdat;
unsigned int imask;
unsigned int power_mode;
struct pxamci_platform_data *pdata;
struct mmc_request *mrq;
struct mmc_command *cmd;
struct mmc_data *data;
dma_addr_t sg_dma;
struct pxa_dma_desc *sg_cpu;
unsigned int dma_len;
unsigned int dma_dir;
unsigned int dma_drcmrrx;
unsigned int dma_drcmrtx;
struct regulator *vcc;
};
static inline void pxamci_init_ocr(struct pxamci_host *host)
{
#ifdef CONFIG_REGULATOR
host->vcc = regulator_get(mmc_dev(host->mmc), "vmmc");
if (IS_ERR(host->vcc))
host->vcc = NULL;
else {
host->mmc->ocr_avail = mmc_regulator_get_ocrmask(host->vcc);
if (host->pdata && host->pdata->ocr_mask)
dev_warn(mmc_dev(host->mmc),
"ocr_mask/setpower will not be used\n");
}
#endif
if (host->vcc == NULL) {
/* fall-back to platform data */
host->mmc->ocr_avail = host->pdata ?
host->pdata->ocr_mask :
MMC_VDD_32_33 | MMC_VDD_33_34;
}
}
static inline int pxamci_set_power(struct pxamci_host *host,
unsigned char power_mode,
unsigned int vdd)
{
int on;
if (host->vcc) {
int ret;
if (power_mode == MMC_POWER_UP) {
ret = mmc_regulator_set_ocr(host->mmc, host->vcc, vdd);
if (ret)
return ret;
} else if (power_mode == MMC_POWER_OFF) {
ret = mmc_regulator_set_ocr(host->mmc, host->vcc, 0);
if (ret)
return ret;
}
}
if (!host->vcc && host->pdata &&
gpio_is_valid(host->pdata->gpio_power)) {
on = ((1 << vdd) & host->pdata->ocr_mask);
gpio_set_value(host->pdata->gpio_power,
!!on ^ host->pdata->gpio_power_invert);
}
if (!host->vcc && host->pdata && host->pdata->setpower)
host->pdata->setpower(mmc_dev(host->mmc), vdd);
return 0;
}
static void pxamci_stop_clock(struct pxamci_host *host)
{
if (readl(host->base + MMC_STAT) & STAT_CLK_EN) {
unsigned long timeout = 10000;
unsigned int v;
writel(STOP_CLOCK, host->base + MMC_STRPCL);
do {
v = readl(host->base + MMC_STAT);
if (!(v & STAT_CLK_EN))
break;
udelay(1);
} while (timeout--);
if (v & STAT_CLK_EN)
dev_err(mmc_dev(host->mmc), "unable to stop clock\n");
}
}
static void pxamci_enable_irq(struct pxamci_host *host, unsigned int mask)
{
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
host->imask &= ~mask;
writel(host->imask, host->base + MMC_I_MASK);
spin_unlock_irqrestore(&host->lock, flags);
}
static void pxamci_disable_irq(struct pxamci_host *host, unsigned int mask)
{
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
host->imask |= mask;
writel(host->imask, host->base + MMC_I_MASK);
spin_unlock_irqrestore(&host->lock, flags);
}
static void pxamci_setup_data(struct pxamci_host *host, struct mmc_data *data)
{
unsigned int nob = data->blocks;
unsigned long long clks;
unsigned int timeout;
bool dalgn = 0;
u32 dcmd;
int i;
host->data = data;
if (data->flags & MMC_DATA_STREAM)
nob = 0xffff;
writel(nob, host->base + MMC_NOB);
writel(data->blksz, host->base + MMC_BLKLEN);
clks = (unsigned long long)data->timeout_ns * host->clkrate;
do_div(clks, 1000000000UL);
timeout = (unsigned int)clks + (data->timeout_clks << host->clkrt);
writel((timeout + 255) / 256, host->base + MMC_RDTO);
if (data->flags & MMC_DATA_READ) {
host->dma_dir = DMA_FROM_DEVICE;
dcmd = DCMD_INCTRGADDR | DCMD_FLOWSRC;
DRCMR(host->dma_drcmrtx) = 0;
DRCMR(host->dma_drcmrrx) = host->dma | DRCMR_MAPVLD;
} else {
host->dma_dir = DMA_TO_DEVICE;
dcmd = DCMD_INCSRCADDR | DCMD_FLOWTRG;
DRCMR(host->dma_drcmrrx) = 0;
DRCMR(host->dma_drcmrtx) = host->dma | DRCMR_MAPVLD;
}
dcmd |= DCMD_BURST32 | DCMD_WIDTH1;
host->dma_len = dma_map_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
host->dma_dir);
for (i = 0; i < host->dma_len; i++) {
unsigned int length = sg_dma_len(&data->sg[i]);
host->sg_cpu[i].dcmd = dcmd | length;
if (length & 31 && !(data->flags & MMC_DATA_READ))
host->sg_cpu[i].dcmd |= DCMD_ENDIRQEN;
/* Not aligned to 8-byte boundary? */
if (sg_dma_address(&data->sg[i]) & 0x7)
dalgn = 1;
if (data->flags & MMC_DATA_READ) {
host->sg_cpu[i].dsadr = host->res->start + MMC_RXFIFO;
host->sg_cpu[i].dtadr = sg_dma_address(&data->sg[i]);
} else {
host->sg_cpu[i].dsadr = sg_dma_address(&data->sg[i]);
host->sg_cpu[i].dtadr = host->res->start + MMC_TXFIFO;
}
host->sg_cpu[i].ddadr = host->sg_dma + (i + 1) *
sizeof(struct pxa_dma_desc);
}
host->sg_cpu[host->dma_len - 1].ddadr = DDADR_STOP;
wmb();
/*
* The PXA27x DMA controller encounters overhead when working with
* unaligned (to 8-byte boundaries) data, so switch on byte alignment
* mode only if we have unaligned data.
*/
if (dalgn)
DALGN |= (1 << host->dma);
else
DALGN &= ~(1 << host->dma);
DDADR(host->dma) = host->sg_dma;
/*
* workaround for erratum #91:
* only start DMA now if we are doing a read,
* otherwise we wait until CMD/RESP has finished
* before starting DMA.
*/
if (!cpu_is_pxa27x() || data->flags & MMC_DATA_READ)
DCSR(host->dma) = DCSR_RUN;
}
static void pxamci_start_cmd(struct pxamci_host *host, struct mmc_command *cmd, unsigned int cmdat)
{
WARN_ON(host->cmd != NULL);
host->cmd = cmd;
if (cmd->flags & MMC_RSP_BUSY)
cmdat |= CMDAT_BUSY;
#define RSP_TYPE(x) ((x) & ~(MMC_RSP_BUSY|MMC_RSP_OPCODE))
switch (RSP_TYPE(mmc_resp_type(cmd))) {
case RSP_TYPE(MMC_RSP_R1): /* r1, r1b, r6, r7 */
cmdat |= CMDAT_RESP_SHORT;
break;
case RSP_TYPE(MMC_RSP_R3):
cmdat |= CMDAT_RESP_R3;
break;
case RSP_TYPE(MMC_RSP_R2):
cmdat |= CMDAT_RESP_R2;
break;
default:
break;
}
writel(cmd->opcode, host->base + MMC_CMD);
writel(cmd->arg >> 16, host->base + MMC_ARGH);
writel(cmd->arg & 0xffff, host->base + MMC_ARGL);
writel(cmdat, host->base + MMC_CMDAT);
writel(host->clkrt, host->base + MMC_CLKRT);
writel(START_CLOCK, host->base + MMC_STRPCL);
pxamci_enable_irq(host, END_CMD_RES);
}
static void pxamci_finish_request(struct pxamci_host *host, struct mmc_request *mrq)
{
host->mrq = NULL;
host->cmd = NULL;
host->data = NULL;
mmc_request_done(host->mmc, mrq);
}
static int pxamci_cmd_done(struct pxamci_host *host, unsigned int stat)
{
struct mmc_command *cmd = host->cmd;
int i;
u32 v;
if (!cmd)
return 0;
host->cmd = NULL;
/*
* Did I mention this is Sick. We always need to
* discard the upper 8 bits of the first 16-bit word.
*/
v = readl(host->base + MMC_RES) & 0xffff;
for (i = 0; i < 4; i++) {
u32 w1 = readl(host->base + MMC_RES) & 0xffff;
u32 w2 = readl(host->base + MMC_RES) & 0xffff;
cmd->resp[i] = v << 24 | w1 << 8 | w2 >> 8;
v = w2;
}
if (stat & STAT_TIME_OUT_RESPONSE) {
cmd->error = -ETIMEDOUT;
} else if (stat & STAT_RES_CRC_ERR && cmd->flags & MMC_RSP_CRC) {
/*
* workaround for erratum #42:
* Intel PXA27x Family Processor Specification Update Rev 001
* A bogus CRC error can appear if the msb of a 136 bit
* response is a one.
*/
if (cpu_is_pxa27x() &&
(cmd->flags & MMC_RSP_136 && cmd->resp[0] & 0x80000000))
pr_debug("ignoring CRC from command %d - *risky*\n", cmd->opcode);
else
cmd->error = -EILSEQ;
}
pxamci_disable_irq(host, END_CMD_RES);
if (host->data && !cmd->error) {
pxamci_enable_irq(host, DATA_TRAN_DONE);
/*
* workaround for erratum #91, if doing write
* enable DMA late
*/
if (cpu_is_pxa27x() && host->data->flags & MMC_DATA_WRITE)
DCSR(host->dma) = DCSR_RUN;
} else {
pxamci_finish_request(host, host->mrq);
}
return 1;
}
static int pxamci_data_done(struct pxamci_host *host, unsigned int stat)
{
struct mmc_data *data = host->data;
if (!data)
return 0;
DCSR(host->dma) = 0;
dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len,
host->dma_dir);
if (stat & STAT_READ_TIME_OUT)
data->error = -ETIMEDOUT;
else if (stat & (STAT_CRC_READ_ERROR|STAT_CRC_WRITE_ERROR))
data->error = -EILSEQ;
/*
* There appears to be a hardware design bug here. There seems to
* be no way to find out how much data was transferred to the card.
* This means that if there was an error on any block, we mark all
* data blocks as being in error.
*/
if (!data->error)
data->bytes_xfered = data->blocks * data->blksz;
else
data->bytes_xfered = 0;
pxamci_disable_irq(host, DATA_TRAN_DONE);
host->data = NULL;
if (host->mrq->stop) {
pxamci_stop_clock(host);
pxamci_start_cmd(host, host->mrq->stop, host->cmdat);
} else {
pxamci_finish_request(host, host->mrq);
}
return 1;
}
static irqreturn_t pxamci_irq(int irq, void *devid)
{
struct pxamci_host *host = devid;
unsigned int ireg;
int handled = 0;
ireg = readl(host->base + MMC_I_REG) & ~readl(host->base + MMC_I_MASK);
if (ireg) {
unsigned stat = readl(host->base + MMC_STAT);
pr_debug("PXAMCI: irq %08x stat %08x\n", ireg, stat);
if (ireg & END_CMD_RES)
handled |= pxamci_cmd_done(host, stat);
if (ireg & DATA_TRAN_DONE)
handled |= pxamci_data_done(host, stat);
if (ireg & SDIO_INT) {
mmc_signal_sdio_irq(host->mmc);
handled = 1;
}
}
return IRQ_RETVAL(handled);
}
static void pxamci_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct pxamci_host *host = mmc_priv(mmc);
unsigned int cmdat;
WARN_ON(host->mrq != NULL);
host->mrq = mrq;
pxamci_stop_clock(host);
cmdat = host->cmdat;
host->cmdat &= ~CMDAT_INIT;
if (mrq->data) {
pxamci_setup_data(host, mrq->data);
cmdat &= ~CMDAT_BUSY;
cmdat |= CMDAT_DATAEN | CMDAT_DMAEN;
if (mrq->data->flags & MMC_DATA_WRITE)
cmdat |= CMDAT_WRITE;
if (mrq->data->flags & MMC_DATA_STREAM)
cmdat |= CMDAT_STREAM;
}
pxamci_start_cmd(host, mrq->cmd, cmdat);
}
static int pxamci_get_ro(struct mmc_host *mmc)
{
struct pxamci_host *host = mmc_priv(mmc);
if (host->pdata && gpio_is_valid(host->pdata->gpio_card_ro)) {
if (host->pdata->gpio_card_ro_invert)
return !gpio_get_value(host->pdata->gpio_card_ro);
else
return gpio_get_value(host->pdata->gpio_card_ro);
}
if (host->pdata && host->pdata->get_ro)
return !!host->pdata->get_ro(mmc_dev(mmc));
/*
* Board doesn't support read only detection; let the mmc core
* decide what to do.
*/
return -ENOSYS;
}
static void pxamci_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct pxamci_host *host = mmc_priv(mmc);
if (ios->clock) {
unsigned long rate = host->clkrate;
unsigned int clk = rate / ios->clock;
if (host->clkrt == CLKRT_OFF)
clk_enable(host->clk);
if (ios->clock == 26000000) {
/* to support 26MHz */
host->clkrt = 7;
} else {
/* to handle (19.5MHz, 26MHz) */
if (!clk)
clk = 1;
/*
* clk might result in a lower divisor than we
* desire. check for that condition and adjust
* as appropriate.
*/
if (rate / clk > ios->clock)
clk <<= 1;
host->clkrt = fls(clk) - 1;
}
/*
* we write clkrt on the next command
*/
} else {
pxamci_stop_clock(host);
if (host->clkrt != CLKRT_OFF) {
host->clkrt = CLKRT_OFF;
clk_disable(host->clk);
}
}
if (host->power_mode != ios->power_mode) {
int ret;
host->power_mode = ios->power_mode;
ret = pxamci_set_power(host, ios->power_mode, ios->vdd);
if (ret) {
dev_err(mmc_dev(mmc), "unable to set power\n");
/*
* The .set_ios() function in the mmc_host_ops
* struct return void, and failing to set the
* power should be rare so we print an error and
* return here.
*/
return;
}
if (ios->power_mode == MMC_POWER_ON)
host->cmdat |= CMDAT_INIT;
}
if (ios->bus_width == MMC_BUS_WIDTH_4)
host->cmdat |= CMDAT_SD_4DAT;
else
host->cmdat &= ~CMDAT_SD_4DAT;
dev_dbg(mmc_dev(mmc), "PXAMCI: clkrt = %x cmdat = %x\n",
host->clkrt, host->cmdat);
}
static void pxamci_enable_sdio_irq(struct mmc_host *host, int enable)
{
struct pxamci_host *pxa_host = mmc_priv(host);
if (enable)
pxamci_enable_irq(pxa_host, SDIO_INT);
else
pxamci_disable_irq(pxa_host, SDIO_INT);
}
static const struct mmc_host_ops pxamci_ops = {
.request = pxamci_request,
.get_ro = pxamci_get_ro,
.set_ios = pxamci_set_ios,
.enable_sdio_irq = pxamci_enable_sdio_irq,
};
static void pxamci_dma_irq(int dma, void *devid)
{
struct pxamci_host *host = devid;
int dcsr = DCSR(dma);
DCSR(dma) = dcsr & ~DCSR_STOPIRQEN;
if (dcsr & DCSR_ENDINTR) {
writel(BUF_PART_FULL, host->base + MMC_PRTBUF);
} else {
printk(KERN_ERR "%s: DMA error on channel %d (DCSR=%#x)\n",
mmc_hostname(host->mmc), dma, dcsr);
host->data->error = -EIO;
pxamci_data_done(host, 0);
}
}
static irqreturn_t pxamci_detect_irq(int irq, void *devid)
{
struct pxamci_host *host = mmc_priv(devid);
mmc_detect_change(devid, msecs_to_jiffies(host->pdata->detect_delay_ms));
return IRQ_HANDLED;
}
static int pxamci_probe(struct platform_device *pdev)
{
struct mmc_host *mmc;
struct pxamci_host *host = NULL;
struct resource *r, *dmarx, *dmatx;
int ret, irq, gpio_cd = -1, gpio_ro = -1, gpio_power = -1;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
irq = platform_get_irq(pdev, 0);
if (!r || irq < 0)
return -ENXIO;
r = request_mem_region(r->start, SZ_4K, DRIVER_NAME);
if (!r)
return -EBUSY;
mmc = mmc_alloc_host(sizeof(struct pxamci_host), &pdev->dev);
if (!mmc) {
ret = -ENOMEM;
goto out;
}
mmc->ops = &pxamci_ops;
/*
* We can do SG-DMA, but we don't because we never know how much
* data we successfully wrote to the card.
*/
mmc->max_segs = NR_SG;
/*
* Our hardware DMA can handle a maximum of one page per SG entry.
*/
mmc->max_seg_size = PAGE_SIZE;
/*
* Block length register is only 10 bits before PXA27x.
*/
mmc->max_blk_size = cpu_is_pxa25x() ? 1023 : 2048;
/*
* Block count register is 16 bits.
*/
mmc->max_blk_count = 65535;
host = mmc_priv(mmc);
host->mmc = mmc;
host->dma = -1;
host->pdata = pdev->dev.platform_data;
host->clkrt = CLKRT_OFF;
host->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(host->clk)) {
ret = PTR_ERR(host->clk);
host->clk = NULL;
goto out;
}
host->clkrate = clk_get_rate(host->clk);
/*
* Calculate minimum clock rate, rounding up.
*/
mmc->f_min = (host->clkrate + 63) / 64;
mmc->f_max = (mmc_has_26MHz()) ? 26000000 : host->clkrate;
pxamci_init_ocr(host);
mmc->caps = 0;
host->cmdat = 0;
if (!cpu_is_pxa25x()) {
mmc->caps |= MMC_CAP_4_BIT_DATA | MMC_CAP_SDIO_IRQ;
host->cmdat |= CMDAT_SDIO_INT_EN;
if (mmc_has_26MHz())
mmc->caps |= MMC_CAP_MMC_HIGHSPEED |
MMC_CAP_SD_HIGHSPEED;
}
host->sg_cpu = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &host->sg_dma, GFP_KERNEL);
if (!host->sg_cpu) {
ret = -ENOMEM;
goto out;
}
spin_lock_init(&host->lock);
host->res = r;
host->irq = irq;
host->imask = MMC_I_MASK_ALL;
host->base = ioremap(r->start, SZ_4K);
if (!host->base) {
ret = -ENOMEM;
goto out;
}
/*
* Ensure that the host controller is shut down, and setup
* with our defaults.
*/
pxamci_stop_clock(host);
writel(0, host->base + MMC_SPI);
writel(64, host->base + MMC_RESTO);
writel(host->imask, host->base + MMC_I_MASK);
host->dma = pxa_request_dma(DRIVER_NAME, DMA_PRIO_LOW,
pxamci_dma_irq, host);
if (host->dma < 0) {
ret = -EBUSY;
goto out;
}
ret = request_irq(host->irq, pxamci_irq, 0, DRIVER_NAME, host);
if (ret)
goto out;
platform_set_drvdata(pdev, mmc);
dmarx = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!dmarx) {
ret = -ENXIO;
goto out;
}
host->dma_drcmrrx = dmarx->start;
dmatx = platform_get_resource(pdev, IORESOURCE_DMA, 1);
if (!dmatx) {
ret = -ENXIO;
goto out;
}
host->dma_drcmrtx = dmatx->start;
if (host->pdata) {
gpio_cd = host->pdata->gpio_card_detect;
gpio_ro = host->pdata->gpio_card_ro;
gpio_power = host->pdata->gpio_power;
}
if (gpio_is_valid(gpio_power)) {
ret = gpio_request(gpio_power, "mmc card power");
if (ret) {
dev_err(&pdev->dev, "Failed requesting gpio_power %d\n", gpio_power);
goto out;
}
gpio_direction_output(gpio_power,
host->pdata->gpio_power_invert);
}
if (gpio_is_valid(gpio_ro)) {
ret = gpio_request(gpio_ro, "mmc card read only");
if (ret) {
dev_err(&pdev->dev, "Failed requesting gpio_ro %d\n", gpio_ro);
goto err_gpio_ro;
}
gpio_direction_input(gpio_ro);
}
if (gpio_is_valid(gpio_cd)) {
ret = gpio_request(gpio_cd, "mmc card detect");
if (ret) {
dev_err(&pdev->dev, "Failed requesting gpio_cd %d\n", gpio_cd);
goto err_gpio_cd;
}
gpio_direction_input(gpio_cd);
ret = request_irq(gpio_to_irq(gpio_cd), pxamci_detect_irq,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
"mmc card detect", mmc);
if (ret) {
dev_err(&pdev->dev, "failed to request card detect IRQ\n");
goto err_request_irq;
}
}
if (host->pdata && host->pdata->init)
host->pdata->init(&pdev->dev, pxamci_detect_irq, mmc);
if (gpio_is_valid(gpio_power) && host->pdata->setpower)
dev_warn(&pdev->dev, "gpio_power and setpower() both defined\n");
if (gpio_is_valid(gpio_ro) && host->pdata->get_ro)
dev_warn(&pdev->dev, "gpio_ro and get_ro() both defined\n");
mmc_add_host(mmc);
return 0;
err_request_irq:
gpio_free(gpio_cd);
err_gpio_cd:
gpio_free(gpio_ro);
err_gpio_ro:
gpio_free(gpio_power);
out:
if (host) {
if (host->dma >= 0)
pxa_free_dma(host->dma);
if (host->base)
iounmap(host->base);
if (host->sg_cpu)
dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma);
if (host->clk)
clk_put(host->clk);
}
if (mmc)
mmc_free_host(mmc);
release_resource(r);
return ret;
}
static int pxamci_remove(struct platform_device *pdev)
{
struct mmc_host *mmc = platform_get_drvdata(pdev);
int gpio_cd = -1, gpio_ro = -1, gpio_power = -1;
platform_set_drvdata(pdev, NULL);
if (mmc) {
struct pxamci_host *host = mmc_priv(mmc);
mmc_remove_host(mmc);
if (host->pdata) {
gpio_cd = host->pdata->gpio_card_detect;
gpio_ro = host->pdata->gpio_card_ro;
gpio_power = host->pdata->gpio_power;
}
if (gpio_is_valid(gpio_cd)) {
free_irq(gpio_to_irq(gpio_cd), mmc);
gpio_free(gpio_cd);
}
if (gpio_is_valid(gpio_ro))
gpio_free(gpio_ro);
if (gpio_is_valid(gpio_power))
gpio_free(gpio_power);
if (host->vcc)
regulator_put(host->vcc);
if (host->pdata && host->pdata->exit)
host->pdata->exit(&pdev->dev, mmc);
pxamci_stop_clock(host);
writel(TXFIFO_WR_REQ|RXFIFO_RD_REQ|CLK_IS_OFF|STOP_CMD|
END_CMD_RES|PRG_DONE|DATA_TRAN_DONE,
host->base + MMC_I_MASK);
DRCMR(host->dma_drcmrrx) = 0;
DRCMR(host->dma_drcmrtx) = 0;
free_irq(host->irq, host);
pxa_free_dma(host->dma);
iounmap(host->base);
dma_free_coherent(&pdev->dev, PAGE_SIZE, host->sg_cpu, host->sg_dma);
clk_put(host->clk);
release_resource(host->res);
mmc_free_host(mmc);
}
return 0;
}
#ifdef CONFIG_PM
static int pxamci_suspend(struct device *dev)
{
struct mmc_host *mmc = dev_get_drvdata(dev);
int ret = 0;
if (mmc)
ret = mmc_suspend_host(mmc);
return ret;
}
static int pxamci_resume(struct device *dev)
{
struct mmc_host *mmc = dev_get_drvdata(dev);
int ret = 0;
if (mmc)
ret = mmc_resume_host(mmc);
return ret;
}
static const struct dev_pm_ops pxamci_pm_ops = {
.suspend = pxamci_suspend,
.resume = pxamci_resume,
};
#endif
static struct platform_driver pxamci_driver = {
.probe = pxamci_probe,
.remove = pxamci_remove,
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &pxamci_pm_ops,
#endif
},
};
static int __init pxamci_init(void)
{
return platform_driver_register(&pxamci_driver);
}
static void __exit pxamci_exit(void)
{
platform_driver_unregister(&pxamci_driver);
}
module_init(pxamci_init);
module_exit(pxamci_exit);
MODULE_DESCRIPTION("PXA Multimedia Card Interface Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:pxa2xx-mci");
| gpl-2.0 |
sktjdgns1189/android_kernel_samsung_SHV-E160S | drivers/hwmon/asc7621.c | 3254 | 35793 | /*
* asc7621.c - Part of lm_sensors, Linux kernel modules for hardware monitoring
* Copyright (c) 2007, 2010 George Joseph <george.joseph@fairview5.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/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>
/* Addresses to scan */
static const unsigned short normal_i2c[] = {
0x2c, 0x2d, 0x2e, I2C_CLIENT_END
};
enum asc7621_type {
asc7621,
asc7621a
};
#define INTERVAL_HIGH (HZ + HZ / 2)
#define INTERVAL_LOW (1 * 60 * HZ)
#define PRI_NONE 0
#define PRI_LOW 1
#define PRI_HIGH 2
#define FIRST_CHIP asc7621
#define LAST_CHIP asc7621a
struct asc7621_chip {
char *name;
enum asc7621_type chip_type;
u8 company_reg;
u8 company_id;
u8 verstep_reg;
u8 verstep_id;
const unsigned short *addresses;
};
static struct asc7621_chip asc7621_chips[] = {
{
.name = "asc7621",
.chip_type = asc7621,
.company_reg = 0x3e,
.company_id = 0x61,
.verstep_reg = 0x3f,
.verstep_id = 0x6c,
.addresses = normal_i2c,
},
{
.name = "asc7621a",
.chip_type = asc7621a,
.company_reg = 0x3e,
.company_id = 0x61,
.verstep_reg = 0x3f,
.verstep_id = 0x6d,
.addresses = normal_i2c,
},
};
/*
* Defines the highest register to be used, not the count.
* The actual count will probably be smaller because of gaps
* in the implementation (unused register locations).
* This define will safely set the array size of both the parameter
* and data arrays.
* This comes from the data sheet register description table.
*/
#define LAST_REGISTER 0xff
struct asc7621_data {
struct i2c_client client;
struct device *class_dev;
struct mutex update_lock;
int valid; /* !=0 if following fields are valid */
unsigned long last_high_reading; /* In jiffies */
unsigned long last_low_reading; /* In jiffies */
/*
* Registers we care about occupy the corresponding index
* in the array. Registers we don't care about are left
* at 0.
*/
u8 reg[LAST_REGISTER + 1];
};
/*
* Macro to get the parent asc7621_param structure
* from a sensor_device_attribute passed into the
* show/store functions.
*/
#define to_asc7621_param(_sda) \
container_of(_sda, struct asc7621_param, sda)
/*
* Each parameter to be retrieved needs an asc7621_param structure
* allocated. It contains the sensor_device_attribute structure
* and the control info needed to retrieve the value from the register map.
*/
struct asc7621_param {
struct sensor_device_attribute sda;
u8 priority;
u8 msb[3];
u8 lsb[3];
u8 mask[3];
u8 shift[3];
};
/*
* This is the map that ultimately indicates whether we'll be
* retrieving a register value or not, and at what frequency.
*/
static u8 asc7621_register_priorities[255];
static struct asc7621_data *asc7621_update_device(struct device *dev);
static inline u8 read_byte(struct i2c_client *client, u8 reg)
{
int res = i2c_smbus_read_byte_data(client, reg);
if (res < 0) {
dev_err(&client->dev,
"Unable to read from register 0x%02x.\n", reg);
return 0;
};
return res & 0xff;
}
static inline int write_byte(struct i2c_client *client, u8 reg, u8 data)
{
int res = i2c_smbus_write_byte_data(client, reg, data);
if (res < 0) {
dev_err(&client->dev,
"Unable to write value 0x%02x to register 0x%02x.\n",
data, reg);
};
return res;
}
/*
* Data Handlers
* Each function handles the formatting, storage
* and retrieval of like parameters.
*/
#define SETUP_SHOW_data_param(d, a) \
struct sensor_device_attribute *sda = to_sensor_dev_attr(a); \
struct asc7621_data *data = asc7621_update_device(d); \
struct asc7621_param *param = to_asc7621_param(sda)
#define SETUP_STORE_data_param(d, a) \
struct sensor_device_attribute *sda = to_sensor_dev_attr(a); \
struct i2c_client *client = to_i2c_client(d); \
struct asc7621_data *data = i2c_get_clientdata(client); \
struct asc7621_param *param = to_asc7621_param(sda)
/*
* u8 is just what it sounds like...an unsigned byte with no
* special formatting.
*/
static ssize_t show_u8(struct device *dev, struct device_attribute *attr,
char *buf)
{
SETUP_SHOW_data_param(dev, attr);
return sprintf(buf, "%u\n", data->reg[param->msb[0]]);
}
static ssize_t store_u8(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
reqval = SENSORS_LIMIT(reqval, 0, 255);
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = reqval;
write_byte(client, param->msb[0], reqval);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Many of the config values occupy only a few bits of a register.
*/
static ssize_t show_bitmask(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
return sprintf(buf, "%u\n",
(data->reg[param->msb[0]] >> param->
shift[0]) & param->mask[0]);
}
static ssize_t store_bitmask(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval;
u8 currval;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
reqval = SENSORS_LIMIT(reqval, 0, param->mask[0]);
reqval = (reqval & param->mask[0]) << param->shift[0];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
reqval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = reqval;
write_byte(client, param->msb[0], reqval);
mutex_unlock(&data->update_lock);
return count;
}
/*
* 16 bit fan rpm values
* reported by the device as the number of 11.111us periods (90khz)
* between full fan rotations. Therefore...
* RPM = (90000 * 60) / register value
*/
static ssize_t show_fan16(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u16 regval;
mutex_lock(&data->update_lock);
regval = (data->reg[param->msb[0]] << 8) | data->reg[param->lsb[0]];
mutex_unlock(&data->update_lock);
return sprintf(buf, "%u\n",
(regval == 0 ? -1 : (regval) ==
0xffff ? 0 : 5400000 / regval));
}
static ssize_t store_fan16(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
/* If a minimum RPM of zero is requested, then we set the register to
0xffff. This value allows the fan to be stopped completely without
generating an alarm. */
reqval =
(reqval <= 0 ? 0xffff : SENSORS_LIMIT(5400000 / reqval, 0, 0xfffe));
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = (reqval >> 8) & 0xff;
data->reg[param->lsb[0]] = reqval & 0xff;
write_byte(client, param->msb[0], data->reg[param->msb[0]]);
write_byte(client, param->lsb[0], data->reg[param->lsb[0]]);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Voltages are scaled in the device so that the nominal voltage
* is 3/4ths of the 0-255 range (i.e. 192).
* If all voltages are 'normal' then all voltage registers will
* read 0xC0.
*
* The data sheet provides us with the 3/4 scale value for each voltage
* which is stored in in_scaling. The sda->index parameter value provides
* the index into in_scaling.
*
* NOTE: The chip expects the first 2 inputs be 2.5 and 2.25 volts
* respectively. That doesn't mean that's what the motherboard provides. :)
*/
static int asc7621_in_scaling[] = {
2500, 2250, 3300, 5000, 12000
};
static ssize_t show_in10(struct device *dev, struct device_attribute *attr,
char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u16 regval;
u8 nr = sda->index;
mutex_lock(&data->update_lock);
regval = (data->reg[param->msb[0]] << 8) | (data->reg[param->lsb[0]]);
mutex_unlock(&data->update_lock);
/* The LSB value is a 2-bit scaling of the MSB's LSbit value. */
regval = (regval >> 6) * asc7621_in_scaling[nr] / (0xc0 << 2);
return sprintf(buf, "%u\n", regval);
}
/* 8 bit voltage values (the mins and maxs) */
static ssize_t show_in8(struct device *dev, struct device_attribute *attr,
char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u8 nr = sda->index;
return sprintf(buf, "%u\n",
((data->reg[param->msb[0]] *
asc7621_in_scaling[nr]) / 0xc0));
}
static ssize_t store_in8(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval;
u8 nr = sda->index;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
reqval = SENSORS_LIMIT(reqval, 0, 0xffff);
reqval = reqval * 0xc0 / asc7621_in_scaling[nr];
reqval = SENSORS_LIMIT(reqval, 0, 0xff);
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = reqval;
write_byte(client, param->msb[0], reqval);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_temp8(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
return sprintf(buf, "%d\n", ((s8) data->reg[param->msb[0]]) * 1000);
}
static ssize_t store_temp8(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval;
s8 temp;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
reqval = SENSORS_LIMIT(reqval, -127000, 127000);
temp = reqval / 1000;
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = temp;
write_byte(client, param->msb[0], temp);
mutex_unlock(&data->update_lock);
return count;
}
/*
* Temperatures that occupy 2 bytes always have the whole
* number of degrees in the MSB with some part of the LSB
* indicating fractional degrees.
*/
/* mmmmmmmm.llxxxxxx */
static ssize_t show_temp10(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u8 msb, lsb;
int temp;
mutex_lock(&data->update_lock);
msb = data->reg[param->msb[0]];
lsb = (data->reg[param->lsb[0]] >> 6) & 0x03;
temp = (((s8) msb) * 1000) + (lsb * 250);
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp);
}
/* mmmmmm.ll */
static ssize_t show_temp62(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u8 regval = data->reg[param->msb[0]];
int temp = ((s8) (regval & 0xfc) * 1000) + ((regval & 0x03) * 250);
return sprintf(buf, "%d\n", temp);
}
static ssize_t store_temp62(struct device *dev,
struct device_attribute *attr, const char *buf,
size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval, i, f;
s8 temp;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
reqval = SENSORS_LIMIT(reqval, -32000, 31750);
i = reqval / 1000;
f = reqval - (i * 1000);
temp = i << 2;
temp |= f / 250;
mutex_lock(&data->update_lock);
data->reg[param->msb[0]] = temp;
write_byte(client, param->msb[0], temp);
mutex_unlock(&data->update_lock);
return count;
}
/*
* The aSC7621 doesn't provide an "auto_point2". Instead, you
* specify the auto_point1 and a range. To keep with the sysfs
* hwmon specs, we synthesize the auto_point_2 from them.
*/
static u32 asc7621_range_map[] = {
2000, 2500, 3330, 4000, 5000, 6670, 8000, 10000,
13330, 16000, 20000, 26670, 32000, 40000, 53330, 80000,
};
static ssize_t show_ap2_temp(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
long auto_point1;
u8 regval;
int temp;
mutex_lock(&data->update_lock);
auto_point1 = ((s8) data->reg[param->msb[1]]) * 1000;
regval =
((data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0]);
temp = auto_point1 + asc7621_range_map[SENSORS_LIMIT(regval, 0, 15)];
mutex_unlock(&data->update_lock);
return sprintf(buf, "%d\n", temp);
}
static ssize_t store_ap2_temp(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval, auto_point1;
int i;
u8 currval, newval = 0;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
mutex_lock(&data->update_lock);
auto_point1 = data->reg[param->msb[1]] * 1000;
reqval = SENSORS_LIMIT(reqval, auto_point1 + 2000, auto_point1 + 80000);
for (i = ARRAY_SIZE(asc7621_range_map) - 1; i >= 0; i--) {
if (reqval >= auto_point1 + asc7621_range_map[i]) {
newval = i;
break;
}
}
newval = (newval & param->mask[0]) << param->shift[0];
currval = read_byte(client, param->msb[0]);
newval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_ac(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u8 config, altbit, regval;
u8 map[] = {
0x01, 0x02, 0x04, 0x1f, 0x00, 0x06, 0x07, 0x10,
0x08, 0x0f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x1f
};
mutex_lock(&data->update_lock);
config = (data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
altbit = (data->reg[param->msb[1]] >> param->shift[1]) & param->mask[1];
regval = config | (altbit << 3);
mutex_unlock(&data->update_lock);
return sprintf(buf, "%u\n", map[SENSORS_LIMIT(regval, 0, 15)]);
}
static ssize_t store_pwm_ac(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_data_param(dev, attr);
unsigned long reqval;
u8 currval, config, altbit, newval;
u16 map[] = {
0x04, 0x00, 0x01, 0xff, 0x02, 0xff, 0x05, 0x06,
0x08, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f,
0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03,
};
if (strict_strtoul(buf, 10, &reqval))
return -EINVAL;
if (reqval > 31)
return -EINVAL;
reqval = map[reqval];
if (reqval == 0xff)
return -EINVAL;
config = reqval & 0x07;
altbit = (reqval >> 3) & 0x01;
config = (config & param->mask[0]) << param->shift[0];
altbit = (altbit & param->mask[1]) << param->shift[1];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
newval = config | (currval & ~(param->mask[0] << param->shift[0]));
newval = altbit | (newval & ~(param->mask[1] << param->shift[1]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t show_pwm_enable(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u8 config, altbit, minoff, val, newval;
mutex_lock(&data->update_lock);
config = (data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
altbit = (data->reg[param->msb[1]] >> param->shift[1]) & param->mask[1];
minoff = (data->reg[param->msb[2]] >> param->shift[2]) & param->mask[2];
mutex_unlock(&data->update_lock);
val = config | (altbit << 3);
newval = 0;
if (val == 3 || val >= 10)
newval = 255;
else if (val == 4)
newval = 0;
else if (val == 7)
newval = 1;
else if (minoff == 1)
newval = 2;
else
newval = 3;
return sprintf(buf, "%u\n", newval);
}
static ssize_t store_pwm_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval;
u8 currval, config, altbit, newval, minoff = 255;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
switch (reqval) {
case 0:
newval = 0x04;
break;
case 1:
newval = 0x07;
break;
case 2:
newval = 0x00;
minoff = 1;
break;
case 3:
newval = 0x00;
minoff = 0;
break;
case 255:
newval = 0x03;
break;
default:
return -EINVAL;
}
config = newval & 0x07;
altbit = (newval >> 3) & 0x01;
mutex_lock(&data->update_lock);
config = (config & param->mask[0]) << param->shift[0];
altbit = (altbit & param->mask[1]) << param->shift[1];
currval = read_byte(client, param->msb[0]);
newval = config | (currval & ~(param->mask[0] << param->shift[0]));
newval = altbit | (newval & ~(param->mask[1] << param->shift[1]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
if (minoff < 255) {
minoff = (minoff & param->mask[2]) << param->shift[2];
currval = read_byte(client, param->msb[2]);
newval =
minoff | (currval & ~(param->mask[2] << param->shift[2]));
data->reg[param->msb[2]] = newval;
write_byte(client, param->msb[2], newval);
}
mutex_unlock(&data->update_lock);
return count;
}
static u32 asc7621_pwm_freq_map[] = {
10, 15, 23, 30, 38, 47, 62, 94,
23000, 24000, 25000, 26000, 27000, 28000, 29000, 30000
};
static ssize_t show_pwm_freq(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u8 regval =
(data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
regval = SENSORS_LIMIT(regval, 0, 15);
return sprintf(buf, "%u\n", asc7621_pwm_freq_map[regval]);
}
static ssize_t store_pwm_freq(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_data_param(dev, attr);
unsigned long reqval;
u8 currval, newval = 255;
int i;
if (strict_strtoul(buf, 10, &reqval))
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(asc7621_pwm_freq_map); i++) {
if (reqval == asc7621_pwm_freq_map[i]) {
newval = i;
break;
}
}
if (newval == 255)
return -EINVAL;
newval = (newval & param->mask[0]) << param->shift[0];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
newval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
static u32 asc7621_pwm_auto_spinup_map[] = {
0, 100, 250, 400, 700, 1000, 2000, 4000
};
static ssize_t show_pwm_ast(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u8 regval =
(data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
regval = SENSORS_LIMIT(regval, 0, 7);
return sprintf(buf, "%u\n", asc7621_pwm_auto_spinup_map[regval]);
}
static ssize_t store_pwm_ast(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval;
u8 currval, newval = 255;
u32 i;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(asc7621_pwm_auto_spinup_map); i++) {
if (reqval == asc7621_pwm_auto_spinup_map[i]) {
newval = i;
break;
}
}
if (newval == 255)
return -EINVAL;
newval = (newval & param->mask[0]) << param->shift[0];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
newval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
static u32 asc7621_temp_smoothing_time_map[] = {
35000, 17600, 11800, 7000, 4400, 3000, 1600, 800
};
static ssize_t show_temp_st(struct device *dev,
struct device_attribute *attr, char *buf)
{
SETUP_SHOW_data_param(dev, attr);
u8 regval =
(data->reg[param->msb[0]] >> param->shift[0]) & param->mask[0];
regval = SENSORS_LIMIT(regval, 0, 7);
return sprintf(buf, "%u\n", asc7621_temp_smoothing_time_map[regval]);
}
static ssize_t store_temp_st(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
SETUP_STORE_data_param(dev, attr);
long reqval;
u8 currval, newval = 255;
u32 i;
if (strict_strtol(buf, 10, &reqval))
return -EINVAL;
for (i = 0; i < ARRAY_SIZE(asc7621_temp_smoothing_time_map); i++) {
if (reqval == asc7621_temp_smoothing_time_map[i]) {
newval = i;
break;
}
}
if (newval == 255)
return -EINVAL;
newval = (newval & param->mask[0]) << param->shift[0];
mutex_lock(&data->update_lock);
currval = read_byte(client, param->msb[0]);
newval |= (currval & ~(param->mask[0] << param->shift[0]));
data->reg[param->msb[0]] = newval;
write_byte(client, param->msb[0], newval);
mutex_unlock(&data->update_lock);
return count;
}
/*
* End of data handlers
*
* These defines do nothing more than make the table easier
* to read when wrapped at column 80.
*/
/*
* Creates a variable length array inititalizer.
* VAA(1,3,5,7) would produce {1,3,5,7}
*/
#define VAA(args...) {args}
#define PREAD(name, n, pri, rm, rl, m, s, r) \
{.sda = SENSOR_ATTR(name, S_IRUGO, show_##r, NULL, n), \
.priority = pri, .msb[0] = rm, .lsb[0] = rl, .mask[0] = m, \
.shift[0] = s,}
#define PWRITE(name, n, pri, rm, rl, m, s, r) \
{.sda = SENSOR_ATTR(name, S_IRUGO | S_IWUSR, show_##r, store_##r, n), \
.priority = pri, .msb[0] = rm, .lsb[0] = rl, .mask[0] = m, \
.shift[0] = s,}
/*
* PWRITEM assumes that the initializers for the .msb, .lsb, .mask and .shift
* were created using the VAA macro.
*/
#define PWRITEM(name, n, pri, rm, rl, m, s, r) \
{.sda = SENSOR_ATTR(name, S_IRUGO | S_IWUSR, show_##r, store_##r, n), \
.priority = pri, .msb = rm, .lsb = rl, .mask = m, .shift = s,}
static struct asc7621_param asc7621_params[] = {
PREAD(in0_input, 0, PRI_HIGH, 0x20, 0x13, 0, 0, in10),
PREAD(in1_input, 1, PRI_HIGH, 0x21, 0x18, 0, 0, in10),
PREAD(in2_input, 2, PRI_HIGH, 0x22, 0x11, 0, 0, in10),
PREAD(in3_input, 3, PRI_HIGH, 0x23, 0x12, 0, 0, in10),
PREAD(in4_input, 4, PRI_HIGH, 0x24, 0x14, 0, 0, in10),
PWRITE(in0_min, 0, PRI_LOW, 0x44, 0, 0, 0, in8),
PWRITE(in1_min, 1, PRI_LOW, 0x46, 0, 0, 0, in8),
PWRITE(in2_min, 2, PRI_LOW, 0x48, 0, 0, 0, in8),
PWRITE(in3_min, 3, PRI_LOW, 0x4a, 0, 0, 0, in8),
PWRITE(in4_min, 4, PRI_LOW, 0x4c, 0, 0, 0, in8),
PWRITE(in0_max, 0, PRI_LOW, 0x45, 0, 0, 0, in8),
PWRITE(in1_max, 1, PRI_LOW, 0x47, 0, 0, 0, in8),
PWRITE(in2_max, 2, PRI_LOW, 0x49, 0, 0, 0, in8),
PWRITE(in3_max, 3, PRI_LOW, 0x4b, 0, 0, 0, in8),
PWRITE(in4_max, 4, PRI_LOW, 0x4d, 0, 0, 0, in8),
PREAD(in0_alarm, 0, PRI_HIGH, 0x41, 0, 0x01, 0, bitmask),
PREAD(in1_alarm, 1, PRI_HIGH, 0x41, 0, 0x01, 1, bitmask),
PREAD(in2_alarm, 2, PRI_HIGH, 0x41, 0, 0x01, 2, bitmask),
PREAD(in3_alarm, 3, PRI_HIGH, 0x41, 0, 0x01, 3, bitmask),
PREAD(in4_alarm, 4, PRI_HIGH, 0x42, 0, 0x01, 0, bitmask),
PREAD(fan1_input, 0, PRI_HIGH, 0x29, 0x28, 0, 0, fan16),
PREAD(fan2_input, 1, PRI_HIGH, 0x2b, 0x2a, 0, 0, fan16),
PREAD(fan3_input, 2, PRI_HIGH, 0x2d, 0x2c, 0, 0, fan16),
PREAD(fan4_input, 3, PRI_HIGH, 0x2f, 0x2e, 0, 0, fan16),
PWRITE(fan1_min, 0, PRI_LOW, 0x55, 0x54, 0, 0, fan16),
PWRITE(fan2_min, 1, PRI_LOW, 0x57, 0x56, 0, 0, fan16),
PWRITE(fan3_min, 2, PRI_LOW, 0x59, 0x58, 0, 0, fan16),
PWRITE(fan4_min, 3, PRI_LOW, 0x5b, 0x5a, 0, 0, fan16),
PREAD(fan1_alarm, 0, PRI_HIGH, 0x42, 0, 0x01, 2, bitmask),
PREAD(fan2_alarm, 1, PRI_HIGH, 0x42, 0, 0x01, 3, bitmask),
PREAD(fan3_alarm, 2, PRI_HIGH, 0x42, 0, 0x01, 4, bitmask),
PREAD(fan4_alarm, 3, PRI_HIGH, 0x42, 0, 0x01, 5, bitmask),
PREAD(temp1_input, 0, PRI_HIGH, 0x25, 0x10, 0, 0, temp10),
PREAD(temp2_input, 1, PRI_HIGH, 0x26, 0x15, 0, 0, temp10),
PREAD(temp3_input, 2, PRI_HIGH, 0x27, 0x16, 0, 0, temp10),
PREAD(temp4_input, 3, PRI_HIGH, 0x33, 0x17, 0, 0, temp10),
PREAD(temp5_input, 4, PRI_HIGH, 0xf7, 0xf6, 0, 0, temp10),
PREAD(temp6_input, 5, PRI_HIGH, 0xf9, 0xf8, 0, 0, temp10),
PREAD(temp7_input, 6, PRI_HIGH, 0xfb, 0xfa, 0, 0, temp10),
PREAD(temp8_input, 7, PRI_HIGH, 0xfd, 0xfc, 0, 0, temp10),
PWRITE(temp1_min, 0, PRI_LOW, 0x4e, 0, 0, 0, temp8),
PWRITE(temp2_min, 1, PRI_LOW, 0x50, 0, 0, 0, temp8),
PWRITE(temp3_min, 2, PRI_LOW, 0x52, 0, 0, 0, temp8),
PWRITE(temp4_min, 3, PRI_LOW, 0x34, 0, 0, 0, temp8),
PWRITE(temp1_max, 0, PRI_LOW, 0x4f, 0, 0, 0, temp8),
PWRITE(temp2_max, 1, PRI_LOW, 0x51, 0, 0, 0, temp8),
PWRITE(temp3_max, 2, PRI_LOW, 0x53, 0, 0, 0, temp8),
PWRITE(temp4_max, 3, PRI_LOW, 0x35, 0, 0, 0, temp8),
PREAD(temp1_alarm, 0, PRI_HIGH, 0x41, 0, 0x01, 4, bitmask),
PREAD(temp2_alarm, 1, PRI_HIGH, 0x41, 0, 0x01, 5, bitmask),
PREAD(temp3_alarm, 2, PRI_HIGH, 0x41, 0, 0x01, 6, bitmask),
PREAD(temp4_alarm, 3, PRI_HIGH, 0x43, 0, 0x01, 0, bitmask),
PWRITE(temp1_source, 0, PRI_LOW, 0x02, 0, 0x07, 4, bitmask),
PWRITE(temp2_source, 1, PRI_LOW, 0x02, 0, 0x07, 0, bitmask),
PWRITE(temp3_source, 2, PRI_LOW, 0x03, 0, 0x07, 4, bitmask),
PWRITE(temp4_source, 3, PRI_LOW, 0x03, 0, 0x07, 0, bitmask),
PWRITE(temp1_smoothing_enable, 0, PRI_LOW, 0x62, 0, 0x01, 3, bitmask),
PWRITE(temp2_smoothing_enable, 1, PRI_LOW, 0x63, 0, 0x01, 7, bitmask),
PWRITE(temp3_smoothing_enable, 2, PRI_LOW, 0x63, 0, 0x01, 3, bitmask),
PWRITE(temp4_smoothing_enable, 3, PRI_LOW, 0x3c, 0, 0x01, 3, bitmask),
PWRITE(temp1_smoothing_time, 0, PRI_LOW, 0x62, 0, 0x07, 0, temp_st),
PWRITE(temp2_smoothing_time, 1, PRI_LOW, 0x63, 0, 0x07, 4, temp_st),
PWRITE(temp3_smoothing_time, 2, PRI_LOW, 0x63, 0, 0x07, 0, temp_st),
PWRITE(temp4_smoothing_time, 3, PRI_LOW, 0x3c, 0, 0x07, 0, temp_st),
PWRITE(temp1_auto_point1_temp_hyst, 0, PRI_LOW, 0x6d, 0, 0x0f, 4,
bitmask),
PWRITE(temp2_auto_point1_temp_hyst, 1, PRI_LOW, 0x6d, 0, 0x0f, 0,
bitmask),
PWRITE(temp3_auto_point1_temp_hyst, 2, PRI_LOW, 0x6e, 0, 0x0f, 4,
bitmask),
PWRITE(temp4_auto_point1_temp_hyst, 3, PRI_LOW, 0x6e, 0, 0x0f, 0,
bitmask),
PREAD(temp1_auto_point2_temp_hyst, 0, PRI_LOW, 0x6d, 0, 0x0f, 4,
bitmask),
PREAD(temp2_auto_point2_temp_hyst, 1, PRI_LOW, 0x6d, 0, 0x0f, 0,
bitmask),
PREAD(temp3_auto_point2_temp_hyst, 2, PRI_LOW, 0x6e, 0, 0x0f, 4,
bitmask),
PREAD(temp4_auto_point2_temp_hyst, 3, PRI_LOW, 0x6e, 0, 0x0f, 0,
bitmask),
PWRITE(temp1_auto_point1_temp, 0, PRI_LOW, 0x67, 0, 0, 0, temp8),
PWRITE(temp2_auto_point1_temp, 1, PRI_LOW, 0x68, 0, 0, 0, temp8),
PWRITE(temp3_auto_point1_temp, 2, PRI_LOW, 0x69, 0, 0, 0, temp8),
PWRITE(temp4_auto_point1_temp, 3, PRI_LOW, 0x3b, 0, 0, 0, temp8),
PWRITEM(temp1_auto_point2_temp, 0, PRI_LOW, VAA(0x5f, 0x67), VAA(0),
VAA(0x0f), VAA(4), ap2_temp),
PWRITEM(temp2_auto_point2_temp, 1, PRI_LOW, VAA(0x60, 0x68), VAA(0),
VAA(0x0f), VAA(4), ap2_temp),
PWRITEM(temp3_auto_point2_temp, 2, PRI_LOW, VAA(0x61, 0x69), VAA(0),
VAA(0x0f), VAA(4), ap2_temp),
PWRITEM(temp4_auto_point2_temp, 3, PRI_LOW, VAA(0x3c, 0x3b), VAA(0),
VAA(0x0f), VAA(4), ap2_temp),
PWRITE(temp1_crit, 0, PRI_LOW, 0x6a, 0, 0, 0, temp8),
PWRITE(temp2_crit, 1, PRI_LOW, 0x6b, 0, 0, 0, temp8),
PWRITE(temp3_crit, 2, PRI_LOW, 0x6c, 0, 0, 0, temp8),
PWRITE(temp4_crit, 3, PRI_LOW, 0x3d, 0, 0, 0, temp8),
PWRITE(temp5_enable, 4, PRI_LOW, 0x0e, 0, 0x01, 0, bitmask),
PWRITE(temp6_enable, 5, PRI_LOW, 0x0e, 0, 0x01, 1, bitmask),
PWRITE(temp7_enable, 6, PRI_LOW, 0x0e, 0, 0x01, 2, bitmask),
PWRITE(temp8_enable, 7, PRI_LOW, 0x0e, 0, 0x01, 3, bitmask),
PWRITE(remote1_offset, 0, PRI_LOW, 0x1c, 0, 0, 0, temp62),
PWRITE(remote2_offset, 1, PRI_LOW, 0x1d, 0, 0, 0, temp62),
PWRITE(pwm1, 0, PRI_HIGH, 0x30, 0, 0, 0, u8),
PWRITE(pwm2, 1, PRI_HIGH, 0x31, 0, 0, 0, u8),
PWRITE(pwm3, 2, PRI_HIGH, 0x32, 0, 0, 0, u8),
PWRITE(pwm1_invert, 0, PRI_LOW, 0x5c, 0, 0x01, 4, bitmask),
PWRITE(pwm2_invert, 1, PRI_LOW, 0x5d, 0, 0x01, 4, bitmask),
PWRITE(pwm3_invert, 2, PRI_LOW, 0x5e, 0, 0x01, 4, bitmask),
PWRITEM(pwm1_enable, 0, PRI_LOW, VAA(0x5c, 0x5c, 0x62), VAA(0, 0, 0),
VAA(0x07, 0x01, 0x01), VAA(5, 3, 5), pwm_enable),
PWRITEM(pwm2_enable, 1, PRI_LOW, VAA(0x5d, 0x5d, 0x62), VAA(0, 0, 0),
VAA(0x07, 0x01, 0x01), VAA(5, 3, 6), pwm_enable),
PWRITEM(pwm3_enable, 2, PRI_LOW, VAA(0x5e, 0x5e, 0x62), VAA(0, 0, 0),
VAA(0x07, 0x01, 0x01), VAA(5, 3, 7), pwm_enable),
PWRITEM(pwm1_auto_channels, 0, PRI_LOW, VAA(0x5c, 0x5c), VAA(0, 0),
VAA(0x07, 0x01), VAA(5, 3), pwm_ac),
PWRITEM(pwm2_auto_channels, 1, PRI_LOW, VAA(0x5d, 0x5d), VAA(0, 0),
VAA(0x07, 0x01), VAA(5, 3), pwm_ac),
PWRITEM(pwm3_auto_channels, 2, PRI_LOW, VAA(0x5e, 0x5e), VAA(0, 0),
VAA(0x07, 0x01), VAA(5, 3), pwm_ac),
PWRITE(pwm1_auto_point1_pwm, 0, PRI_LOW, 0x64, 0, 0, 0, u8),
PWRITE(pwm2_auto_point1_pwm, 1, PRI_LOW, 0x65, 0, 0, 0, u8),
PWRITE(pwm3_auto_point1_pwm, 2, PRI_LOW, 0x66, 0, 0, 0, u8),
PWRITE(pwm1_auto_point2_pwm, 0, PRI_LOW, 0x38, 0, 0, 0, u8),
PWRITE(pwm2_auto_point2_pwm, 1, PRI_LOW, 0x39, 0, 0, 0, u8),
PWRITE(pwm3_auto_point2_pwm, 2, PRI_LOW, 0x3a, 0, 0, 0, u8),
PWRITE(pwm1_freq, 0, PRI_LOW, 0x5f, 0, 0x0f, 0, pwm_freq),
PWRITE(pwm2_freq, 1, PRI_LOW, 0x60, 0, 0x0f, 0, pwm_freq),
PWRITE(pwm3_freq, 2, PRI_LOW, 0x61, 0, 0x0f, 0, pwm_freq),
PREAD(pwm1_auto_zone_assigned, 0, PRI_LOW, 0, 0, 0x03, 2, bitmask),
PREAD(pwm2_auto_zone_assigned, 1, PRI_LOW, 0, 0, 0x03, 4, bitmask),
PREAD(pwm3_auto_zone_assigned, 2, PRI_LOW, 0, 0, 0x03, 6, bitmask),
PWRITE(pwm1_auto_spinup_time, 0, PRI_LOW, 0x5c, 0, 0x07, 0, pwm_ast),
PWRITE(pwm2_auto_spinup_time, 1, PRI_LOW, 0x5d, 0, 0x07, 0, pwm_ast),
PWRITE(pwm3_auto_spinup_time, 2, PRI_LOW, 0x5e, 0, 0x07, 0, pwm_ast),
PWRITE(peci_enable, 0, PRI_LOW, 0x40, 0, 0x01, 4, bitmask),
PWRITE(peci_avg, 0, PRI_LOW, 0x36, 0, 0x07, 0, bitmask),
PWRITE(peci_domain, 0, PRI_LOW, 0x36, 0, 0x01, 3, bitmask),
PWRITE(peci_legacy, 0, PRI_LOW, 0x36, 0, 0x01, 4, bitmask),
PWRITE(peci_diode, 0, PRI_LOW, 0x0e, 0, 0x07, 4, bitmask),
PWRITE(peci_4domain, 0, PRI_LOW, 0x0e, 0, 0x01, 4, bitmask),
};
static struct asc7621_data *asc7621_update_device(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct asc7621_data *data = i2c_get_clientdata(client);
int i;
/*
* The asc7621 chips guarantee consistent reads of multi-byte values
* regardless of the order of the reads. No special logic is needed
* so we can just read the registers in whatever order they appear
* in the asc7621_params array.
*/
mutex_lock(&data->update_lock);
/* Read all the high priority registers */
if (!data->valid ||
time_after(jiffies, data->last_high_reading + INTERVAL_HIGH)) {
for (i = 0; i < ARRAY_SIZE(asc7621_register_priorities); i++) {
if (asc7621_register_priorities[i] == PRI_HIGH) {
data->reg[i] =
i2c_smbus_read_byte_data(client, i) & 0xff;
}
}
data->last_high_reading = jiffies;
}; /* last_reading */
/* Read all the low priority registers. */
if (!data->valid ||
time_after(jiffies, data->last_low_reading + INTERVAL_LOW)) {
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
if (asc7621_register_priorities[i] == PRI_LOW) {
data->reg[i] =
i2c_smbus_read_byte_data(client, i) & 0xff;
}
}
data->last_low_reading = jiffies;
}; /* last_reading */
data->valid = 1;
mutex_unlock(&data->update_lock);
return data;
}
/*
* Standard detection and initialization below
*
* Helper function that checks if an address is valid
* for a particular chip.
*/
static inline int valid_address_for_chip(int chip_type, int address)
{
int i;
for (i = 0; asc7621_chips[chip_type].addresses[i] != I2C_CLIENT_END;
i++) {
if (asc7621_chips[chip_type].addresses[i] == address)
return 1;
}
return 0;
}
static void asc7621_init_client(struct i2c_client *client)
{
int value;
/* Warn if part was not "READY" */
value = read_byte(client, 0x40);
if (value & 0x02) {
dev_err(&client->dev,
"Client (%d,0x%02x) config is locked.\n",
i2c_adapter_id(client->adapter), client->addr);
};
if (!(value & 0x04)) {
dev_err(&client->dev, "Client (%d,0x%02x) is not ready.\n",
i2c_adapter_id(client->adapter), client->addr);
};
/*
* Start monitoring
*
* Try to clear LOCK, Set START, save everything else
*/
value = (value & ~0x02) | 0x01;
write_byte(client, 0x40, value & 0xff);
}
static int
asc7621_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct asc7621_data *data;
int i, err;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -EIO;
data = kzalloc(sizeof(struct asc7621_data), GFP_KERNEL);
if (data == NULL)
return -ENOMEM;
i2c_set_clientdata(client, data);
data->valid = 0;
mutex_init(&data->update_lock);
/* Initialize the asc7621 chip */
asc7621_init_client(client);
/* Create the sysfs entries */
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
err =
device_create_file(&client->dev,
&(asc7621_params[i].sda.dev_attr));
if (err)
goto exit_remove;
}
data->class_dev = hwmon_device_register(&client->dev);
if (IS_ERR(data->class_dev)) {
err = PTR_ERR(data->class_dev);
goto exit_remove;
}
return 0;
exit_remove:
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
device_remove_file(&client->dev,
&(asc7621_params[i].sda.dev_attr));
}
kfree(data);
return err;
}
static int asc7621_detect(struct i2c_client *client,
struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
int company, verstep, chip_index;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA))
return -ENODEV;
for (chip_index = FIRST_CHIP; chip_index <= LAST_CHIP; chip_index++) {
if (!valid_address_for_chip(chip_index, client->addr))
continue;
company = read_byte(client,
asc7621_chips[chip_index].company_reg);
verstep = read_byte(client,
asc7621_chips[chip_index].verstep_reg);
if (company == asc7621_chips[chip_index].company_id &&
verstep == asc7621_chips[chip_index].verstep_id) {
strlcpy(info->type, asc7621_chips[chip_index].name,
I2C_NAME_SIZE);
dev_info(&adapter->dev, "Matched %s at 0x%02x\n",
asc7621_chips[chip_index].name, client->addr);
return 0;
}
}
return -ENODEV;
}
static int asc7621_remove(struct i2c_client *client)
{
struct asc7621_data *data = i2c_get_clientdata(client);
int i;
hwmon_device_unregister(data->class_dev);
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
device_remove_file(&client->dev,
&(asc7621_params[i].sda.dev_attr));
}
kfree(data);
return 0;
}
static const struct i2c_device_id asc7621_id[] = {
{"asc7621", asc7621},
{"asc7621a", asc7621a},
{},
};
MODULE_DEVICE_TABLE(i2c, asc7621_id);
static struct i2c_driver asc7621_driver = {
.class = I2C_CLASS_HWMON,
.driver = {
.name = "asc7621",
},
.probe = asc7621_probe,
.remove = asc7621_remove,
.id_table = asc7621_id,
.detect = asc7621_detect,
.address_list = normal_i2c,
};
static int __init sm_asc7621_init(void)
{
int i, j;
/*
* Collect all the registers needed into a single array.
* This way, if a register isn't actually used for anything,
* we don't retrieve it.
*/
for (i = 0; i < ARRAY_SIZE(asc7621_params); i++) {
for (j = 0; j < ARRAY_SIZE(asc7621_params[i].msb); j++)
asc7621_register_priorities[asc7621_params[i].msb[j]] =
asc7621_params[i].priority;
for (j = 0; j < ARRAY_SIZE(asc7621_params[i].lsb); j++)
asc7621_register_priorities[asc7621_params[i].lsb[j]] =
asc7621_params[i].priority;
}
return i2c_add_driver(&asc7621_driver);
}
static void __exit sm_asc7621_exit(void)
{
i2c_del_driver(&asc7621_driver);
}
MODULE_LICENSE("GPL");
MODULE_AUTHOR("George Joseph");
MODULE_DESCRIPTION("Andigilog aSC7621 and aSC7621a driver");
module_init(sm_asc7621_init);
module_exit(sm_asc7621_exit);
| gpl-2.0 |
TeamOrion-Devices/kernel_lge_msm8974 | security/integrity/evm/evm_crypto.c | 3510 | 6263 | /*
* Copyright (C) 2005-2010 IBM Corporation
*
* Authors:
* Mimi Zohar <zohar@us.ibm.com>
* Kylene Hall <kjhall@us.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* File: evm_crypto.c
* Using root's kernel master key (kmk), calculate the HMAC
*/
#include <linux/module.h>
#include <linux/crypto.h>
#include <linux/xattr.h>
#include <keys/encrypted-type.h>
#include <crypto/hash.h>
#include "evm.h"
#define EVMKEY "evm-key"
#define MAX_KEY_SIZE 128
static unsigned char evmkey[MAX_KEY_SIZE];
static int evmkey_len = MAX_KEY_SIZE;
struct crypto_shash *hmac_tfm;
struct crypto_shash *hash_tfm;
static DEFINE_MUTEX(mutex);
static struct shash_desc *init_desc(char type)
{
long rc;
char *algo;
struct crypto_shash **tfm;
struct shash_desc *desc;
if (type == EVM_XATTR_HMAC) {
tfm = &hmac_tfm;
algo = evm_hmac;
} else {
tfm = &hash_tfm;
algo = evm_hash;
}
if (*tfm == NULL) {
mutex_lock(&mutex);
if (*tfm)
goto out;
*tfm = crypto_alloc_shash(algo, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(*tfm)) {
rc = PTR_ERR(*tfm);
pr_err("Can not allocate %s (reason: %ld)\n", algo, rc);
*tfm = NULL;
mutex_unlock(&mutex);
return ERR_PTR(rc);
}
if (type == EVM_XATTR_HMAC) {
rc = crypto_shash_setkey(*tfm, evmkey, evmkey_len);
if (rc) {
crypto_free_shash(*tfm);
*tfm = NULL;
mutex_unlock(&mutex);
return ERR_PTR(rc);
}
}
out:
mutex_unlock(&mutex);
}
desc = kmalloc(sizeof(*desc) + crypto_shash_descsize(*tfm),
GFP_KERNEL);
if (!desc)
return ERR_PTR(-ENOMEM);
desc->tfm = *tfm;
desc->flags = CRYPTO_TFM_REQ_MAY_SLEEP;
rc = crypto_shash_init(desc);
if (rc) {
kfree(desc);
return ERR_PTR(rc);
}
return desc;
}
/* Protect against 'cutting & pasting' security.evm xattr, include inode
* specific info.
*
* (Additional directory/file metadata needs to be added for more complete
* protection.)
*/
static void hmac_add_misc(struct shash_desc *desc, struct inode *inode,
char *digest)
{
struct h_misc {
unsigned long ino;
__u32 generation;
uid_t uid;
gid_t gid;
umode_t mode;
} hmac_misc;
memset(&hmac_misc, 0, sizeof hmac_misc);
hmac_misc.ino = inode->i_ino;
hmac_misc.generation = inode->i_generation;
hmac_misc.uid = inode->i_uid;
hmac_misc.gid = inode->i_gid;
hmac_misc.mode = inode->i_mode;
crypto_shash_update(desc, (const u8 *)&hmac_misc, sizeof hmac_misc);
crypto_shash_final(desc, digest);
}
/*
* Calculate the HMAC value across the set of protected security xattrs.
*
* Instead of retrieving the requested xattr, for performance, calculate
* the hmac using the requested xattr value. Don't alloc/free memory for
* each xattr, but attempt to re-use the previously allocated memory.
*/
static int evm_calc_hmac_or_hash(struct dentry *dentry,
const char *req_xattr_name,
const char *req_xattr_value,
size_t req_xattr_value_len,
char type, char *digest)
{
struct inode *inode = dentry->d_inode;
struct shash_desc *desc;
char **xattrname;
size_t xattr_size = 0;
char *xattr_value = NULL;
int error;
int size;
if (!inode->i_op || !inode->i_op->getxattr)
return -EOPNOTSUPP;
desc = init_desc(type);
if (IS_ERR(desc))
return PTR_ERR(desc);
error = -ENODATA;
for (xattrname = evm_config_xattrnames; *xattrname != NULL; xattrname++) {
if ((req_xattr_name && req_xattr_value)
&& !strcmp(*xattrname, req_xattr_name)) {
error = 0;
crypto_shash_update(desc, (const u8 *)req_xattr_value,
req_xattr_value_len);
continue;
}
size = vfs_getxattr_alloc(dentry, *xattrname,
&xattr_value, xattr_size, GFP_NOFS);
if (size == -ENOMEM) {
error = -ENOMEM;
goto out;
}
if (size < 0)
continue;
error = 0;
xattr_size = size;
crypto_shash_update(desc, (const u8 *)xattr_value, xattr_size);
}
hmac_add_misc(desc, inode, digest);
out:
kfree(xattr_value);
kfree(desc);
return error;
}
int evm_calc_hmac(struct dentry *dentry, const char *req_xattr_name,
const char *req_xattr_value, size_t req_xattr_value_len,
char *digest)
{
return evm_calc_hmac_or_hash(dentry, req_xattr_name, req_xattr_value,
req_xattr_value_len, EVM_XATTR_HMAC, digest);
}
int evm_calc_hash(struct dentry *dentry, const char *req_xattr_name,
const char *req_xattr_value, size_t req_xattr_value_len,
char *digest)
{
return evm_calc_hmac_or_hash(dentry, req_xattr_name, req_xattr_value,
req_xattr_value_len, IMA_XATTR_DIGEST, digest);
}
/*
* Calculate the hmac and update security.evm xattr
*
* Expects to be called with i_mutex locked.
*/
int evm_update_evmxattr(struct dentry *dentry, const char *xattr_name,
const char *xattr_value, size_t xattr_value_len)
{
struct inode *inode = dentry->d_inode;
struct evm_ima_xattr_data xattr_data;
int rc = 0;
rc = evm_calc_hmac(dentry, xattr_name, xattr_value,
xattr_value_len, xattr_data.digest);
if (rc == 0) {
xattr_data.type = EVM_XATTR_HMAC;
rc = __vfs_setxattr_noperm(dentry, XATTR_NAME_EVM,
&xattr_data,
sizeof(xattr_data), 0);
}
else if (rc == -ENODATA)
rc = inode->i_op->removexattr(dentry, XATTR_NAME_EVM);
return rc;
}
int evm_init_hmac(struct inode *inode, const struct xattr *lsm_xattr,
char *hmac_val)
{
struct shash_desc *desc;
desc = init_desc(EVM_XATTR_HMAC);
if (IS_ERR(desc)) {
printk(KERN_INFO "init_desc failed\n");
return PTR_ERR(desc);
}
crypto_shash_update(desc, lsm_xattr->value, lsm_xattr->value_len);
hmac_add_misc(desc, inode, hmac_val);
kfree(desc);
return 0;
}
/*
* Get the key from the TPM for the SHA1-HMAC
*/
int evm_init_key(void)
{
struct key *evm_key;
struct encrypted_key_payload *ekp;
int rc = 0;
evm_key = request_key(&key_type_encrypted, EVMKEY, NULL);
if (IS_ERR(evm_key))
return -ENOENT;
down_read(&evm_key->sem);
ekp = evm_key->payload.data;
if (ekp->decrypted_datalen > MAX_KEY_SIZE) {
rc = -EINVAL;
goto out;
}
memcpy(evmkey, ekp->decrypted_data, ekp->decrypted_datalen);
out:
/* burn the original key contents */
memset(ekp->decrypted_data, 0, ekp->decrypted_datalen);
up_read(&evm_key->sem);
key_put(evm_key);
return rc;
}
| gpl-2.0 |
IndieBeto/StockLP | arch/arm/common/vic.c | 4790 | 11708 | /*
* linux/arch/arm/common/vic.c
*
* Copyright (C) 1999 - 2003 ARM Limited
* Copyright (C) 2000 Deep Blue Solutions Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This 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/export.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/irqdomain.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/syscore_ops.h>
#include <linux/device.h>
#include <linux/amba/bus.h>
#include <asm/exception.h>
#include <asm/mach/irq.h>
#include <asm/hardware/vic.h>
/**
* struct vic_device - VIC PM device
* @irq: The IRQ number for the base of the VIC.
* @base: The register base for the VIC.
* @resume_sources: A bitmask of interrupts for resume.
* @resume_irqs: The IRQs enabled for resume.
* @int_select: Save for VIC_INT_SELECT.
* @int_enable: Save for VIC_INT_ENABLE.
* @soft_int: Save for VIC_INT_SOFT.
* @protect: Save for VIC_PROTECT.
* @domain: The IRQ domain for the VIC.
*/
struct vic_device {
void __iomem *base;
int irq;
u32 resume_sources;
u32 resume_irqs;
u32 int_select;
u32 int_enable;
u32 soft_int;
u32 protect;
struct irq_domain *domain;
};
/* we cannot allocate memory when VICs are initially registered */
static struct vic_device vic_devices[CONFIG_ARM_VIC_NR];
static int vic_id;
/**
* vic_init2 - common initialisation code
* @base: Base of the VIC.
*
* Common initialisation code for registration
* and resume.
*/
static void vic_init2(void __iomem *base)
{
int i;
for (i = 0; i < 16; i++) {
void __iomem *reg = base + VIC_VECT_CNTL0 + (i * 4);
writel(VIC_VECT_CNTL_ENABLE | i, reg);
}
writel(32, base + VIC_PL190_DEF_VECT_ADDR);
}
#ifdef CONFIG_PM
static void resume_one_vic(struct vic_device *vic)
{
void __iomem *base = vic->base;
printk(KERN_DEBUG "%s: resuming vic at %p\n", __func__, base);
/* re-initialise static settings */
vic_init2(base);
writel(vic->int_select, base + VIC_INT_SELECT);
writel(vic->protect, base + VIC_PROTECT);
/* set the enabled ints and then clear the non-enabled */
writel(vic->int_enable, base + VIC_INT_ENABLE);
writel(~vic->int_enable, base + VIC_INT_ENABLE_CLEAR);
/* and the same for the soft-int register */
writel(vic->soft_int, base + VIC_INT_SOFT);
writel(~vic->soft_int, base + VIC_INT_SOFT_CLEAR);
}
static void vic_resume(void)
{
int id;
for (id = vic_id - 1; id >= 0; id--)
resume_one_vic(vic_devices + id);
}
static void suspend_one_vic(struct vic_device *vic)
{
void __iomem *base = vic->base;
printk(KERN_DEBUG "%s: suspending vic at %p\n", __func__, base);
vic->int_select = readl(base + VIC_INT_SELECT);
vic->int_enable = readl(base + VIC_INT_ENABLE);
vic->soft_int = readl(base + VIC_INT_SOFT);
vic->protect = readl(base + VIC_PROTECT);
/* set the interrupts (if any) that are used for
* resuming the system */
writel(vic->resume_irqs, base + VIC_INT_ENABLE);
writel(~vic->resume_irqs, base + VIC_INT_ENABLE_CLEAR);
}
static int vic_suspend(void)
{
int id;
for (id = 0; id < vic_id; id++)
suspend_one_vic(vic_devices + id);
return 0;
}
struct syscore_ops vic_syscore_ops = {
.suspend = vic_suspend,
.resume = vic_resume,
};
/**
* vic_pm_init - initicall to register VIC pm
*
* This is called via late_initcall() to register
* the resources for the VICs due to the early
* nature of the VIC's registration.
*/
static int __init vic_pm_init(void)
{
if (vic_id > 0)
register_syscore_ops(&vic_syscore_ops);
return 0;
}
late_initcall(vic_pm_init);
#endif /* CONFIG_PM */
/**
* vic_register() - Register a VIC.
* @base: The base address of the VIC.
* @irq: The base IRQ for the VIC.
* @resume_sources: bitmask of interrupts allowed for resume sources.
* @node: The device tree node associated with the VIC.
*
* Register the VIC with the system device tree so that it can be notified
* of suspend and resume requests and ensure that the correct actions are
* taken to re-instate the settings on resume.
*
* This also configures the IRQ domain for the VIC.
*/
static void __init vic_register(void __iomem *base, unsigned int irq,
u32 resume_sources, struct device_node *node)
{
struct vic_device *v;
if (vic_id >= ARRAY_SIZE(vic_devices)) {
printk(KERN_ERR "%s: too few VICs, increase CONFIG_ARM_VIC_NR\n", __func__);
return;
}
v = &vic_devices[vic_id];
v->base = base;
v->resume_sources = resume_sources;
v->irq = irq;
vic_id++;
v->domain = irq_domain_add_legacy(node, 32, irq, 0,
&irq_domain_simple_ops, v);
}
static void vic_ack_irq(struct irq_data *d)
{
void __iomem *base = irq_data_get_irq_chip_data(d);
unsigned int irq = d->hwirq;
writel(1 << irq, base + VIC_INT_ENABLE_CLEAR);
/* moreover, clear the soft-triggered, in case it was the reason */
writel(1 << irq, base + VIC_INT_SOFT_CLEAR);
}
static void vic_mask_irq(struct irq_data *d)
{
void __iomem *base = irq_data_get_irq_chip_data(d);
unsigned int irq = d->hwirq;
writel(1 << irq, base + VIC_INT_ENABLE_CLEAR);
}
static void vic_unmask_irq(struct irq_data *d)
{
void __iomem *base = irq_data_get_irq_chip_data(d);
unsigned int irq = d->hwirq;
writel(1 << irq, base + VIC_INT_ENABLE);
}
#if defined(CONFIG_PM)
static struct vic_device *vic_from_irq(unsigned int irq)
{
struct vic_device *v = vic_devices;
unsigned int base_irq = irq & ~31;
int id;
for (id = 0; id < vic_id; id++, v++) {
if (v->irq == base_irq)
return v;
}
return NULL;
}
static int vic_set_wake(struct irq_data *d, unsigned int on)
{
struct vic_device *v = vic_from_irq(d->irq);
unsigned int off = d->hwirq;
u32 bit = 1 << off;
if (!v)
return -EINVAL;
if (!(bit & v->resume_sources))
return -EINVAL;
if (on)
v->resume_irqs |= bit;
else
v->resume_irqs &= ~bit;
return 0;
}
#else
#define vic_set_wake NULL
#endif /* CONFIG_PM */
static struct irq_chip vic_chip = {
.name = "VIC",
.irq_ack = vic_ack_irq,
.irq_mask = vic_mask_irq,
.irq_unmask = vic_unmask_irq,
.irq_set_wake = vic_set_wake,
};
static void __init vic_disable(void __iomem *base)
{
writel(0, base + VIC_INT_SELECT);
writel(0, base + VIC_INT_ENABLE);
writel(~0, base + VIC_INT_ENABLE_CLEAR);
writel(0, base + VIC_ITCR);
writel(~0, base + VIC_INT_SOFT_CLEAR);
}
static void __init vic_clear_interrupts(void __iomem *base)
{
unsigned int i;
writel(0, base + VIC_PL190_VECT_ADDR);
for (i = 0; i < 19; i++) {
unsigned int value;
value = readl(base + VIC_PL190_VECT_ADDR);
writel(value, base + VIC_PL190_VECT_ADDR);
}
}
static void __init vic_set_irq_sources(void __iomem *base,
unsigned int irq_start, u32 vic_sources)
{
unsigned int i;
for (i = 0; i < 32; i++) {
if (vic_sources & (1 << i)) {
unsigned int irq = irq_start + i;
irq_set_chip_and_handler(irq, &vic_chip,
handle_level_irq);
irq_set_chip_data(irq, base);
set_irq_flags(irq, IRQF_VALID | IRQF_PROBE);
}
}
}
/*
* The PL190 cell from ARM has been modified by ST to handle 64 interrupts.
* The original cell has 32 interrupts, while the modified one has 64,
* replocating two blocks 0x00..0x1f in 0x20..0x3f. In that case
* the probe function is called twice, with base set to offset 000
* and 020 within the page. We call this "second block".
*/
static void __init vic_init_st(void __iomem *base, unsigned int irq_start,
u32 vic_sources, struct device_node *node)
{
unsigned int i;
int vic_2nd_block = ((unsigned long)base & ~PAGE_MASK) != 0;
/* Disable all interrupts initially. */
vic_disable(base);
/*
* Make sure we clear all existing interrupts. The vector registers
* in this cell are after the second block of general registers,
* so we can address them using standard offsets, but only from
* the second base address, which is 0x20 in the page
*/
if (vic_2nd_block) {
vic_clear_interrupts(base);
/* ST has 16 vectors as well, but we don't enable them by now */
for (i = 0; i < 16; i++) {
void __iomem *reg = base + VIC_VECT_CNTL0 + (i * 4);
writel(0, reg);
}
writel(32, base + VIC_PL190_DEF_VECT_ADDR);
}
vic_set_irq_sources(base, irq_start, vic_sources);
vic_register(base, irq_start, 0, node);
}
void __init __vic_init(void __iomem *base, unsigned int irq_start,
u32 vic_sources, u32 resume_sources,
struct device_node *node)
{
unsigned int i;
u32 cellid = 0;
enum amba_vendor vendor;
/* Identify which VIC cell this one is, by reading the ID */
for (i = 0; i < 4; i++) {
void __iomem *addr;
addr = (void __iomem *)((u32)base & PAGE_MASK) + 0xfe0 + (i * 4);
cellid |= (readl(addr) & 0xff) << (8 * i);
}
vendor = (cellid >> 12) & 0xff;
printk(KERN_INFO "VIC @%p: id 0x%08x, vendor 0x%02x\n",
base, cellid, vendor);
switch(vendor) {
case AMBA_VENDOR_ST:
vic_init_st(base, irq_start, vic_sources, node);
return;
default:
printk(KERN_WARNING "VIC: unknown vendor, continuing anyways\n");
/* fall through */
case AMBA_VENDOR_ARM:
break;
}
/* Disable all interrupts initially. */
vic_disable(base);
/* Make sure we clear all existing interrupts */
vic_clear_interrupts(base);
vic_init2(base);
vic_set_irq_sources(base, irq_start, vic_sources);
vic_register(base, irq_start, resume_sources, node);
}
/**
* vic_init() - initialise a vectored interrupt controller
* @base: iomem base address
* @irq_start: starting interrupt number, must be muliple of 32
* @vic_sources: bitmask of interrupt sources to allow
* @resume_sources: bitmask of interrupt sources to allow for resume
*/
void __init vic_init(void __iomem *base, unsigned int irq_start,
u32 vic_sources, u32 resume_sources)
{
__vic_init(base, irq_start, vic_sources, resume_sources, NULL);
}
#ifdef CONFIG_OF
int __init vic_of_init(struct device_node *node, struct device_node *parent)
{
void __iomem *regs;
int irq_base;
if (WARN(parent, "non-root VICs are not supported"))
return -EINVAL;
regs = of_iomap(node, 0);
if (WARN_ON(!regs))
return -EIO;
irq_base = irq_alloc_descs(-1, 0, 32, numa_node_id());
if (WARN_ON(irq_base < 0))
goto out_unmap;
__vic_init(regs, irq_base, ~0, ~0, node);
return 0;
out_unmap:
iounmap(regs);
return -EIO;
}
#endif /* CONFIG OF */
/*
* Handle each interrupt in a single VIC. Returns non-zero if we've
* handled at least one interrupt. This reads the status register
* before handling each interrupt, which is necessary given that
* handle_IRQ may briefly re-enable interrupts for soft IRQ handling.
*/
static int handle_one_vic(struct vic_device *vic, struct pt_regs *regs)
{
u32 stat, irq;
int handled = 0;
while ((stat = readl_relaxed(vic->base + VIC_IRQ_STATUS))) {
irq = ffs(stat) - 1;
handle_IRQ(irq_find_mapping(vic->domain, irq), regs);
handled = 1;
}
return handled;
}
/*
* Keep iterating over all registered VIC's until there are no pending
* interrupts.
*/
asmlinkage void __exception_irq_entry vic_handle_irq(struct pt_regs *regs)
{
int i, handled;
do {
for (i = 0, handled = 0; i < vic_id; ++i)
handled |= handle_one_vic(&vic_devices[i], regs);
} while (handled);
}
| gpl-2.0 |
GreatDevs/kernel_sony_msm8974 | drivers/mfd/ab8500-core.c | 4790 | 28013 | /*
* Copyright (C) ST-Ericsson SA 2010
*
* License Terms: GNU General Public License v2
* Author: Srinidhi Kasagar <srinidhi.kasagar@stericsson.com>
* Author: Rabin Vincent <rabin.vincent@stericsson.com>
* Author: Mattias Wallin <mattias.wallin@stericsson.com>
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/mfd/core.h>
#include <linux/mfd/abx500.h>
#include <linux/mfd/abx500/ab8500.h>
#include <linux/regulator/ab8500.h>
/*
* Interrupt register offsets
* Bank : 0x0E
*/
#define AB8500_IT_SOURCE1_REG 0x00
#define AB8500_IT_SOURCE2_REG 0x01
#define AB8500_IT_SOURCE3_REG 0x02
#define AB8500_IT_SOURCE4_REG 0x03
#define AB8500_IT_SOURCE5_REG 0x04
#define AB8500_IT_SOURCE6_REG 0x05
#define AB8500_IT_SOURCE7_REG 0x06
#define AB8500_IT_SOURCE8_REG 0x07
#define AB9540_IT_SOURCE13_REG 0x0C
#define AB8500_IT_SOURCE19_REG 0x12
#define AB8500_IT_SOURCE20_REG 0x13
#define AB8500_IT_SOURCE21_REG 0x14
#define AB8500_IT_SOURCE22_REG 0x15
#define AB8500_IT_SOURCE23_REG 0x16
#define AB8500_IT_SOURCE24_REG 0x17
/*
* latch registers
*/
#define AB8500_IT_LATCH1_REG 0x20
#define AB8500_IT_LATCH2_REG 0x21
#define AB8500_IT_LATCH3_REG 0x22
#define AB8500_IT_LATCH4_REG 0x23
#define AB8500_IT_LATCH5_REG 0x24
#define AB8500_IT_LATCH6_REG 0x25
#define AB8500_IT_LATCH7_REG 0x26
#define AB8500_IT_LATCH8_REG 0x27
#define AB8500_IT_LATCH9_REG 0x28
#define AB8500_IT_LATCH10_REG 0x29
#define AB8500_IT_LATCH12_REG 0x2B
#define AB9540_IT_LATCH13_REG 0x2C
#define AB8500_IT_LATCH19_REG 0x32
#define AB8500_IT_LATCH20_REG 0x33
#define AB8500_IT_LATCH21_REG 0x34
#define AB8500_IT_LATCH22_REG 0x35
#define AB8500_IT_LATCH23_REG 0x36
#define AB8500_IT_LATCH24_REG 0x37
/*
* mask registers
*/
#define AB8500_IT_MASK1_REG 0x40
#define AB8500_IT_MASK2_REG 0x41
#define AB8500_IT_MASK3_REG 0x42
#define AB8500_IT_MASK4_REG 0x43
#define AB8500_IT_MASK5_REG 0x44
#define AB8500_IT_MASK6_REG 0x45
#define AB8500_IT_MASK7_REG 0x46
#define AB8500_IT_MASK8_REG 0x47
#define AB8500_IT_MASK9_REG 0x48
#define AB8500_IT_MASK10_REG 0x49
#define AB8500_IT_MASK11_REG 0x4A
#define AB8500_IT_MASK12_REG 0x4B
#define AB8500_IT_MASK13_REG 0x4C
#define AB8500_IT_MASK14_REG 0x4D
#define AB8500_IT_MASK15_REG 0x4E
#define AB8500_IT_MASK16_REG 0x4F
#define AB8500_IT_MASK17_REG 0x50
#define AB8500_IT_MASK18_REG 0x51
#define AB8500_IT_MASK19_REG 0x52
#define AB8500_IT_MASK20_REG 0x53
#define AB8500_IT_MASK21_REG 0x54
#define AB8500_IT_MASK22_REG 0x55
#define AB8500_IT_MASK23_REG 0x56
#define AB8500_IT_MASK24_REG 0x57
#define AB8500_REV_REG 0x80
#define AB8500_IC_NAME_REG 0x82
#define AB8500_SWITCH_OFF_STATUS 0x00
#define AB8500_TURN_ON_STATUS 0x00
#define AB9540_MODEM_CTRL2_REG 0x23
#define AB9540_MODEM_CTRL2_SWDBBRSTN_BIT BIT(2)
/*
* Map interrupt numbers to the LATCH and MASK register offsets, Interrupt
* numbers are indexed into this array with (num / 8). The interupts are
* defined in linux/mfd/ab8500.h
*
* This is one off from the register names, i.e. AB8500_IT_MASK1_REG is at
* offset 0.
*/
/* AB8500 support */
static const int ab8500_irq_regoffset[AB8500_NUM_IRQ_REGS] = {
0, 1, 2, 3, 4, 6, 7, 8, 9, 11, 18, 19, 20, 21,
};
/* AB9540 support */
static const int ab9540_irq_regoffset[AB9540_NUM_IRQ_REGS] = {
0, 1, 2, 3, 4, 6, 7, 8, 9, 11, 18, 19, 20, 21, 12, 13, 24,
};
static const char ab8500_version_str[][7] = {
[AB8500_VERSION_AB8500] = "AB8500",
[AB8500_VERSION_AB8505] = "AB8505",
[AB8500_VERSION_AB9540] = "AB9540",
[AB8500_VERSION_AB8540] = "AB8540",
};
static int ab8500_get_chip_id(struct device *dev)
{
struct ab8500 *ab8500;
if (!dev)
return -EINVAL;
ab8500 = dev_get_drvdata(dev->parent);
return ab8500 ? (int)ab8500->chip_id : -EINVAL;
}
static int set_register_interruptible(struct ab8500 *ab8500, u8 bank,
u8 reg, u8 data)
{
int ret;
/*
* Put the u8 bank and u8 register together into a an u16.
* The bank on higher 8 bits and register in lower 8 bits.
* */
u16 addr = ((u16)bank) << 8 | reg;
dev_vdbg(ab8500->dev, "wr: addr %#x <= %#x\n", addr, data);
mutex_lock(&ab8500->lock);
ret = ab8500->write(ab8500, addr, data);
if (ret < 0)
dev_err(ab8500->dev, "failed to write reg %#x: %d\n",
addr, ret);
mutex_unlock(&ab8500->lock);
return ret;
}
static int ab8500_set_register(struct device *dev, u8 bank,
u8 reg, u8 value)
{
struct ab8500 *ab8500 = dev_get_drvdata(dev->parent);
return set_register_interruptible(ab8500, bank, reg, value);
}
static int get_register_interruptible(struct ab8500 *ab8500, u8 bank,
u8 reg, u8 *value)
{
int ret;
/* put the u8 bank and u8 reg together into a an u16.
* bank on higher 8 bits and reg in lower */
u16 addr = ((u16)bank) << 8 | reg;
mutex_lock(&ab8500->lock);
ret = ab8500->read(ab8500, addr);
if (ret < 0)
dev_err(ab8500->dev, "failed to read reg %#x: %d\n",
addr, ret);
else
*value = ret;
mutex_unlock(&ab8500->lock);
dev_vdbg(ab8500->dev, "rd: addr %#x => data %#x\n", addr, ret);
return ret;
}
static int ab8500_get_register(struct device *dev, u8 bank,
u8 reg, u8 *value)
{
struct ab8500 *ab8500 = dev_get_drvdata(dev->parent);
return get_register_interruptible(ab8500, bank, reg, value);
}
static int mask_and_set_register_interruptible(struct ab8500 *ab8500, u8 bank,
u8 reg, u8 bitmask, u8 bitvalues)
{
int ret;
/* put the u8 bank and u8 reg together into a an u16.
* bank on higher 8 bits and reg in lower */
u16 addr = ((u16)bank) << 8 | reg;
mutex_lock(&ab8500->lock);
if (ab8500->write_masked == NULL) {
u8 data;
ret = ab8500->read(ab8500, addr);
if (ret < 0) {
dev_err(ab8500->dev, "failed to read reg %#x: %d\n",
addr, ret);
goto out;
}
data = (u8)ret;
data = (~bitmask & data) | (bitmask & bitvalues);
ret = ab8500->write(ab8500, addr, data);
if (ret < 0)
dev_err(ab8500->dev, "failed to write reg %#x: %d\n",
addr, ret);
dev_vdbg(ab8500->dev, "mask: addr %#x => data %#x\n", addr,
data);
goto out;
}
ret = ab8500->write_masked(ab8500, addr, bitmask, bitvalues);
if (ret < 0)
dev_err(ab8500->dev, "failed to modify reg %#x: %d\n", addr,
ret);
out:
mutex_unlock(&ab8500->lock);
return ret;
}
static int ab8500_mask_and_set_register(struct device *dev,
u8 bank, u8 reg, u8 bitmask, u8 bitvalues)
{
struct ab8500 *ab8500 = dev_get_drvdata(dev->parent);
return mask_and_set_register_interruptible(ab8500, bank, reg,
bitmask, bitvalues);
}
static struct abx500_ops ab8500_ops = {
.get_chip_id = ab8500_get_chip_id,
.get_register = ab8500_get_register,
.set_register = ab8500_set_register,
.get_register_page = NULL,
.set_register_page = NULL,
.mask_and_set_register = ab8500_mask_and_set_register,
.event_registers_startup_state_get = NULL,
.startup_irq_enabled = NULL,
};
static void ab8500_irq_lock(struct irq_data *data)
{
struct ab8500 *ab8500 = irq_data_get_irq_chip_data(data);
mutex_lock(&ab8500->irq_lock);
}
static void ab8500_irq_sync_unlock(struct irq_data *data)
{
struct ab8500 *ab8500 = irq_data_get_irq_chip_data(data);
int i;
for (i = 0; i < ab8500->mask_size; i++) {
u8 old = ab8500->oldmask[i];
u8 new = ab8500->mask[i];
int reg;
if (new == old)
continue;
/*
* Interrupt register 12 doesn't exist prior to AB8500 version
* 2.0
*/
if (ab8500->irq_reg_offset[i] == 11 &&
is_ab8500_1p1_or_earlier(ab8500))
continue;
ab8500->oldmask[i] = new;
reg = AB8500_IT_MASK1_REG + ab8500->irq_reg_offset[i];
set_register_interruptible(ab8500, AB8500_INTERRUPT, reg, new);
}
mutex_unlock(&ab8500->irq_lock);
}
static void ab8500_irq_mask(struct irq_data *data)
{
struct ab8500 *ab8500 = irq_data_get_irq_chip_data(data);
int offset = data->irq - ab8500->irq_base;
int index = offset / 8;
int mask = 1 << (offset % 8);
ab8500->mask[index] |= mask;
}
static void ab8500_irq_unmask(struct irq_data *data)
{
struct ab8500 *ab8500 = irq_data_get_irq_chip_data(data);
int offset = data->irq - ab8500->irq_base;
int index = offset / 8;
int mask = 1 << (offset % 8);
ab8500->mask[index] &= ~mask;
}
static struct irq_chip ab8500_irq_chip = {
.name = "ab8500",
.irq_bus_lock = ab8500_irq_lock,
.irq_bus_sync_unlock = ab8500_irq_sync_unlock,
.irq_mask = ab8500_irq_mask,
.irq_disable = ab8500_irq_mask,
.irq_unmask = ab8500_irq_unmask,
};
static irqreturn_t ab8500_irq(int irq, void *dev)
{
struct ab8500 *ab8500 = dev;
int i;
dev_vdbg(ab8500->dev, "interrupt\n");
for (i = 0; i < ab8500->mask_size; i++) {
int regoffset = ab8500->irq_reg_offset[i];
int status;
u8 value;
/*
* Interrupt register 12 doesn't exist prior to AB8500 version
* 2.0
*/
if (regoffset == 11 && is_ab8500_1p1_or_earlier(ab8500))
continue;
status = get_register_interruptible(ab8500, AB8500_INTERRUPT,
AB8500_IT_LATCH1_REG + regoffset, &value);
if (status < 0 || value == 0)
continue;
do {
int bit = __ffs(value);
int line = i * 8 + bit;
handle_nested_irq(ab8500->irq_base + line);
value &= ~(1 << bit);
} while (value);
}
return IRQ_HANDLED;
}
static int ab8500_irq_init(struct ab8500 *ab8500)
{
int base = ab8500->irq_base;
int irq;
int num_irqs;
if (is_ab9540(ab8500))
num_irqs = AB9540_NR_IRQS;
else if (is_ab8505(ab8500))
num_irqs = AB8505_NR_IRQS;
else
num_irqs = AB8500_NR_IRQS;
for (irq = base; irq < base + num_irqs; irq++) {
irq_set_chip_data(irq, ab8500);
irq_set_chip_and_handler(irq, &ab8500_irq_chip,
handle_simple_irq);
irq_set_nested_thread(irq, 1);
#ifdef CONFIG_ARM
set_irq_flags(irq, IRQF_VALID);
#else
irq_set_noprobe(irq);
#endif
}
return 0;
}
static void ab8500_irq_remove(struct ab8500 *ab8500)
{
int base = ab8500->irq_base;
int irq;
int num_irqs;
if (is_ab9540(ab8500))
num_irqs = AB9540_NR_IRQS;
else if (is_ab8505(ab8500))
num_irqs = AB8505_NR_IRQS;
else
num_irqs = AB8500_NR_IRQS;
for (irq = base; irq < base + num_irqs; irq++) {
#ifdef CONFIG_ARM
set_irq_flags(irq, 0);
#endif
irq_set_chip_and_handler(irq, NULL, NULL);
irq_set_chip_data(irq, NULL);
}
}
/* AB8500 GPIO Resources */
static struct resource __devinitdata ab8500_gpio_resources[] = {
{
.name = "GPIO_INT6",
.start = AB8500_INT_GPIO6R,
.end = AB8500_INT_GPIO41F,
.flags = IORESOURCE_IRQ,
}
};
/* AB9540 GPIO Resources */
static struct resource __devinitdata ab9540_gpio_resources[] = {
{
.name = "GPIO_INT6",
.start = AB8500_INT_GPIO6R,
.end = AB8500_INT_GPIO41F,
.flags = IORESOURCE_IRQ,
},
{
.name = "GPIO_INT14",
.start = AB9540_INT_GPIO50R,
.end = AB9540_INT_GPIO54R,
.flags = IORESOURCE_IRQ,
},
{
.name = "GPIO_INT15",
.start = AB9540_INT_GPIO50F,
.end = AB9540_INT_GPIO54F,
.flags = IORESOURCE_IRQ,
}
};
static struct resource __devinitdata ab8500_gpadc_resources[] = {
{
.name = "HW_CONV_END",
.start = AB8500_INT_GP_HW_ADC_CONV_END,
.end = AB8500_INT_GP_HW_ADC_CONV_END,
.flags = IORESOURCE_IRQ,
},
{
.name = "SW_CONV_END",
.start = AB8500_INT_GP_SW_ADC_CONV_END,
.end = AB8500_INT_GP_SW_ADC_CONV_END,
.flags = IORESOURCE_IRQ,
},
};
static struct resource __devinitdata ab8500_rtc_resources[] = {
{
.name = "60S",
.start = AB8500_INT_RTC_60S,
.end = AB8500_INT_RTC_60S,
.flags = IORESOURCE_IRQ,
},
{
.name = "ALARM",
.start = AB8500_INT_RTC_ALARM,
.end = AB8500_INT_RTC_ALARM,
.flags = IORESOURCE_IRQ,
},
};
static struct resource __devinitdata ab8500_poweronkey_db_resources[] = {
{
.name = "ONKEY_DBF",
.start = AB8500_INT_PON_KEY1DB_F,
.end = AB8500_INT_PON_KEY1DB_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "ONKEY_DBR",
.start = AB8500_INT_PON_KEY1DB_R,
.end = AB8500_INT_PON_KEY1DB_R,
.flags = IORESOURCE_IRQ,
},
};
static struct resource __devinitdata ab8500_av_acc_detect_resources[] = {
{
.name = "ACC_DETECT_1DB_F",
.start = AB8500_INT_ACC_DETECT_1DB_F,
.end = AB8500_INT_ACC_DETECT_1DB_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "ACC_DETECT_1DB_R",
.start = AB8500_INT_ACC_DETECT_1DB_R,
.end = AB8500_INT_ACC_DETECT_1DB_R,
.flags = IORESOURCE_IRQ,
},
{
.name = "ACC_DETECT_21DB_F",
.start = AB8500_INT_ACC_DETECT_21DB_F,
.end = AB8500_INT_ACC_DETECT_21DB_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "ACC_DETECT_21DB_R",
.start = AB8500_INT_ACC_DETECT_21DB_R,
.end = AB8500_INT_ACC_DETECT_21DB_R,
.flags = IORESOURCE_IRQ,
},
{
.name = "ACC_DETECT_22DB_F",
.start = AB8500_INT_ACC_DETECT_22DB_F,
.end = AB8500_INT_ACC_DETECT_22DB_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "ACC_DETECT_22DB_R",
.start = AB8500_INT_ACC_DETECT_22DB_R,
.end = AB8500_INT_ACC_DETECT_22DB_R,
.flags = IORESOURCE_IRQ,
},
};
static struct resource __devinitdata ab8500_charger_resources[] = {
{
.name = "MAIN_CH_UNPLUG_DET",
.start = AB8500_INT_MAIN_CH_UNPLUG_DET,
.end = AB8500_INT_MAIN_CH_UNPLUG_DET,
.flags = IORESOURCE_IRQ,
},
{
.name = "MAIN_CHARGE_PLUG_DET",
.start = AB8500_INT_MAIN_CH_PLUG_DET,
.end = AB8500_INT_MAIN_CH_PLUG_DET,
.flags = IORESOURCE_IRQ,
},
{
.name = "VBUS_DET_R",
.start = AB8500_INT_VBUS_DET_R,
.end = AB8500_INT_VBUS_DET_R,
.flags = IORESOURCE_IRQ,
},
{
.name = "VBUS_DET_F",
.start = AB8500_INT_VBUS_DET_F,
.end = AB8500_INT_VBUS_DET_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "USB_LINK_STATUS",
.start = AB8500_INT_USB_LINK_STATUS,
.end = AB8500_INT_USB_LINK_STATUS,
.flags = IORESOURCE_IRQ,
},
{
.name = "VBUS_OVV",
.start = AB8500_INT_VBUS_OVV,
.end = AB8500_INT_VBUS_OVV,
.flags = IORESOURCE_IRQ,
},
{
.name = "USB_CH_TH_PROT_R",
.start = AB8500_INT_USB_CH_TH_PROT_R,
.end = AB8500_INT_USB_CH_TH_PROT_R,
.flags = IORESOURCE_IRQ,
},
{
.name = "USB_CH_TH_PROT_F",
.start = AB8500_INT_USB_CH_TH_PROT_F,
.end = AB8500_INT_USB_CH_TH_PROT_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "MAIN_EXT_CH_NOT_OK",
.start = AB8500_INT_MAIN_EXT_CH_NOT_OK,
.end = AB8500_INT_MAIN_EXT_CH_NOT_OK,
.flags = IORESOURCE_IRQ,
},
{
.name = "MAIN_CH_TH_PROT_R",
.start = AB8500_INT_MAIN_CH_TH_PROT_R,
.end = AB8500_INT_MAIN_CH_TH_PROT_R,
.flags = IORESOURCE_IRQ,
},
{
.name = "MAIN_CH_TH_PROT_F",
.start = AB8500_INT_MAIN_CH_TH_PROT_F,
.end = AB8500_INT_MAIN_CH_TH_PROT_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "USB_CHARGER_NOT_OKR",
.start = AB8500_INT_USB_CHARGER_NOT_OKR,
.end = AB8500_INT_USB_CHARGER_NOT_OKR,
.flags = IORESOURCE_IRQ,
},
{
.name = "CH_WD_EXP",
.start = AB8500_INT_CH_WD_EXP,
.end = AB8500_INT_CH_WD_EXP,
.flags = IORESOURCE_IRQ,
},
};
static struct resource __devinitdata ab8500_btemp_resources[] = {
{
.name = "BAT_CTRL_INDB",
.start = AB8500_INT_BAT_CTRL_INDB,
.end = AB8500_INT_BAT_CTRL_INDB,
.flags = IORESOURCE_IRQ,
},
{
.name = "BTEMP_LOW",
.start = AB8500_INT_BTEMP_LOW,
.end = AB8500_INT_BTEMP_LOW,
.flags = IORESOURCE_IRQ,
},
{
.name = "BTEMP_HIGH",
.start = AB8500_INT_BTEMP_HIGH,
.end = AB8500_INT_BTEMP_HIGH,
.flags = IORESOURCE_IRQ,
},
{
.name = "BTEMP_LOW_MEDIUM",
.start = AB8500_INT_BTEMP_LOW_MEDIUM,
.end = AB8500_INT_BTEMP_LOW_MEDIUM,
.flags = IORESOURCE_IRQ,
},
{
.name = "BTEMP_MEDIUM_HIGH",
.start = AB8500_INT_BTEMP_MEDIUM_HIGH,
.end = AB8500_INT_BTEMP_MEDIUM_HIGH,
.flags = IORESOURCE_IRQ,
},
};
static struct resource __devinitdata ab8500_fg_resources[] = {
{
.name = "NCONV_ACCU",
.start = AB8500_INT_CCN_CONV_ACC,
.end = AB8500_INT_CCN_CONV_ACC,
.flags = IORESOURCE_IRQ,
},
{
.name = "BATT_OVV",
.start = AB8500_INT_BATT_OVV,
.end = AB8500_INT_BATT_OVV,
.flags = IORESOURCE_IRQ,
},
{
.name = "LOW_BAT_F",
.start = AB8500_INT_LOW_BAT_F,
.end = AB8500_INT_LOW_BAT_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "LOW_BAT_R",
.start = AB8500_INT_LOW_BAT_R,
.end = AB8500_INT_LOW_BAT_R,
.flags = IORESOURCE_IRQ,
},
{
.name = "CC_INT_CALIB",
.start = AB8500_INT_CC_INT_CALIB,
.end = AB8500_INT_CC_INT_CALIB,
.flags = IORESOURCE_IRQ,
},
{
.name = "CCEOC",
.start = AB8500_INT_CCEOC,
.end = AB8500_INT_CCEOC,
.flags = IORESOURCE_IRQ,
},
};
static struct resource __devinitdata ab8500_chargalg_resources[] = {};
#ifdef CONFIG_DEBUG_FS
static struct resource __devinitdata ab8500_debug_resources[] = {
{
.name = "IRQ_FIRST",
.start = AB8500_INT_MAIN_EXT_CH_NOT_OK,
.end = AB8500_INT_MAIN_EXT_CH_NOT_OK,
.flags = IORESOURCE_IRQ,
},
{
.name = "IRQ_LAST",
.start = AB8500_INT_XTAL32K_KO,
.end = AB8500_INT_XTAL32K_KO,
.flags = IORESOURCE_IRQ,
},
};
#endif
static struct resource __devinitdata ab8500_usb_resources[] = {
{
.name = "ID_WAKEUP_R",
.start = AB8500_INT_ID_WAKEUP_R,
.end = AB8500_INT_ID_WAKEUP_R,
.flags = IORESOURCE_IRQ,
},
{
.name = "ID_WAKEUP_F",
.start = AB8500_INT_ID_WAKEUP_F,
.end = AB8500_INT_ID_WAKEUP_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "VBUS_DET_F",
.start = AB8500_INT_VBUS_DET_F,
.end = AB8500_INT_VBUS_DET_F,
.flags = IORESOURCE_IRQ,
},
{
.name = "VBUS_DET_R",
.start = AB8500_INT_VBUS_DET_R,
.end = AB8500_INT_VBUS_DET_R,
.flags = IORESOURCE_IRQ,
},
{
.name = "USB_LINK_STATUS",
.start = AB8500_INT_USB_LINK_STATUS,
.end = AB8500_INT_USB_LINK_STATUS,
.flags = IORESOURCE_IRQ,
},
{
.name = "USB_ADP_PROBE_PLUG",
.start = AB8500_INT_ADP_PROBE_PLUG,
.end = AB8500_INT_ADP_PROBE_PLUG,
.flags = IORESOURCE_IRQ,
},
{
.name = "USB_ADP_PROBE_UNPLUG",
.start = AB8500_INT_ADP_PROBE_UNPLUG,
.end = AB8500_INT_ADP_PROBE_UNPLUG,
.flags = IORESOURCE_IRQ,
},
};
static struct resource __devinitdata ab8500_temp_resources[] = {
{
.name = "AB8500_TEMP_WARM",
.start = AB8500_INT_TEMP_WARM,
.end = AB8500_INT_TEMP_WARM,
.flags = IORESOURCE_IRQ,
},
};
static struct mfd_cell __devinitdata abx500_common_devs[] = {
#ifdef CONFIG_DEBUG_FS
{
.name = "ab8500-debug",
.num_resources = ARRAY_SIZE(ab8500_debug_resources),
.resources = ab8500_debug_resources,
},
#endif
{
.name = "ab8500-sysctrl",
},
{
.name = "ab8500-regulator",
},
{
.name = "ab8500-gpadc",
.num_resources = ARRAY_SIZE(ab8500_gpadc_resources),
.resources = ab8500_gpadc_resources,
},
{
.name = "ab8500-rtc",
.num_resources = ARRAY_SIZE(ab8500_rtc_resources),
.resources = ab8500_rtc_resources,
},
{
.name = "ab8500-charger",
.num_resources = ARRAY_SIZE(ab8500_charger_resources),
.resources = ab8500_charger_resources,
},
{
.name = "ab8500-btemp",
.num_resources = ARRAY_SIZE(ab8500_btemp_resources),
.resources = ab8500_btemp_resources,
},
{
.name = "ab8500-fg",
.num_resources = ARRAY_SIZE(ab8500_fg_resources),
.resources = ab8500_fg_resources,
},
{
.name = "ab8500-chargalg",
.num_resources = ARRAY_SIZE(ab8500_chargalg_resources),
.resources = ab8500_chargalg_resources,
},
{
.name = "ab8500-acc-det",
.num_resources = ARRAY_SIZE(ab8500_av_acc_detect_resources),
.resources = ab8500_av_acc_detect_resources,
},
{
.name = "ab8500-codec",
},
{
.name = "ab8500-poweron-key",
.num_resources = ARRAY_SIZE(ab8500_poweronkey_db_resources),
.resources = ab8500_poweronkey_db_resources,
},
{
.name = "ab8500-pwm",
.id = 1,
},
{
.name = "ab8500-pwm",
.id = 2,
},
{
.name = "ab8500-pwm",
.id = 3,
},
{ .name = "ab8500-leds", },
{
.name = "ab8500-denc",
},
{
.name = "ab8500-temp",
.num_resources = ARRAY_SIZE(ab8500_temp_resources),
.resources = ab8500_temp_resources,
},
};
static struct mfd_cell __devinitdata ab8500_devs[] = {
{
.name = "ab8500-gpio",
.num_resources = ARRAY_SIZE(ab8500_gpio_resources),
.resources = ab8500_gpio_resources,
},
{
.name = "ab8500-usb",
.num_resources = ARRAY_SIZE(ab8500_usb_resources),
.resources = ab8500_usb_resources,
},
};
static struct mfd_cell __devinitdata ab9540_devs[] = {
{
.name = "ab8500-gpio",
.num_resources = ARRAY_SIZE(ab9540_gpio_resources),
.resources = ab9540_gpio_resources,
},
{
.name = "ab9540-usb",
.num_resources = ARRAY_SIZE(ab8500_usb_resources),
.resources = ab8500_usb_resources,
},
};
static ssize_t show_chip_id(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ab8500 *ab8500;
ab8500 = dev_get_drvdata(dev);
return sprintf(buf, "%#x\n", ab8500 ? ab8500->chip_id : -EINVAL);
}
/*
* ab8500 has switched off due to (SWITCH_OFF_STATUS):
* 0x01 Swoff bit programming
* 0x02 Thermal protection activation
* 0x04 Vbat lower then BattOk falling threshold
* 0x08 Watchdog expired
* 0x10 Non presence of 32kHz clock
* 0x20 Battery level lower than power on reset threshold
* 0x40 Power on key 1 pressed longer than 10 seconds
* 0x80 DB8500 thermal shutdown
*/
static ssize_t show_switch_off_status(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
u8 value;
struct ab8500 *ab8500;
ab8500 = dev_get_drvdata(dev);
ret = get_register_interruptible(ab8500, AB8500_RTC,
AB8500_SWITCH_OFF_STATUS, &value);
if (ret < 0)
return ret;
return sprintf(buf, "%#x\n", value);
}
/*
* ab8500 has turned on due to (TURN_ON_STATUS):
* 0x01 PORnVbat
* 0x02 PonKey1dbF
* 0x04 PonKey2dbF
* 0x08 RTCAlarm
* 0x10 MainChDet
* 0x20 VbusDet
* 0x40 UsbIDDetect
* 0x80 Reserved
*/
static ssize_t show_turn_on_status(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
u8 value;
struct ab8500 *ab8500;
ab8500 = dev_get_drvdata(dev);
ret = get_register_interruptible(ab8500, AB8500_SYS_CTRL1_BLOCK,
AB8500_TURN_ON_STATUS, &value);
if (ret < 0)
return ret;
return sprintf(buf, "%#x\n", value);
}
static ssize_t show_ab9540_dbbrstn(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct ab8500 *ab8500;
int ret;
u8 value;
ab8500 = dev_get_drvdata(dev);
ret = get_register_interruptible(ab8500, AB8500_REGU_CTRL2,
AB9540_MODEM_CTRL2_REG, &value);
if (ret < 0)
return ret;
return sprintf(buf, "%d\n",
(value & AB9540_MODEM_CTRL2_SWDBBRSTN_BIT) ? 1 : 0);
}
static ssize_t store_ab9540_dbbrstn(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
struct ab8500 *ab8500;
int ret = count;
int err;
u8 bitvalues;
ab8500 = dev_get_drvdata(dev);
if (count > 0) {
switch (buf[0]) {
case '0':
bitvalues = 0;
break;
case '1':
bitvalues = AB9540_MODEM_CTRL2_SWDBBRSTN_BIT;
break;
default:
goto exit;
}
err = mask_and_set_register_interruptible(ab8500,
AB8500_REGU_CTRL2, AB9540_MODEM_CTRL2_REG,
AB9540_MODEM_CTRL2_SWDBBRSTN_BIT, bitvalues);
if (err)
dev_info(ab8500->dev,
"Failed to set DBBRSTN %c, err %#x\n",
buf[0], err);
}
exit:
return ret;
}
static DEVICE_ATTR(chip_id, S_IRUGO, show_chip_id, NULL);
static DEVICE_ATTR(switch_off_status, S_IRUGO, show_switch_off_status, NULL);
static DEVICE_ATTR(turn_on_status, S_IRUGO, show_turn_on_status, NULL);
static DEVICE_ATTR(dbbrstn, S_IRUGO | S_IWUSR,
show_ab9540_dbbrstn, store_ab9540_dbbrstn);
static struct attribute *ab8500_sysfs_entries[] = {
&dev_attr_chip_id.attr,
&dev_attr_switch_off_status.attr,
&dev_attr_turn_on_status.attr,
NULL,
};
static struct attribute *ab9540_sysfs_entries[] = {
&dev_attr_chip_id.attr,
&dev_attr_switch_off_status.attr,
&dev_attr_turn_on_status.attr,
&dev_attr_dbbrstn.attr,
NULL,
};
static struct attribute_group ab8500_attr_group = {
.attrs = ab8500_sysfs_entries,
};
static struct attribute_group ab9540_attr_group = {
.attrs = ab9540_sysfs_entries,
};
int __devinit ab8500_init(struct ab8500 *ab8500, enum ab8500_version version)
{
struct ab8500_platform_data *plat = dev_get_platdata(ab8500->dev);
int ret;
int i;
u8 value;
if (plat)
ab8500->irq_base = plat->irq_base;
mutex_init(&ab8500->lock);
mutex_init(&ab8500->irq_lock);
if (version != AB8500_VERSION_UNDEFINED)
ab8500->version = version;
else {
ret = get_register_interruptible(ab8500, AB8500_MISC,
AB8500_IC_NAME_REG, &value);
if (ret < 0)
return ret;
ab8500->version = value;
}
ret = get_register_interruptible(ab8500, AB8500_MISC,
AB8500_REV_REG, &value);
if (ret < 0)
return ret;
ab8500->chip_id = value;
dev_info(ab8500->dev, "detected chip, %s rev. %1x.%1x\n",
ab8500_version_str[ab8500->version],
ab8500->chip_id >> 4,
ab8500->chip_id & 0x0F);
/* Configure AB8500 or AB9540 IRQ */
if (is_ab9540(ab8500) || is_ab8505(ab8500)) {
ab8500->mask_size = AB9540_NUM_IRQ_REGS;
ab8500->irq_reg_offset = ab9540_irq_regoffset;
} else {
ab8500->mask_size = AB8500_NUM_IRQ_REGS;
ab8500->irq_reg_offset = ab8500_irq_regoffset;
}
ab8500->mask = kzalloc(ab8500->mask_size, GFP_KERNEL);
if (!ab8500->mask)
return -ENOMEM;
ab8500->oldmask = kzalloc(ab8500->mask_size, GFP_KERNEL);
if (!ab8500->oldmask) {
ret = -ENOMEM;
goto out_freemask;
}
/*
* ab8500 has switched off due to (SWITCH_OFF_STATUS):
* 0x01 Swoff bit programming
* 0x02 Thermal protection activation
* 0x04 Vbat lower then BattOk falling threshold
* 0x08 Watchdog expired
* 0x10 Non presence of 32kHz clock
* 0x20 Battery level lower than power on reset threshold
* 0x40 Power on key 1 pressed longer than 10 seconds
* 0x80 DB8500 thermal shutdown
*/
ret = get_register_interruptible(ab8500, AB8500_RTC,
AB8500_SWITCH_OFF_STATUS, &value);
if (ret < 0)
return ret;
dev_info(ab8500->dev, "switch off status: %#x", value);
if (plat && plat->init)
plat->init(ab8500);
/* Clear and mask all interrupts */
for (i = 0; i < ab8500->mask_size; i++) {
/*
* Interrupt register 12 doesn't exist prior to AB8500 version
* 2.0
*/
if (ab8500->irq_reg_offset[i] == 11 &&
is_ab8500_1p1_or_earlier(ab8500))
continue;
get_register_interruptible(ab8500, AB8500_INTERRUPT,
AB8500_IT_LATCH1_REG + ab8500->irq_reg_offset[i],
&value);
set_register_interruptible(ab8500, AB8500_INTERRUPT,
AB8500_IT_MASK1_REG + ab8500->irq_reg_offset[i], 0xff);
}
ret = abx500_register_ops(ab8500->dev, &ab8500_ops);
if (ret)
goto out_freeoldmask;
for (i = 0; i < ab8500->mask_size; i++)
ab8500->mask[i] = ab8500->oldmask[i] = 0xff;
if (ab8500->irq_base) {
ret = ab8500_irq_init(ab8500);
if (ret)
goto out_freeoldmask;
ret = request_threaded_irq(ab8500->irq, NULL, ab8500_irq,
IRQF_ONESHOT | IRQF_NO_SUSPEND,
"ab8500", ab8500);
if (ret)
goto out_removeirq;
}
ret = mfd_add_devices(ab8500->dev, 0, abx500_common_devs,
ARRAY_SIZE(abx500_common_devs), NULL,
ab8500->irq_base);
if (ret)
goto out_freeirq;
if (is_ab9540(ab8500))
ret = mfd_add_devices(ab8500->dev, 0, ab9540_devs,
ARRAY_SIZE(ab9540_devs), NULL,
ab8500->irq_base);
else
ret = mfd_add_devices(ab8500->dev, 0, ab8500_devs,
ARRAY_SIZE(ab9540_devs), NULL,
ab8500->irq_base);
if (ret)
goto out_freeirq;
if (is_ab9540(ab8500))
ret = sysfs_create_group(&ab8500->dev->kobj,
&ab9540_attr_group);
else
ret = sysfs_create_group(&ab8500->dev->kobj,
&ab8500_attr_group);
if (ret)
dev_err(ab8500->dev, "error creating sysfs entries\n");
else
return ret;
out_freeirq:
if (ab8500->irq_base)
free_irq(ab8500->irq, ab8500);
out_removeirq:
if (ab8500->irq_base)
ab8500_irq_remove(ab8500);
out_freeoldmask:
kfree(ab8500->oldmask);
out_freemask:
kfree(ab8500->mask);
return ret;
}
int __devexit ab8500_exit(struct ab8500 *ab8500)
{
if (is_ab9540(ab8500))
sysfs_remove_group(&ab8500->dev->kobj, &ab9540_attr_group);
else
sysfs_remove_group(&ab8500->dev->kobj, &ab8500_attr_group);
mfd_remove_devices(ab8500->dev);
if (ab8500->irq_base) {
free_irq(ab8500->irq, ab8500);
ab8500_irq_remove(ab8500);
}
kfree(ab8500->oldmask);
kfree(ab8500->mask);
return 0;
}
MODULE_AUTHOR("Mattias Wallin, Srinidhi Kasagar, Rabin Vincent");
MODULE_DESCRIPTION("AB8500 MFD core");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
utuu/kernel_huawei | drivers/isdn/hardware/eicon/os_4bri.c | 4790 | 29089 | /* $Id: os_4bri.c,v 1.28.4.4 2005/02/11 19:40:25 armin Exp $ */
#include "platform.h"
#include "debuglib.h"
#include "cardtype.h"
#include "pc.h"
#include "pr_pc.h"
#include "di_defs.h"
#include "dsp_defs.h"
#include "di.h"
#include "io.h"
#include "xdi_msg.h"
#include "xdi_adapter.h"
#include "os_4bri.h"
#include "diva_pci.h"
#include "mi_pc.h"
#include "dsrv4bri.h"
#include "helpers.h"
static void *diva_xdiLoadFileFile = NULL;
static dword diva_xdiLoadFileLength = 0;
/*
** IMPORTS
*/
extern void prepare_qBri_functions(PISDN_ADAPTER IoAdapter);
extern void prepare_qBri2_functions(PISDN_ADAPTER IoAdapter);
extern void diva_xdi_display_adapter_features(int card);
extern void diva_add_slave_adapter(diva_os_xdi_adapter_t * a);
extern int qBri_FPGA_download(PISDN_ADAPTER IoAdapter);
extern void start_qBri_hardware(PISDN_ADAPTER IoAdapter);
extern int diva_card_read_xlog(diva_os_xdi_adapter_t * a);
/*
** LOCALS
*/
static unsigned long _4bri_bar_length[4] = {
0x100,
0x100, /* I/O */
MQ_MEMORY_SIZE,
0x2000
};
static unsigned long _4bri_v2_bar_length[4] = {
0x100,
0x100, /* I/O */
MQ2_MEMORY_SIZE,
0x10000
};
static unsigned long _4bri_v2_bri_bar_length[4] = {
0x100,
0x100, /* I/O */
BRI2_MEMORY_SIZE,
0x10000
};
static int diva_4bri_cleanup_adapter(diva_os_xdi_adapter_t * a);
static int _4bri_get_serial_number(diva_os_xdi_adapter_t * a);
static int diva_4bri_cmd_card_proc(struct _diva_os_xdi_adapter *a,
diva_xdi_um_cfg_cmd_t * cmd,
int length);
static int diva_4bri_cleanup_slave_adapters(diva_os_xdi_adapter_t * a);
static int diva_4bri_write_fpga_image(diva_os_xdi_adapter_t * a,
byte * data, dword length);
static int diva_4bri_reset_adapter(PISDN_ADAPTER IoAdapter);
static int diva_4bri_write_sdram_block(PISDN_ADAPTER IoAdapter,
dword address,
const byte * data,
dword length, dword limit);
static int diva_4bri_start_adapter(PISDN_ADAPTER IoAdapter,
dword start_address, dword features);
static int check_qBri_interrupt(PISDN_ADAPTER IoAdapter);
static int diva_4bri_stop_adapter(diva_os_xdi_adapter_t * a);
static int _4bri_is_rev_2_card(int card_ordinal)
{
switch (card_ordinal) {
case CARDTYPE_DIVASRV_Q_8M_V2_PCI:
case CARDTYPE_DIVASRV_VOICE_Q_8M_V2_PCI:
case CARDTYPE_DIVASRV_B_2M_V2_PCI:
case CARDTYPE_DIVASRV_B_2F_PCI:
case CARDTYPE_DIVASRV_VOICE_B_2M_V2_PCI:
return (1);
}
return (0);
}
static int _4bri_is_rev_2_bri_card(int card_ordinal)
{
switch (card_ordinal) {
case CARDTYPE_DIVASRV_B_2M_V2_PCI:
case CARDTYPE_DIVASRV_B_2F_PCI:
case CARDTYPE_DIVASRV_VOICE_B_2M_V2_PCI:
return (1);
}
return (0);
}
static void diva_4bri_set_addresses(diva_os_xdi_adapter_t *a)
{
dword offset = a->resources.pci.qoffset;
dword c_offset = offset * a->xdi_adapter.ControllerNumber;
a->resources.pci.mem_type_id[MEM_TYPE_RAM] = 2;
a->resources.pci.mem_type_id[MEM_TYPE_ADDRESS] = 2;
a->resources.pci.mem_type_id[MEM_TYPE_CONTROL] = 2;
a->resources.pci.mem_type_id[MEM_TYPE_RESET] = 0;
a->resources.pci.mem_type_id[MEM_TYPE_CTLREG] = 3;
a->resources.pci.mem_type_id[MEM_TYPE_PROM] = 0;
/*
Set up hardware related pointers
*/
a->xdi_adapter.Address = a->resources.pci.addr[2]; /* BAR2 SDRAM */
a->xdi_adapter.Address += c_offset;
a->xdi_adapter.Control = a->resources.pci.addr[2]; /* BAR2 SDRAM */
a->xdi_adapter.ram = a->resources.pci.addr[2]; /* BAR2 SDRAM */
a->xdi_adapter.ram += c_offset + (offset - MQ_SHARED_RAM_SIZE);
a->xdi_adapter.reset = a->resources.pci.addr[0]; /* BAR0 CONFIG */
/*
ctlReg contains the register address for the MIPS CPU reset control
*/
a->xdi_adapter.ctlReg = a->resources.pci.addr[3]; /* BAR3 CNTRL */
/*
prom contains the register address for FPGA and EEPROM programming
*/
a->xdi_adapter.prom = &a->xdi_adapter.reset[0x6E];
}
/*
** BAR0 - MEM - 0x100 - CONFIG MEM
** BAR1 - I/O - 0x100 - UNUSED
** BAR2 - MEM - MQ_MEMORY_SIZE (MQ2_MEMORY_SIZE on Rev.2) - SDRAM
** BAR3 - MEM - 0x2000 (0x10000 on Rev.2) - CNTRL
**
** Called by master adapter, that will initialize and add slave adapters
*/
int diva_4bri_init_card(diva_os_xdi_adapter_t * a)
{
int bar, i;
byte __iomem *p;
PADAPTER_LIST_ENTRY quadro_list;
diva_os_xdi_adapter_t *diva_current;
diva_os_xdi_adapter_t *adapter_list[4];
PISDN_ADAPTER Slave;
unsigned long bar_length[ARRAY_SIZE(_4bri_bar_length)];
int v2 = _4bri_is_rev_2_card(a->CardOrdinal);
int tasks = _4bri_is_rev_2_bri_card(a->CardOrdinal) ? 1 : MQ_INSTANCE_COUNT;
int factor = (tasks == 1) ? 1 : 2;
if (v2) {
if (_4bri_is_rev_2_bri_card(a->CardOrdinal)) {
memcpy(bar_length, _4bri_v2_bri_bar_length,
sizeof(bar_length));
} else {
memcpy(bar_length, _4bri_v2_bar_length,
sizeof(bar_length));
}
} else {
memcpy(bar_length, _4bri_bar_length, sizeof(bar_length));
}
DBG_TRC(("SDRAM_LENGTH=%08x, tasks=%d, factor=%d",
bar_length[2], tasks, factor))
/*
Get Serial Number
The serial number of 4BRI is accessible in accordance with PCI spec
via command register located in configuration space, also we do not
have to map any BAR before we can access it
*/
if (!_4bri_get_serial_number(a)) {
DBG_ERR(("A: 4BRI can't get Serial Number"))
diva_4bri_cleanup_adapter(a);
return (-1);
}
/*
Set properties
*/
a->xdi_adapter.Properties = CardProperties[a->CardOrdinal];
DBG_LOG(("Load %s, SN:%ld, bus:%02x, func:%02x",
a->xdi_adapter.Properties.Name,
a->xdi_adapter.serialNo,
a->resources.pci.bus, a->resources.pci.func))
/*
First initialization step: get and check hardware resoures.
Do not map resources and do not access card at this step
*/
for (bar = 0; bar < 4; bar++) {
a->resources.pci.bar[bar] =
divasa_get_pci_bar(a->resources.pci.bus,
a->resources.pci.func, bar,
a->resources.pci.hdev);
if (!a->resources.pci.bar[bar]
|| (a->resources.pci.bar[bar] == 0xFFFFFFF0)) {
DBG_ERR(
("A: invalid bar[%d]=%08x", bar,
a->resources.pci.bar[bar]))
return (-1);
}
}
a->resources.pci.irq =
(byte) divasa_get_pci_irq(a->resources.pci.bus,
a->resources.pci.func,
a->resources.pci.hdev);
if (!a->resources.pci.irq) {
DBG_ERR(("A: invalid irq"));
return (-1);
}
a->xdi_adapter.sdram_bar = a->resources.pci.bar[2];
/*
Map all MEMORY BAR's
*/
for (bar = 0; bar < 4; bar++) {
if (bar != 1) { /* ignore I/O */
a->resources.pci.addr[bar] =
divasa_remap_pci_bar(a, bar, a->resources.pci.bar[bar],
bar_length[bar]);
if (!a->resources.pci.addr[bar]) {
DBG_ERR(("A: 4BRI: can't map bar[%d]", bar))
diva_4bri_cleanup_adapter(a);
return (-1);
}
}
}
/*
Register I/O port
*/
sprintf(&a->port_name[0], "DIVA 4BRI %ld", (long) a->xdi_adapter.serialNo);
if (diva_os_register_io_port(a, 1, a->resources.pci.bar[1],
bar_length[1], &a->port_name[0], 1)) {
DBG_ERR(("A: 4BRI: can't register bar[1]"))
diva_4bri_cleanup_adapter(a);
return (-1);
}
a->resources.pci.addr[1] =
(void *) (unsigned long) a->resources.pci.bar[1];
/*
Set cleanup pointer for base adapter only, so slave adapter
will be unable to get cleanup
*/
a->interface.cleanup_adapter_proc = diva_4bri_cleanup_adapter;
/*
Create slave adapters
*/
if (tasks > 1) {
if (!(a->slave_adapters[0] =
(diva_os_xdi_adapter_t *) diva_os_malloc(0, sizeof(*a))))
{
diva_4bri_cleanup_adapter(a);
return (-1);
}
if (!(a->slave_adapters[1] =
(diva_os_xdi_adapter_t *) diva_os_malloc(0, sizeof(*a))))
{
diva_os_free(0, a->slave_adapters[0]);
a->slave_adapters[0] = NULL;
diva_4bri_cleanup_adapter(a);
return (-1);
}
if (!(a->slave_adapters[2] =
(diva_os_xdi_adapter_t *) diva_os_malloc(0, sizeof(*a))))
{
diva_os_free(0, a->slave_adapters[0]);
diva_os_free(0, a->slave_adapters[1]);
a->slave_adapters[0] = NULL;
a->slave_adapters[1] = NULL;
diva_4bri_cleanup_adapter(a);
return (-1);
}
memset(a->slave_adapters[0], 0x00, sizeof(*a));
memset(a->slave_adapters[1], 0x00, sizeof(*a));
memset(a->slave_adapters[2], 0x00, sizeof(*a));
}
adapter_list[0] = a;
adapter_list[1] = a->slave_adapters[0];
adapter_list[2] = a->slave_adapters[1];
adapter_list[3] = a->slave_adapters[2];
/*
Allocate slave list
*/
quadro_list =
(PADAPTER_LIST_ENTRY) diva_os_malloc(0, sizeof(*quadro_list));
if (!(a->slave_list = quadro_list)) {
for (i = 0; i < (tasks - 1); i++) {
diva_os_free(0, a->slave_adapters[i]);
a->slave_adapters[i] = NULL;
}
diva_4bri_cleanup_adapter(a);
return (-1);
}
memset(quadro_list, 0x00, sizeof(*quadro_list));
/*
Set interfaces
*/
a->xdi_adapter.QuadroList = quadro_list;
for (i = 0; i < tasks; i++) {
adapter_list[i]->xdi_adapter.ControllerNumber = i;
adapter_list[i]->xdi_adapter.tasks = tasks;
quadro_list->QuadroAdapter[i] =
&adapter_list[i]->xdi_adapter;
}
for (i = 0; i < tasks; i++) {
diva_current = adapter_list[i];
diva_current->dsp_mask = 0x00000003;
diva_current->xdi_adapter.a.io =
&diva_current->xdi_adapter;
diva_current->xdi_adapter.DIRequest = request;
diva_current->interface.cmd_proc = diva_4bri_cmd_card_proc;
diva_current->xdi_adapter.Properties =
CardProperties[a->CardOrdinal];
diva_current->CardOrdinal = a->CardOrdinal;
diva_current->xdi_adapter.Channels =
CardProperties[a->CardOrdinal].Channels;
diva_current->xdi_adapter.e_max =
CardProperties[a->CardOrdinal].E_info;
diva_current->xdi_adapter.e_tbl =
diva_os_malloc(0,
diva_current->xdi_adapter.e_max *
sizeof(E_INFO));
if (!diva_current->xdi_adapter.e_tbl) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
memset(diva_current->xdi_adapter.e_tbl, 0x00,
diva_current->xdi_adapter.e_max * sizeof(E_INFO));
if (diva_os_initialize_spin_lock(&diva_current->xdi_adapter.isr_spin_lock, "isr")) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
if (diva_os_initialize_spin_lock(&diva_current->xdi_adapter.data_spin_lock, "data")) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
strcpy(diva_current->xdi_adapter.req_soft_isr. dpc_thread_name, "kdivas4brid");
if (diva_os_initialize_soft_isr (&diva_current->xdi_adapter.req_soft_isr, DIDpcRoutine,
&diva_current->xdi_adapter)) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
/*
Do not initialize second DPC - only one thread will be created
*/
diva_current->xdi_adapter.isr_soft_isr.object =
diva_current->xdi_adapter.req_soft_isr.object;
}
if (v2) {
prepare_qBri2_functions(&a->xdi_adapter);
} else {
prepare_qBri_functions(&a->xdi_adapter);
}
for (i = 0; i < tasks; i++) {
diva_current = adapter_list[i];
if (i)
memcpy(&diva_current->resources, &a->resources, sizeof(divas_card_resources_t));
diva_current->resources.pci.qoffset = (a->xdi_adapter.MemorySize >> factor);
}
/*
Set up hardware related pointers
*/
a->xdi_adapter.cfg = (void *) (unsigned long) a->resources.pci.bar[0]; /* BAR0 CONFIG */
a->xdi_adapter.port = (void *) (unsigned long) a->resources.pci.bar[1]; /* BAR1 */
a->xdi_adapter.ctlReg = (void *) (unsigned long) a->resources.pci.bar[3]; /* BAR3 CNTRL */
for (i = 0; i < tasks; i++) {
diva_current = adapter_list[i];
diva_4bri_set_addresses(diva_current);
Slave = a->xdi_adapter.QuadroList->QuadroAdapter[i];
Slave->MultiMaster = &a->xdi_adapter;
Slave->sdram_bar = a->xdi_adapter.sdram_bar;
if (i) {
Slave->serialNo = ((dword) (Slave->ControllerNumber << 24)) |
a->xdi_adapter.serialNo;
Slave->cardType = a->xdi_adapter.cardType;
}
}
/*
reset contains the base address for the PLX 9054 register set
*/
p = DIVA_OS_MEM_ATTACH_RESET(&a->xdi_adapter);
WRITE_BYTE(&p[PLX9054_INTCSR], 0x00); /* disable PCI interrupts */
DIVA_OS_MEM_DETACH_RESET(&a->xdi_adapter, p);
/*
Set IRQ handler
*/
a->xdi_adapter.irq_info.irq_nr = a->resources.pci.irq;
sprintf(a->xdi_adapter.irq_info.irq_name, "DIVA 4BRI %ld",
(long) a->xdi_adapter.serialNo);
if (diva_os_register_irq(a, a->xdi_adapter.irq_info.irq_nr,
a->xdi_adapter.irq_info.irq_name)) {
diva_4bri_cleanup_slave_adapters(a);
diva_4bri_cleanup_adapter(a);
for (i = 1; i < (tasks - 1); i++) {
diva_os_free(0, adapter_list[i]);
}
return (-1);
}
a->xdi_adapter.irq_info.registered = 1;
/*
Add three slave adapters
*/
if (tasks > 1) {
diva_add_slave_adapter(adapter_list[1]);
diva_add_slave_adapter(adapter_list[2]);
diva_add_slave_adapter(adapter_list[3]);
}
diva_log_info("%s IRQ:%d SerNo:%d", a->xdi_adapter.Properties.Name,
a->resources.pci.irq, a->xdi_adapter.serialNo);
return (0);
}
/*
** Cleanup function will be called for master adapter only
** this is guaranteed by design: cleanup callback is set
** by master adapter only
*/
static int diva_4bri_cleanup_adapter(diva_os_xdi_adapter_t * a)
{
int bar;
/*
Stop adapter if running
*/
if (a->xdi_adapter.Initialized) {
diva_4bri_stop_adapter(a);
}
/*
Remove IRQ handler
*/
if (a->xdi_adapter.irq_info.registered) {
diva_os_remove_irq(a, a->xdi_adapter.irq_info.irq_nr);
}
a->xdi_adapter.irq_info.registered = 0;
/*
Free DPC's and spin locks on all adapters
*/
diva_4bri_cleanup_slave_adapters(a);
/*
Unmap all BARS
*/
for (bar = 0; bar < 4; bar++) {
if (bar != 1) {
if (a->resources.pci.bar[bar]
&& a->resources.pci.addr[bar]) {
divasa_unmap_pci_bar(a->resources.pci.addr[bar]);
a->resources.pci.bar[bar] = 0;
a->resources.pci.addr[bar] = NULL;
}
}
}
/*
Unregister I/O
*/
if (a->resources.pci.bar[1] && a->resources.pci.addr[1]) {
diva_os_register_io_port(a, 0, a->resources.pci.bar[1],
_4bri_is_rev_2_card(a->
CardOrdinal) ?
_4bri_v2_bar_length[1] :
_4bri_bar_length[1],
&a->port_name[0], 1);
a->resources.pci.bar[1] = 0;
a->resources.pci.addr[1] = NULL;
}
if (a->slave_list) {
diva_os_free(0, a->slave_list);
a->slave_list = NULL;
}
return (0);
}
static int _4bri_get_serial_number(diva_os_xdi_adapter_t * a)
{
dword data[64];
dword serNo;
word addr, status, i, j;
byte Bus, Slot;
void *hdev;
Bus = a->resources.pci.bus;
Slot = a->resources.pci.func;
hdev = a->resources.pci.hdev;
for (i = 0; i < 64; ++i) {
addr = i * 4;
for (j = 0; j < 5; ++j) {
PCIwrite(Bus, Slot, 0x4E, &addr, sizeof(addr),
hdev);
diva_os_wait(1);
PCIread(Bus, Slot, 0x4E, &status, sizeof(status),
hdev);
if (status & 0x8000)
break;
}
if (j >= 5) {
DBG_ERR(("EEPROM[%d] read failed (0x%x)", i * 4, addr))
return (0);
}
PCIread(Bus, Slot, 0x50, &data[i], sizeof(data[i]), hdev);
}
DBG_BLK(((char *) &data[0], sizeof(data)))
serNo = data[32];
if (serNo == 0 || serNo == 0xffffffff)
serNo = data[63];
if (!serNo) {
DBG_LOG(("W: Serial Number == 0, create one serial number"));
serNo = a->resources.pci.bar[1] & 0xffff0000;
serNo |= a->resources.pci.bus << 8;
serNo |= a->resources.pci.func;
}
a->xdi_adapter.serialNo = serNo;
DBG_REG(("Serial No. : %ld", a->xdi_adapter.serialNo))
return (serNo);
}
/*
** Release resources of slave adapters
*/
static int diva_4bri_cleanup_slave_adapters(diva_os_xdi_adapter_t * a)
{
diva_os_xdi_adapter_t *adapter_list[4];
diva_os_xdi_adapter_t *diva_current;
int i;
adapter_list[0] = a;
adapter_list[1] = a->slave_adapters[0];
adapter_list[2] = a->slave_adapters[1];
adapter_list[3] = a->slave_adapters[2];
for (i = 0; i < a->xdi_adapter.tasks; i++) {
diva_current = adapter_list[i];
if (diva_current) {
diva_os_destroy_spin_lock(&diva_current->
xdi_adapter.
isr_spin_lock, "unload");
diva_os_destroy_spin_lock(&diva_current->
xdi_adapter.
data_spin_lock,
"unload");
diva_os_cancel_soft_isr(&diva_current->xdi_adapter.
req_soft_isr);
diva_os_cancel_soft_isr(&diva_current->xdi_adapter.
isr_soft_isr);
diva_os_remove_soft_isr(&diva_current->xdi_adapter.
req_soft_isr);
diva_current->xdi_adapter.isr_soft_isr.object = NULL;
if (diva_current->xdi_adapter.e_tbl) {
diva_os_free(0,
diva_current->xdi_adapter.
e_tbl);
}
diva_current->xdi_adapter.e_tbl = NULL;
diva_current->xdi_adapter.e_max = 0;
diva_current->xdi_adapter.e_count = 0;
}
}
return (0);
}
static int
diva_4bri_cmd_card_proc(struct _diva_os_xdi_adapter *a,
diva_xdi_um_cfg_cmd_t * cmd, int length)
{
int ret = -1;
if (cmd->adapter != a->controller) {
DBG_ERR(("A: 4bri_cmd, invalid controller=%d != %d",
cmd->adapter, a->controller))
return (-1);
}
switch (cmd->command) {
case DIVA_XDI_UM_CMD_GET_CARD_ORDINAL:
a->xdi_mbox.data_length = sizeof(dword);
a->xdi_mbox.data =
diva_os_malloc(0, a->xdi_mbox.data_length);
if (a->xdi_mbox.data) {
*(dword *) a->xdi_mbox.data =
(dword) a->CardOrdinal;
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
break;
case DIVA_XDI_UM_CMD_GET_SERIAL_NR:
a->xdi_mbox.data_length = sizeof(dword);
a->xdi_mbox.data =
diva_os_malloc(0, a->xdi_mbox.data_length);
if (a->xdi_mbox.data) {
*(dword *) a->xdi_mbox.data =
(dword) a->xdi_adapter.serialNo;
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
break;
case DIVA_XDI_UM_CMD_GET_PCI_HW_CONFIG:
if (!a->xdi_adapter.ControllerNumber) {
/*
Only master adapter can access hardware config
*/
a->xdi_mbox.data_length = sizeof(dword) * 9;
a->xdi_mbox.data =
diva_os_malloc(0, a->xdi_mbox.data_length);
if (a->xdi_mbox.data) {
int i;
dword *data = (dword *) a->xdi_mbox.data;
for (i = 0; i < 8; i++) {
*data++ = a->resources.pci.bar[i];
}
*data++ = (dword) a->resources.pci.irq;
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
}
break;
case DIVA_XDI_UM_CMD_GET_CARD_STATE:
if (!a->xdi_adapter.ControllerNumber) {
a->xdi_mbox.data_length = sizeof(dword);
a->xdi_mbox.data =
diva_os_malloc(0, a->xdi_mbox.data_length);
if (a->xdi_mbox.data) {
dword *data = (dword *) a->xdi_mbox.data;
if (!a->xdi_adapter.ram
|| !a->xdi_adapter.reset
|| !a->xdi_adapter.cfg) {
*data = 3;
} else if (a->xdi_adapter.trapped) {
*data = 2;
} else if (a->xdi_adapter.Initialized) {
*data = 1;
} else {
*data = 0;
}
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
}
break;
case DIVA_XDI_UM_CMD_WRITE_FPGA:
if (!a->xdi_adapter.ControllerNumber) {
ret =
diva_4bri_write_fpga_image(a,
(byte *) & cmd[1],
cmd->command_data.
write_fpga.
image_length);
}
break;
case DIVA_XDI_UM_CMD_RESET_ADAPTER:
if (!a->xdi_adapter.ControllerNumber) {
ret = diva_4bri_reset_adapter(&a->xdi_adapter);
}
break;
case DIVA_XDI_UM_CMD_WRITE_SDRAM_BLOCK:
if (!a->xdi_adapter.ControllerNumber) {
ret = diva_4bri_write_sdram_block(&a->xdi_adapter,
cmd->
command_data.
write_sdram.
offset,
(byte *) &
cmd[1],
cmd->
command_data.
write_sdram.
length,
a->xdi_adapter.
MemorySize);
}
break;
case DIVA_XDI_UM_CMD_START_ADAPTER:
if (!a->xdi_adapter.ControllerNumber) {
ret = diva_4bri_start_adapter(&a->xdi_adapter,
cmd->command_data.
start.offset,
cmd->command_data.
start.features);
}
break;
case DIVA_XDI_UM_CMD_SET_PROTOCOL_FEATURES:
if (!a->xdi_adapter.ControllerNumber) {
a->xdi_adapter.features =
cmd->command_data.features.features;
a->xdi_adapter.a.protocol_capabilities =
a->xdi_adapter.features;
DBG_TRC(("Set raw protocol features (%08x)",
a->xdi_adapter.features))
ret = 0;
}
break;
case DIVA_XDI_UM_CMD_STOP_ADAPTER:
if (!a->xdi_adapter.ControllerNumber) {
ret = diva_4bri_stop_adapter(a);
}
break;
case DIVA_XDI_UM_CMD_READ_XLOG_ENTRY:
ret = diva_card_read_xlog(a);
break;
case DIVA_XDI_UM_CMD_READ_SDRAM:
if (!a->xdi_adapter.ControllerNumber
&& a->xdi_adapter.Address) {
if (
(a->xdi_mbox.data_length =
cmd->command_data.read_sdram.length)) {
if (
(a->xdi_mbox.data_length +
cmd->command_data.read_sdram.offset) <
a->xdi_adapter.MemorySize) {
a->xdi_mbox.data =
diva_os_malloc(0,
a->xdi_mbox.
data_length);
if (a->xdi_mbox.data) {
byte __iomem *p = DIVA_OS_MEM_ATTACH_ADDRESS(&a->xdi_adapter);
byte __iomem *src = p;
byte *dst = a->xdi_mbox.data;
dword len = a->xdi_mbox.data_length;
src += cmd->command_data.read_sdram.offset;
while (len--) {
*dst++ = READ_BYTE(src++);
}
DIVA_OS_MEM_DETACH_ADDRESS(&a->xdi_adapter, p);
a->xdi_mbox.status = DIVA_XDI_MBOX_BUSY;
ret = 0;
}
}
}
}
break;
default:
DBG_ERR(("A: A(%d) invalid cmd=%d", a->controller,
cmd->command))
}
return (ret);
}
void *xdiLoadFile(char *FileName, dword *FileLength,
unsigned long lim)
{
void *ret = diva_xdiLoadFileFile;
if (FileLength) {
*FileLength = diva_xdiLoadFileLength;
}
diva_xdiLoadFileFile = NULL;
diva_xdiLoadFileLength = 0;
return (ret);
}
void diva_os_set_qBri_functions(PISDN_ADAPTER IoAdapter)
{
}
void diva_os_set_qBri2_functions(PISDN_ADAPTER IoAdapter)
{
}
static int
diva_4bri_write_fpga_image(diva_os_xdi_adapter_t * a, byte * data,
dword length)
{
int ret;
diva_xdiLoadFileFile = data;
diva_xdiLoadFileLength = length;
ret = qBri_FPGA_download(&a->xdi_adapter);
diva_xdiLoadFileFile = NULL;
diva_xdiLoadFileLength = 0;
return (ret ? 0 : -1);
}
static int diva_4bri_reset_adapter(PISDN_ADAPTER IoAdapter)
{
PISDN_ADAPTER Slave;
int i;
if (!IoAdapter->Address || !IoAdapter->reset) {
return (-1);
}
if (IoAdapter->Initialized) {
DBG_ERR(("A: A(%d) can't reset 4BRI adapter - please stop first",
IoAdapter->ANum))
return (-1);
}
/*
Forget all entities on all adapters
*/
for (i = 0; ((i < IoAdapter->tasks) && IoAdapter->QuadroList); i++) {
Slave = IoAdapter->QuadroList->QuadroAdapter[i];
Slave->e_count = 0;
if (Slave->e_tbl) {
memset(Slave->e_tbl, 0x00,
Slave->e_max * sizeof(E_INFO));
}
Slave->head = 0;
Slave->tail = 0;
Slave->assign = 0;
Slave->trapped = 0;
memset(&Slave->a.IdTable[0], 0x00,
sizeof(Slave->a.IdTable));
memset(&Slave->a.IdTypeTable[0], 0x00,
sizeof(Slave->a.IdTypeTable));
memset(&Slave->a.FlowControlIdTable[0], 0x00,
sizeof(Slave->a.FlowControlIdTable));
memset(&Slave->a.FlowControlSkipTable[0], 0x00,
sizeof(Slave->a.FlowControlSkipTable));
memset(&Slave->a.misc_flags_table[0], 0x00,
sizeof(Slave->a.misc_flags_table));
memset(&Slave->a.rx_stream[0], 0x00,
sizeof(Slave->a.rx_stream));
memset(&Slave->a.tx_stream[0], 0x00,
sizeof(Slave->a.tx_stream));
memset(&Slave->a.tx_pos[0], 0x00, sizeof(Slave->a.tx_pos));
memset(&Slave->a.rx_pos[0], 0x00, sizeof(Slave->a.rx_pos));
}
return (0);
}
static int
diva_4bri_write_sdram_block(PISDN_ADAPTER IoAdapter,
dword address,
const byte * data, dword length, dword limit)
{
byte __iomem *p = DIVA_OS_MEM_ATTACH_ADDRESS(IoAdapter);
byte __iomem *mem = p;
if (((address + length) >= limit) || !mem) {
DIVA_OS_MEM_DETACH_ADDRESS(IoAdapter, p);
DBG_ERR(("A: A(%d) write 4BRI address=0x%08lx",
IoAdapter->ANum, address + length))
return (-1);
}
mem += address;
while (length--) {
WRITE_BYTE(mem++, *data++);
}
DIVA_OS_MEM_DETACH_ADDRESS(IoAdapter, p);
return (0);
}
static int
diva_4bri_start_adapter(PISDN_ADAPTER IoAdapter,
dword start_address, dword features)
{
volatile word __iomem *signature;
int started = 0;
int i;
byte __iomem *p;
/*
start adapter
*/
start_qBri_hardware(IoAdapter);
p = DIVA_OS_MEM_ATTACH_RAM(IoAdapter);
/*
wait for signature in shared memory (max. 3 seconds)
*/
signature = (volatile word __iomem *) (&p[0x1E]);
for (i = 0; i < 300; ++i) {
diva_os_wait(10);
if (READ_WORD(&signature[0]) == 0x4447) {
DBG_TRC(("Protocol startup time %d.%02d seconds",
(i / 100), (i % 100)))
started = 1;
break;
}
}
for (i = 1; i < IoAdapter->tasks; i++) {
IoAdapter->QuadroList->QuadroAdapter[i]->features =
IoAdapter->features;
IoAdapter->QuadroList->QuadroAdapter[i]->a.
protocol_capabilities = IoAdapter->features;
}
if (!started) {
DBG_FTL(("%s: Adapter selftest failed, signature=%04x",
IoAdapter->Properties.Name,
READ_WORD(&signature[0])))
DIVA_OS_MEM_DETACH_RAM(IoAdapter, p);
(*(IoAdapter->trapFnc)) (IoAdapter);
IoAdapter->stop(IoAdapter);
return (-1);
}
DIVA_OS_MEM_DETACH_RAM(IoAdapter, p);
for (i = 0; i < IoAdapter->tasks; i++) {
IoAdapter->QuadroList->QuadroAdapter[i]->Initialized = 1;
IoAdapter->QuadroList->QuadroAdapter[i]->IrqCount = 0;
}
if (check_qBri_interrupt(IoAdapter)) {
DBG_ERR(("A: A(%d) interrupt test failed",
IoAdapter->ANum))
for (i = 0; i < IoAdapter->tasks; i++) {
IoAdapter->QuadroList->QuadroAdapter[i]->Initialized = 0;
}
IoAdapter->stop(IoAdapter);
return (-1);
}
IoAdapter->Properties.Features = (word) features;
diva_xdi_display_adapter_features(IoAdapter->ANum);
for (i = 0; i < IoAdapter->tasks; i++) {
DBG_LOG(("A(%d) %s adapter successfully started",
IoAdapter->QuadroList->QuadroAdapter[i]->ANum,
(IoAdapter->tasks == 1) ? "BRI 2.0" : "4BRI"))
diva_xdi_didd_register_adapter(IoAdapter->QuadroList->QuadroAdapter[i]->ANum);
IoAdapter->QuadroList->QuadroAdapter[i]->Properties.Features = (word) features;
}
return (0);
}
static int check_qBri_interrupt(PISDN_ADAPTER IoAdapter)
{
#ifdef SUPPORT_INTERRUPT_TEST_ON_4BRI
int i;
ADAPTER *a = &IoAdapter->a;
byte __iomem *p;
IoAdapter->IrqCount = 0;
if (IoAdapter->ControllerNumber > 0)
return (-1);
p = DIVA_OS_MEM_ATTACH_RESET(IoAdapter);
WRITE_BYTE(&p[PLX9054_INTCSR], PLX9054_INT_ENABLE);
DIVA_OS_MEM_DETACH_RESET(IoAdapter, p);
/*
interrupt test
*/
a->ReadyInt = 1;
a->ram_out(a, &PR_RAM->ReadyInt, 1);
for (i = 100; !IoAdapter->IrqCount && (i-- > 0); diva_os_wait(10));
return ((IoAdapter->IrqCount > 0) ? 0 : -1);
#else
dword volatile __iomem *qBriIrq;
byte __iomem *p;
/*
Reset on-board interrupt register
*/
IoAdapter->IrqCount = 0;
p = DIVA_OS_MEM_ATTACH_CTLREG(IoAdapter);
qBriIrq = (dword volatile __iomem *) (&p[_4bri_is_rev_2_card
(IoAdapter->
cardType) ? (MQ2_BREG_IRQ_TEST)
: (MQ_BREG_IRQ_TEST)]);
WRITE_DWORD(qBriIrq, MQ_IRQ_REQ_OFF);
DIVA_OS_MEM_DETACH_CTLREG(IoAdapter, p);
p = DIVA_OS_MEM_ATTACH_RESET(IoAdapter);
WRITE_BYTE(&p[PLX9054_INTCSR], PLX9054_INT_ENABLE);
DIVA_OS_MEM_DETACH_RESET(IoAdapter, p);
diva_os_wait(100);
return (0);
#endif /* SUPPORT_INTERRUPT_TEST_ON_4BRI */
}
static void diva_4bri_clear_interrupts(diva_os_xdi_adapter_t * a)
{
PISDN_ADAPTER IoAdapter = &a->xdi_adapter;
/*
clear any pending interrupt
*/
IoAdapter->disIrq(IoAdapter);
IoAdapter->tst_irq(&IoAdapter->a);
IoAdapter->clr_irq(&IoAdapter->a);
IoAdapter->tst_irq(&IoAdapter->a);
/*
kill pending dpcs
*/
diva_os_cancel_soft_isr(&IoAdapter->req_soft_isr);
diva_os_cancel_soft_isr(&IoAdapter->isr_soft_isr);
}
static int diva_4bri_stop_adapter(diva_os_xdi_adapter_t * a)
{
PISDN_ADAPTER IoAdapter = &a->xdi_adapter;
int i;
if (!IoAdapter->ram) {
return (-1);
}
if (!IoAdapter->Initialized) {
DBG_ERR(("A: A(%d) can't stop PRI adapter - not running",
IoAdapter->ANum))
return (-1); /* nothing to stop */
}
for (i = 0; i < IoAdapter->tasks; i++) {
IoAdapter->QuadroList->QuadroAdapter[i]->Initialized = 0;
}
/*
Disconnect Adapters from DIDD
*/
for (i = 0; i < IoAdapter->tasks; i++) {
diva_xdi_didd_remove_adapter(IoAdapter->QuadroList->QuadroAdapter[i]->ANum);
}
i = 100;
/*
Stop interrupts
*/
a->clear_interrupts_proc = diva_4bri_clear_interrupts;
IoAdapter->a.ReadyInt = 1;
IoAdapter->a.ram_inc(&IoAdapter->a, &PR_RAM->ReadyInt);
do {
diva_os_sleep(10);
} while (i-- && a->clear_interrupts_proc);
if (a->clear_interrupts_proc) {
diva_4bri_clear_interrupts(a);
a->clear_interrupts_proc = NULL;
DBG_ERR(("A: A(%d) no final interrupt from 4BRI adapter",
IoAdapter->ANum))
}
IoAdapter->a.ReadyInt = 0;
/*
Stop and reset adapter
*/
IoAdapter->stop(IoAdapter);
return (0);
}
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_klimtwifi | arch/arm/common/vic.c | 4790 | 11708 | /*
* linux/arch/arm/common/vic.c
*
* Copyright (C) 1999 - 2003 ARM Limited
* Copyright (C) 2000 Deep Blue Solutions Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This 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/export.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/irqdomain.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/syscore_ops.h>
#include <linux/device.h>
#include <linux/amba/bus.h>
#include <asm/exception.h>
#include <asm/mach/irq.h>
#include <asm/hardware/vic.h>
/**
* struct vic_device - VIC PM device
* @irq: The IRQ number for the base of the VIC.
* @base: The register base for the VIC.
* @resume_sources: A bitmask of interrupts for resume.
* @resume_irqs: The IRQs enabled for resume.
* @int_select: Save for VIC_INT_SELECT.
* @int_enable: Save for VIC_INT_ENABLE.
* @soft_int: Save for VIC_INT_SOFT.
* @protect: Save for VIC_PROTECT.
* @domain: The IRQ domain for the VIC.
*/
struct vic_device {
void __iomem *base;
int irq;
u32 resume_sources;
u32 resume_irqs;
u32 int_select;
u32 int_enable;
u32 soft_int;
u32 protect;
struct irq_domain *domain;
};
/* we cannot allocate memory when VICs are initially registered */
static struct vic_device vic_devices[CONFIG_ARM_VIC_NR];
static int vic_id;
/**
* vic_init2 - common initialisation code
* @base: Base of the VIC.
*
* Common initialisation code for registration
* and resume.
*/
static void vic_init2(void __iomem *base)
{
int i;
for (i = 0; i < 16; i++) {
void __iomem *reg = base + VIC_VECT_CNTL0 + (i * 4);
writel(VIC_VECT_CNTL_ENABLE | i, reg);
}
writel(32, base + VIC_PL190_DEF_VECT_ADDR);
}
#ifdef CONFIG_PM
static void resume_one_vic(struct vic_device *vic)
{
void __iomem *base = vic->base;
printk(KERN_DEBUG "%s: resuming vic at %p\n", __func__, base);
/* re-initialise static settings */
vic_init2(base);
writel(vic->int_select, base + VIC_INT_SELECT);
writel(vic->protect, base + VIC_PROTECT);
/* set the enabled ints and then clear the non-enabled */
writel(vic->int_enable, base + VIC_INT_ENABLE);
writel(~vic->int_enable, base + VIC_INT_ENABLE_CLEAR);
/* and the same for the soft-int register */
writel(vic->soft_int, base + VIC_INT_SOFT);
writel(~vic->soft_int, base + VIC_INT_SOFT_CLEAR);
}
static void vic_resume(void)
{
int id;
for (id = vic_id - 1; id >= 0; id--)
resume_one_vic(vic_devices + id);
}
static void suspend_one_vic(struct vic_device *vic)
{
void __iomem *base = vic->base;
printk(KERN_DEBUG "%s: suspending vic at %p\n", __func__, base);
vic->int_select = readl(base + VIC_INT_SELECT);
vic->int_enable = readl(base + VIC_INT_ENABLE);
vic->soft_int = readl(base + VIC_INT_SOFT);
vic->protect = readl(base + VIC_PROTECT);
/* set the interrupts (if any) that are used for
* resuming the system */
writel(vic->resume_irqs, base + VIC_INT_ENABLE);
writel(~vic->resume_irqs, base + VIC_INT_ENABLE_CLEAR);
}
static int vic_suspend(void)
{
int id;
for (id = 0; id < vic_id; id++)
suspend_one_vic(vic_devices + id);
return 0;
}
struct syscore_ops vic_syscore_ops = {
.suspend = vic_suspend,
.resume = vic_resume,
};
/**
* vic_pm_init - initicall to register VIC pm
*
* This is called via late_initcall() to register
* the resources for the VICs due to the early
* nature of the VIC's registration.
*/
static int __init vic_pm_init(void)
{
if (vic_id > 0)
register_syscore_ops(&vic_syscore_ops);
return 0;
}
late_initcall(vic_pm_init);
#endif /* CONFIG_PM */
/**
* vic_register() - Register a VIC.
* @base: The base address of the VIC.
* @irq: The base IRQ for the VIC.
* @resume_sources: bitmask of interrupts allowed for resume sources.
* @node: The device tree node associated with the VIC.
*
* Register the VIC with the system device tree so that it can be notified
* of suspend and resume requests and ensure that the correct actions are
* taken to re-instate the settings on resume.
*
* This also configures the IRQ domain for the VIC.
*/
static void __init vic_register(void __iomem *base, unsigned int irq,
u32 resume_sources, struct device_node *node)
{
struct vic_device *v;
if (vic_id >= ARRAY_SIZE(vic_devices)) {
printk(KERN_ERR "%s: too few VICs, increase CONFIG_ARM_VIC_NR\n", __func__);
return;
}
v = &vic_devices[vic_id];
v->base = base;
v->resume_sources = resume_sources;
v->irq = irq;
vic_id++;
v->domain = irq_domain_add_legacy(node, 32, irq, 0,
&irq_domain_simple_ops, v);
}
static void vic_ack_irq(struct irq_data *d)
{
void __iomem *base = irq_data_get_irq_chip_data(d);
unsigned int irq = d->hwirq;
writel(1 << irq, base + VIC_INT_ENABLE_CLEAR);
/* moreover, clear the soft-triggered, in case it was the reason */
writel(1 << irq, base + VIC_INT_SOFT_CLEAR);
}
static void vic_mask_irq(struct irq_data *d)
{
void __iomem *base = irq_data_get_irq_chip_data(d);
unsigned int irq = d->hwirq;
writel(1 << irq, base + VIC_INT_ENABLE_CLEAR);
}
static void vic_unmask_irq(struct irq_data *d)
{
void __iomem *base = irq_data_get_irq_chip_data(d);
unsigned int irq = d->hwirq;
writel(1 << irq, base + VIC_INT_ENABLE);
}
#if defined(CONFIG_PM)
static struct vic_device *vic_from_irq(unsigned int irq)
{
struct vic_device *v = vic_devices;
unsigned int base_irq = irq & ~31;
int id;
for (id = 0; id < vic_id; id++, v++) {
if (v->irq == base_irq)
return v;
}
return NULL;
}
static int vic_set_wake(struct irq_data *d, unsigned int on)
{
struct vic_device *v = vic_from_irq(d->irq);
unsigned int off = d->hwirq;
u32 bit = 1 << off;
if (!v)
return -EINVAL;
if (!(bit & v->resume_sources))
return -EINVAL;
if (on)
v->resume_irqs |= bit;
else
v->resume_irqs &= ~bit;
return 0;
}
#else
#define vic_set_wake NULL
#endif /* CONFIG_PM */
static struct irq_chip vic_chip = {
.name = "VIC",
.irq_ack = vic_ack_irq,
.irq_mask = vic_mask_irq,
.irq_unmask = vic_unmask_irq,
.irq_set_wake = vic_set_wake,
};
static void __init vic_disable(void __iomem *base)
{
writel(0, base + VIC_INT_SELECT);
writel(0, base + VIC_INT_ENABLE);
writel(~0, base + VIC_INT_ENABLE_CLEAR);
writel(0, base + VIC_ITCR);
writel(~0, base + VIC_INT_SOFT_CLEAR);
}
static void __init vic_clear_interrupts(void __iomem *base)
{
unsigned int i;
writel(0, base + VIC_PL190_VECT_ADDR);
for (i = 0; i < 19; i++) {
unsigned int value;
value = readl(base + VIC_PL190_VECT_ADDR);
writel(value, base + VIC_PL190_VECT_ADDR);
}
}
static void __init vic_set_irq_sources(void __iomem *base,
unsigned int irq_start, u32 vic_sources)
{
unsigned int i;
for (i = 0; i < 32; i++) {
if (vic_sources & (1 << i)) {
unsigned int irq = irq_start + i;
irq_set_chip_and_handler(irq, &vic_chip,
handle_level_irq);
irq_set_chip_data(irq, base);
set_irq_flags(irq, IRQF_VALID | IRQF_PROBE);
}
}
}
/*
* The PL190 cell from ARM has been modified by ST to handle 64 interrupts.
* The original cell has 32 interrupts, while the modified one has 64,
* replocating two blocks 0x00..0x1f in 0x20..0x3f. In that case
* the probe function is called twice, with base set to offset 000
* and 020 within the page. We call this "second block".
*/
static void __init vic_init_st(void __iomem *base, unsigned int irq_start,
u32 vic_sources, struct device_node *node)
{
unsigned int i;
int vic_2nd_block = ((unsigned long)base & ~PAGE_MASK) != 0;
/* Disable all interrupts initially. */
vic_disable(base);
/*
* Make sure we clear all existing interrupts. The vector registers
* in this cell are after the second block of general registers,
* so we can address them using standard offsets, but only from
* the second base address, which is 0x20 in the page
*/
if (vic_2nd_block) {
vic_clear_interrupts(base);
/* ST has 16 vectors as well, but we don't enable them by now */
for (i = 0; i < 16; i++) {
void __iomem *reg = base + VIC_VECT_CNTL0 + (i * 4);
writel(0, reg);
}
writel(32, base + VIC_PL190_DEF_VECT_ADDR);
}
vic_set_irq_sources(base, irq_start, vic_sources);
vic_register(base, irq_start, 0, node);
}
void __init __vic_init(void __iomem *base, unsigned int irq_start,
u32 vic_sources, u32 resume_sources,
struct device_node *node)
{
unsigned int i;
u32 cellid = 0;
enum amba_vendor vendor;
/* Identify which VIC cell this one is, by reading the ID */
for (i = 0; i < 4; i++) {
void __iomem *addr;
addr = (void __iomem *)((u32)base & PAGE_MASK) + 0xfe0 + (i * 4);
cellid |= (readl(addr) & 0xff) << (8 * i);
}
vendor = (cellid >> 12) & 0xff;
printk(KERN_INFO "VIC @%p: id 0x%08x, vendor 0x%02x\n",
base, cellid, vendor);
switch(vendor) {
case AMBA_VENDOR_ST:
vic_init_st(base, irq_start, vic_sources, node);
return;
default:
printk(KERN_WARNING "VIC: unknown vendor, continuing anyways\n");
/* fall through */
case AMBA_VENDOR_ARM:
break;
}
/* Disable all interrupts initially. */
vic_disable(base);
/* Make sure we clear all existing interrupts */
vic_clear_interrupts(base);
vic_init2(base);
vic_set_irq_sources(base, irq_start, vic_sources);
vic_register(base, irq_start, resume_sources, node);
}
/**
* vic_init() - initialise a vectored interrupt controller
* @base: iomem base address
* @irq_start: starting interrupt number, must be muliple of 32
* @vic_sources: bitmask of interrupt sources to allow
* @resume_sources: bitmask of interrupt sources to allow for resume
*/
void __init vic_init(void __iomem *base, unsigned int irq_start,
u32 vic_sources, u32 resume_sources)
{
__vic_init(base, irq_start, vic_sources, resume_sources, NULL);
}
#ifdef CONFIG_OF
int __init vic_of_init(struct device_node *node, struct device_node *parent)
{
void __iomem *regs;
int irq_base;
if (WARN(parent, "non-root VICs are not supported"))
return -EINVAL;
regs = of_iomap(node, 0);
if (WARN_ON(!regs))
return -EIO;
irq_base = irq_alloc_descs(-1, 0, 32, numa_node_id());
if (WARN_ON(irq_base < 0))
goto out_unmap;
__vic_init(regs, irq_base, ~0, ~0, node);
return 0;
out_unmap:
iounmap(regs);
return -EIO;
}
#endif /* CONFIG OF */
/*
* Handle each interrupt in a single VIC. Returns non-zero if we've
* handled at least one interrupt. This reads the status register
* before handling each interrupt, which is necessary given that
* handle_IRQ may briefly re-enable interrupts for soft IRQ handling.
*/
static int handle_one_vic(struct vic_device *vic, struct pt_regs *regs)
{
u32 stat, irq;
int handled = 0;
while ((stat = readl_relaxed(vic->base + VIC_IRQ_STATUS))) {
irq = ffs(stat) - 1;
handle_IRQ(irq_find_mapping(vic->domain, irq), regs);
handled = 1;
}
return handled;
}
/*
* Keep iterating over all registered VIC's until there are no pending
* interrupts.
*/
asmlinkage void __exception_irq_entry vic_handle_irq(struct pt_regs *regs)
{
int i, handled;
do {
for (i = 0, handled = 0; i < vic_id; ++i)
handled |= handle_one_vic(&vic_devices[i], regs);
} while (handled);
}
| gpl-2.0 |
shanzin/M7_Lollipop_Kernel | arch/arm/common/vic.c | 4790 | 11708 | /*
* linux/arch/arm/common/vic.c
*
* Copyright (C) 1999 - 2003 ARM Limited
* Copyright (C) 2000 Deep Blue Solutions Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This 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/export.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/io.h>
#include <linux/irqdomain.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/syscore_ops.h>
#include <linux/device.h>
#include <linux/amba/bus.h>
#include <asm/exception.h>
#include <asm/mach/irq.h>
#include <asm/hardware/vic.h>
/**
* struct vic_device - VIC PM device
* @irq: The IRQ number for the base of the VIC.
* @base: The register base for the VIC.
* @resume_sources: A bitmask of interrupts for resume.
* @resume_irqs: The IRQs enabled for resume.
* @int_select: Save for VIC_INT_SELECT.
* @int_enable: Save for VIC_INT_ENABLE.
* @soft_int: Save for VIC_INT_SOFT.
* @protect: Save for VIC_PROTECT.
* @domain: The IRQ domain for the VIC.
*/
struct vic_device {
void __iomem *base;
int irq;
u32 resume_sources;
u32 resume_irqs;
u32 int_select;
u32 int_enable;
u32 soft_int;
u32 protect;
struct irq_domain *domain;
};
/* we cannot allocate memory when VICs are initially registered */
static struct vic_device vic_devices[CONFIG_ARM_VIC_NR];
static int vic_id;
/**
* vic_init2 - common initialisation code
* @base: Base of the VIC.
*
* Common initialisation code for registration
* and resume.
*/
static void vic_init2(void __iomem *base)
{
int i;
for (i = 0; i < 16; i++) {
void __iomem *reg = base + VIC_VECT_CNTL0 + (i * 4);
writel(VIC_VECT_CNTL_ENABLE | i, reg);
}
writel(32, base + VIC_PL190_DEF_VECT_ADDR);
}
#ifdef CONFIG_PM
static void resume_one_vic(struct vic_device *vic)
{
void __iomem *base = vic->base;
printk(KERN_DEBUG "%s: resuming vic at %p\n", __func__, base);
/* re-initialise static settings */
vic_init2(base);
writel(vic->int_select, base + VIC_INT_SELECT);
writel(vic->protect, base + VIC_PROTECT);
/* set the enabled ints and then clear the non-enabled */
writel(vic->int_enable, base + VIC_INT_ENABLE);
writel(~vic->int_enable, base + VIC_INT_ENABLE_CLEAR);
/* and the same for the soft-int register */
writel(vic->soft_int, base + VIC_INT_SOFT);
writel(~vic->soft_int, base + VIC_INT_SOFT_CLEAR);
}
static void vic_resume(void)
{
int id;
for (id = vic_id - 1; id >= 0; id--)
resume_one_vic(vic_devices + id);
}
static void suspend_one_vic(struct vic_device *vic)
{
void __iomem *base = vic->base;
printk(KERN_DEBUG "%s: suspending vic at %p\n", __func__, base);
vic->int_select = readl(base + VIC_INT_SELECT);
vic->int_enable = readl(base + VIC_INT_ENABLE);
vic->soft_int = readl(base + VIC_INT_SOFT);
vic->protect = readl(base + VIC_PROTECT);
/* set the interrupts (if any) that are used for
* resuming the system */
writel(vic->resume_irqs, base + VIC_INT_ENABLE);
writel(~vic->resume_irqs, base + VIC_INT_ENABLE_CLEAR);
}
static int vic_suspend(void)
{
int id;
for (id = 0; id < vic_id; id++)
suspend_one_vic(vic_devices + id);
return 0;
}
struct syscore_ops vic_syscore_ops = {
.suspend = vic_suspend,
.resume = vic_resume,
};
/**
* vic_pm_init - initicall to register VIC pm
*
* This is called via late_initcall() to register
* the resources for the VICs due to the early
* nature of the VIC's registration.
*/
static int __init vic_pm_init(void)
{
if (vic_id > 0)
register_syscore_ops(&vic_syscore_ops);
return 0;
}
late_initcall(vic_pm_init);
#endif /* CONFIG_PM */
/**
* vic_register() - Register a VIC.
* @base: The base address of the VIC.
* @irq: The base IRQ for the VIC.
* @resume_sources: bitmask of interrupts allowed for resume sources.
* @node: The device tree node associated with the VIC.
*
* Register the VIC with the system device tree so that it can be notified
* of suspend and resume requests and ensure that the correct actions are
* taken to re-instate the settings on resume.
*
* This also configures the IRQ domain for the VIC.
*/
static void __init vic_register(void __iomem *base, unsigned int irq,
u32 resume_sources, struct device_node *node)
{
struct vic_device *v;
if (vic_id >= ARRAY_SIZE(vic_devices)) {
printk(KERN_ERR "%s: too few VICs, increase CONFIG_ARM_VIC_NR\n", __func__);
return;
}
v = &vic_devices[vic_id];
v->base = base;
v->resume_sources = resume_sources;
v->irq = irq;
vic_id++;
v->domain = irq_domain_add_legacy(node, 32, irq, 0,
&irq_domain_simple_ops, v);
}
static void vic_ack_irq(struct irq_data *d)
{
void __iomem *base = irq_data_get_irq_chip_data(d);
unsigned int irq = d->hwirq;
writel(1 << irq, base + VIC_INT_ENABLE_CLEAR);
/* moreover, clear the soft-triggered, in case it was the reason */
writel(1 << irq, base + VIC_INT_SOFT_CLEAR);
}
static void vic_mask_irq(struct irq_data *d)
{
void __iomem *base = irq_data_get_irq_chip_data(d);
unsigned int irq = d->hwirq;
writel(1 << irq, base + VIC_INT_ENABLE_CLEAR);
}
static void vic_unmask_irq(struct irq_data *d)
{
void __iomem *base = irq_data_get_irq_chip_data(d);
unsigned int irq = d->hwirq;
writel(1 << irq, base + VIC_INT_ENABLE);
}
#if defined(CONFIG_PM)
static struct vic_device *vic_from_irq(unsigned int irq)
{
struct vic_device *v = vic_devices;
unsigned int base_irq = irq & ~31;
int id;
for (id = 0; id < vic_id; id++, v++) {
if (v->irq == base_irq)
return v;
}
return NULL;
}
static int vic_set_wake(struct irq_data *d, unsigned int on)
{
struct vic_device *v = vic_from_irq(d->irq);
unsigned int off = d->hwirq;
u32 bit = 1 << off;
if (!v)
return -EINVAL;
if (!(bit & v->resume_sources))
return -EINVAL;
if (on)
v->resume_irqs |= bit;
else
v->resume_irqs &= ~bit;
return 0;
}
#else
#define vic_set_wake NULL
#endif /* CONFIG_PM */
static struct irq_chip vic_chip = {
.name = "VIC",
.irq_ack = vic_ack_irq,
.irq_mask = vic_mask_irq,
.irq_unmask = vic_unmask_irq,
.irq_set_wake = vic_set_wake,
};
static void __init vic_disable(void __iomem *base)
{
writel(0, base + VIC_INT_SELECT);
writel(0, base + VIC_INT_ENABLE);
writel(~0, base + VIC_INT_ENABLE_CLEAR);
writel(0, base + VIC_ITCR);
writel(~0, base + VIC_INT_SOFT_CLEAR);
}
static void __init vic_clear_interrupts(void __iomem *base)
{
unsigned int i;
writel(0, base + VIC_PL190_VECT_ADDR);
for (i = 0; i < 19; i++) {
unsigned int value;
value = readl(base + VIC_PL190_VECT_ADDR);
writel(value, base + VIC_PL190_VECT_ADDR);
}
}
static void __init vic_set_irq_sources(void __iomem *base,
unsigned int irq_start, u32 vic_sources)
{
unsigned int i;
for (i = 0; i < 32; i++) {
if (vic_sources & (1 << i)) {
unsigned int irq = irq_start + i;
irq_set_chip_and_handler(irq, &vic_chip,
handle_level_irq);
irq_set_chip_data(irq, base);
set_irq_flags(irq, IRQF_VALID | IRQF_PROBE);
}
}
}
/*
* The PL190 cell from ARM has been modified by ST to handle 64 interrupts.
* The original cell has 32 interrupts, while the modified one has 64,
* replocating two blocks 0x00..0x1f in 0x20..0x3f. In that case
* the probe function is called twice, with base set to offset 000
* and 020 within the page. We call this "second block".
*/
static void __init vic_init_st(void __iomem *base, unsigned int irq_start,
u32 vic_sources, struct device_node *node)
{
unsigned int i;
int vic_2nd_block = ((unsigned long)base & ~PAGE_MASK) != 0;
/* Disable all interrupts initially. */
vic_disable(base);
/*
* Make sure we clear all existing interrupts. The vector registers
* in this cell are after the second block of general registers,
* so we can address them using standard offsets, but only from
* the second base address, which is 0x20 in the page
*/
if (vic_2nd_block) {
vic_clear_interrupts(base);
/* ST has 16 vectors as well, but we don't enable them by now */
for (i = 0; i < 16; i++) {
void __iomem *reg = base + VIC_VECT_CNTL0 + (i * 4);
writel(0, reg);
}
writel(32, base + VIC_PL190_DEF_VECT_ADDR);
}
vic_set_irq_sources(base, irq_start, vic_sources);
vic_register(base, irq_start, 0, node);
}
void __init __vic_init(void __iomem *base, unsigned int irq_start,
u32 vic_sources, u32 resume_sources,
struct device_node *node)
{
unsigned int i;
u32 cellid = 0;
enum amba_vendor vendor;
/* Identify which VIC cell this one is, by reading the ID */
for (i = 0; i < 4; i++) {
void __iomem *addr;
addr = (void __iomem *)((u32)base & PAGE_MASK) + 0xfe0 + (i * 4);
cellid |= (readl(addr) & 0xff) << (8 * i);
}
vendor = (cellid >> 12) & 0xff;
printk(KERN_INFO "VIC @%p: id 0x%08x, vendor 0x%02x\n",
base, cellid, vendor);
switch(vendor) {
case AMBA_VENDOR_ST:
vic_init_st(base, irq_start, vic_sources, node);
return;
default:
printk(KERN_WARNING "VIC: unknown vendor, continuing anyways\n");
/* fall through */
case AMBA_VENDOR_ARM:
break;
}
/* Disable all interrupts initially. */
vic_disable(base);
/* Make sure we clear all existing interrupts */
vic_clear_interrupts(base);
vic_init2(base);
vic_set_irq_sources(base, irq_start, vic_sources);
vic_register(base, irq_start, resume_sources, node);
}
/**
* vic_init() - initialise a vectored interrupt controller
* @base: iomem base address
* @irq_start: starting interrupt number, must be muliple of 32
* @vic_sources: bitmask of interrupt sources to allow
* @resume_sources: bitmask of interrupt sources to allow for resume
*/
void __init vic_init(void __iomem *base, unsigned int irq_start,
u32 vic_sources, u32 resume_sources)
{
__vic_init(base, irq_start, vic_sources, resume_sources, NULL);
}
#ifdef CONFIG_OF
int __init vic_of_init(struct device_node *node, struct device_node *parent)
{
void __iomem *regs;
int irq_base;
if (WARN(parent, "non-root VICs are not supported"))
return -EINVAL;
regs = of_iomap(node, 0);
if (WARN_ON(!regs))
return -EIO;
irq_base = irq_alloc_descs(-1, 0, 32, numa_node_id());
if (WARN_ON(irq_base < 0))
goto out_unmap;
__vic_init(regs, irq_base, ~0, ~0, node);
return 0;
out_unmap:
iounmap(regs);
return -EIO;
}
#endif /* CONFIG OF */
/*
* Handle each interrupt in a single VIC. Returns non-zero if we've
* handled at least one interrupt. This reads the status register
* before handling each interrupt, which is necessary given that
* handle_IRQ may briefly re-enable interrupts for soft IRQ handling.
*/
static int handle_one_vic(struct vic_device *vic, struct pt_regs *regs)
{
u32 stat, irq;
int handled = 0;
while ((stat = readl_relaxed(vic->base + VIC_IRQ_STATUS))) {
irq = ffs(stat) - 1;
handle_IRQ(irq_find_mapping(vic->domain, irq), regs);
handled = 1;
}
return handled;
}
/*
* Keep iterating over all registered VIC's until there are no pending
* interrupts.
*/
asmlinkage void __exception_irq_entry vic_handle_irq(struct pt_regs *regs)
{
int i, handled;
do {
for (i = 0, handled = 0; i < vic_id; ++i)
handled |= handle_one_vic(&vic_devices[i], regs);
} while (handled);
}
| gpl-2.0 |
joaompinto/kernel-2.6.32.27-M722HC | drivers/staging/octeon/cvmx-helper-loop.c | 4790 | 2679 | /***********************license start***************
* Author: Cavium Networks
*
* Contact: support@caviumnetworks.com
* This file is part of the OCTEON SDK
*
* Copyright (c) 2003-2008 Cavium Networks
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, Version 2, as
* published by the Free Software Foundation.
*
* This file is distributed in the hope that it will be useful, but
* AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
* NONINFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* or visit http://www.gnu.org/licenses/.
*
* This file may also be available under a different license from Cavium.
* Contact Cavium Networks for more information
***********************license end**************************************/
/*
* Functions for LOOP initialization, configuration,
* and monitoring.
*/
#include <asm/octeon/octeon.h>
#include "cvmx-config.h"
#include "cvmx-helper.h"
#include "cvmx-pip-defs.h"
/**
* Probe a LOOP interface and determine the number of ports
* connected to it. The LOOP interface should still be down
* after this call.
*
* @interface: Interface to probe
*
* Returns Number of ports on the interface. Zero to disable.
*/
int __cvmx_helper_loop_probe(int interface)
{
union cvmx_ipd_sub_port_fcs ipd_sub_port_fcs;
int num_ports = 4;
int port;
/* We need to disable length checking so packet < 64 bytes and jumbo
frames don't get errors */
for (port = 0; port < num_ports; port++) {
union cvmx_pip_prt_cfgx port_cfg;
int ipd_port = cvmx_helper_get_ipd_port(interface, port);
port_cfg.u64 = cvmx_read_csr(CVMX_PIP_PRT_CFGX(ipd_port));
port_cfg.s.maxerr_en = 0;
port_cfg.s.minerr_en = 0;
cvmx_write_csr(CVMX_PIP_PRT_CFGX(ipd_port), port_cfg.u64);
}
/* Disable FCS stripping for loopback ports */
ipd_sub_port_fcs.u64 = cvmx_read_csr(CVMX_IPD_SUB_PORT_FCS);
ipd_sub_port_fcs.s.port_bit2 = 0;
cvmx_write_csr(CVMX_IPD_SUB_PORT_FCS, ipd_sub_port_fcs.u64);
return num_ports;
}
/**
* Bringup and enable a LOOP interface. After this call packet
* I/O should be fully functional. This is called with IPD
* enabled but PKO disabled.
*
* @interface: Interface to bring up
*
* Returns Zero on success, negative on failure
*/
int __cvmx_helper_loop_enable(int interface)
{
/* Do nothing. */
return 0;
}
| gpl-2.0 |
IngenicSemiconductor/KERNEL-NPM801 | drivers/staging/rtl8192u/ieee80211/rtl819x_HTProc.c | 8118 | 49749 |
//As this function is mainly ported from Windows driver, so leave the name little changed. If any confusion caused, tell me. Created by WB. 2008.05.08
#include "ieee80211.h"
#include "rtl819x_HT.h"
u8 MCS_FILTER_ALL[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
u8 MCS_FILTER_1SS[16] = {0xff, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
u16 MCS_DATA_RATE[2][2][77] =
{ { {13, 26, 39, 52, 78, 104, 117, 130, 26, 52, 78 ,104, 156, 208, 234, 260,
39, 78, 117, 234, 312, 351, 390, 52, 104, 156, 208, 312, 416, 468, 520,
0, 78, 104, 130, 117, 156, 195, 104, 130, 130, 156, 182, 182, 208, 156, 195,
195, 234, 273, 273, 312, 130, 156, 181, 156, 181, 208, 234, 208, 234, 260, 260,
286, 195, 234, 273, 234, 273, 312, 351, 312, 351, 390, 390, 429}, // Long GI, 20MHz
{14, 29, 43, 58, 87, 116, 130, 144, 29, 58, 87, 116, 173, 231, 260, 289,
43, 87, 130, 173, 260, 347, 390, 433, 58, 116, 173, 231, 347, 462, 520, 578,
0, 87, 116, 144, 130, 173, 217, 116, 144, 144, 173, 202, 202, 231, 173, 217,
217, 260, 303, 303, 347, 144, 173, 202, 173, 202, 231, 260, 231, 260, 289, 289,
318, 217, 260, 303, 260, 303, 347, 390, 347, 390, 433, 433, 477} }, // Short GI, 20MHz
{ {27, 54, 81, 108, 162, 216, 243, 270, 54, 108, 162, 216, 324, 432, 486, 540,
81, 162, 243, 324, 486, 648, 729, 810, 108, 216, 324, 432, 648, 864, 972, 1080,
12, 162, 216, 270, 243, 324, 405, 216, 270, 270, 324, 378, 378, 432, 324, 405,
405, 486, 567, 567, 648, 270, 324, 378, 324, 378, 432, 486, 432, 486, 540, 540,
594, 405, 486, 567, 486, 567, 648, 729, 648, 729, 810, 810, 891}, // Long GI, 40MHz
{30, 60, 90, 120, 180, 240, 270, 300, 60, 120, 180, 240, 360, 480, 540, 600,
90, 180, 270, 360, 540, 720, 810, 900, 120, 240, 360, 480, 720, 960, 1080, 1200,
13, 180, 240, 300, 270, 360, 450, 240, 300, 300, 360, 420, 420, 480, 360, 450,
450, 540, 630, 630, 720, 300, 360, 420, 360, 420, 480, 540, 480, 540, 600, 600,
660, 450, 540, 630, 540, 630, 720, 810, 720, 810, 900, 900, 990} } // Short GI, 40MHz
};
static u8 UNKNOWN_BORADCOM[3] = {0x00, 0x14, 0xbf};
static u8 LINKSYSWRT330_LINKSYSWRT300_BROADCOM[3] = {0x00, 0x1a, 0x70};
static u8 LINKSYSWRT350_LINKSYSWRT150_BROADCOM[3] = {0x00, 0x1d, 0x7e};
static u8 NETGEAR834Bv2_BROADCOM[3] = {0x00, 0x1b, 0x2f};
static u8 BELKINF5D8233V1_RALINK[3] = {0x00, 0x17, 0x3f}; //cosa 03202008
static u8 BELKINF5D82334V3_RALINK[3] = {0x00, 0x1c, 0xdf};
static u8 PCI_RALINK[3] = {0x00, 0x90, 0xcc};
static u8 EDIMAX_RALINK[3] = {0x00, 0x0e, 0x2e};
static u8 AIRLINK_RALINK[3] = {0x00, 0x18, 0x02};
//static u8 DLINK_ATHEROS[3] = {0x00, 0x1c, 0xf0};
static u8 CISCO_BROADCOM[3] = {0x00, 0x17, 0x94};
// 2008/04/01 MH For Cisco G mode RX TP We need to change FW duration. Should we put the
// code in other place??
//static u8 WIFI_CISCO_G_AP[3] = {0x00, 0x40, 0x96};
/********************************************************************************************************************
*function: This function update default settings in pHTInfo structure
* input: PRT_HIGH_THROUGHPUT pHTInfo
* output: none
* return: none
* notice: These value need be modified if any changes.
* *****************************************************************************************************************/
void HTUpdateDefaultSetting(struct ieee80211_device* ieee)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
//const typeof( ((struct ieee80211_device *)0)->pHTInfo ) *__mptr = &pHTInfo;
//printk("pHTinfo:%p, &pHTinfo:%p, mptr:%p, offsetof:%x\n", pHTInfo, &pHTInfo, __mptr, offsetof(struct ieee80211_device, pHTInfo));
//printk("===>ieee:%p,\n", ieee);
// ShortGI support
pHTInfo->bRegShortGI20MHz= 1;
pHTInfo->bRegShortGI40MHz= 1;
// 40MHz channel support
pHTInfo->bRegBW40MHz = 1;
// CCK rate support in 40MHz channel
if(pHTInfo->bRegBW40MHz)
pHTInfo->bRegSuppCCK = 1;
else
pHTInfo->bRegSuppCCK = true;
// AMSDU related
pHTInfo->nAMSDU_MaxSize = 7935UL;
pHTInfo->bAMSDU_Support = 0;
// AMPDU related
pHTInfo->bAMPDUEnable = 1;
pHTInfo->AMPDU_Factor = 2; //// 0: 2n13(8K), 1:2n14(16K), 2:2n15(32K), 3:2n16(64k)
pHTInfo->MPDU_Density = 0;// 0: No restriction, 1: 1/8usec, 2: 1/4usec, 3: 1/2usec, 4: 1usec, 5: 2usec, 6: 4usec, 7:8usec
// MIMO Power Save
pHTInfo->SelfMimoPs = 3;// 0: Static Mimo Ps, 1: Dynamic Mimo Ps, 3: No Limitation, 2: Reserved(Set to 3 automatically.)
if(pHTInfo->SelfMimoPs == 2)
pHTInfo->SelfMimoPs = 3;
// 8190 only. Assign rate operation mode to firmware
ieee->bTxDisableRateFallBack = 0;
ieee->bTxUseDriverAssingedRate = 0;
#ifdef TO_DO_LIST
// 8190 only. Assign duration operation mode to firmware
pMgntInfo->bTxEnableFwCalcDur = (BOOLEAN)pNdisCommon->bRegTxEnableFwCalcDur;
#endif
// 8190 only, Realtek proprietary aggregation mode
// Set MPDUDensity=2, 1: Set MPDUDensity=2(32k) for Realtek AP and set MPDUDensity=0(8k) for others
pHTInfo->bRegRT2RTAggregation = 1;//0: Set MPDUDensity=2, 1: Set MPDUDensity=2(32k) for Realtek AP and set MPDUDensity=0(8k) for others
// For Rx Reorder Control
pHTInfo->bRegRxReorderEnable = 1;
pHTInfo->RxReorderWinSize = 64;
pHTInfo->RxReorderPendingTime = 30;
#ifdef USB_TX_DRIVER_AGGREGATION_ENABLE
pHTInfo->UsbTxAggrNum = 4;
#endif
#ifdef USB_RX_AGGREGATION_SUPPORT
pHTInfo->UsbRxFwAggrEn = 1;
pHTInfo->UsbRxFwAggrPageNum = 24;
pHTInfo->UsbRxFwAggrPacketNum = 8;
pHTInfo->UsbRxFwAggrTimeout = 16; ////usb rx FW aggregation timeout threshold.It's in units of 64us
#endif
}
/********************************************************************************************************************
*function: This function print out each field on HT capability IE mainly from (Beacon/ProbeRsp/AssocReq)
* input: u8* CapIE //Capability IE to be printed out
* u8* TitleString //mainly print out caller function
* output: none
* return: none
* notice: Driver should not print out this message by default.
* *****************************************************************************************************************/
void HTDebugHTCapability(u8* CapIE, u8* TitleString )
{
static u8 EWC11NHTCap[] = {0x00, 0x90, 0x4c, 0x33}; // For 11n EWC definition, 2007.07.17, by Emily
PHT_CAPABILITY_ELE pCapELE;
if(!memcmp(CapIE, EWC11NHTCap, sizeof(EWC11NHTCap)))
{
//EWC IE
IEEE80211_DEBUG(IEEE80211_DL_HT, "EWC IE in %s()\n", __FUNCTION__);
pCapELE = (PHT_CAPABILITY_ELE)(&CapIE[4]);
}else
pCapELE = (PHT_CAPABILITY_ELE)(&CapIE[0]);
IEEE80211_DEBUG(IEEE80211_DL_HT, "<Log HT Capability>. Called by %s\n", TitleString );
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tSupported Channel Width = %s\n", (pCapELE->ChlWidth)?"20MHz": "20/40MHz");
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tSupport Short GI for 20M = %s\n", (pCapELE->ShortGI20Mhz)?"YES": "NO");
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tSupport Short GI for 40M = %s\n", (pCapELE->ShortGI40Mhz)?"YES": "NO");
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tSupport TX STBC = %s\n", (pCapELE->TxSTBC)?"YES": "NO");
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tMax AMSDU Size = %s\n", (pCapELE->MaxAMSDUSize)?"3839": "7935");
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tSupport CCK in 20/40 mode = %s\n", (pCapELE->DssCCk)?"YES": "NO");
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tMax AMPDU Factor = %d\n", pCapELE->MaxRxAMPDUFactor);
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tMPDU Density = %d\n", pCapELE->MPDUDensity);
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tMCS Rate Set = [%x][%x][%x][%x][%x]\n", pCapELE->MCS[0],\
pCapELE->MCS[1], pCapELE->MCS[2], pCapELE->MCS[3], pCapELE->MCS[4]);
return;
}
/********************************************************************************************************************
*function: This function print out each field on HT Information IE mainly from (Beacon/ProbeRsp)
* input: u8* InfoIE //Capability IE to be printed out
* u8* TitleString //mainly print out caller function
* output: none
* return: none
* notice: Driver should not print out this message by default.
* *****************************************************************************************************************/
void HTDebugHTInfo(u8* InfoIE, u8* TitleString)
{
static u8 EWC11NHTInfo[] = {0x00, 0x90, 0x4c, 0x34}; // For 11n EWC definition, 2007.07.17, by Emily
PHT_INFORMATION_ELE pHTInfoEle;
if(!memcmp(InfoIE, EWC11NHTInfo, sizeof(EWC11NHTInfo)))
{
// Not EWC IE
IEEE80211_DEBUG(IEEE80211_DL_HT, "EWC IE in %s()\n", __FUNCTION__);
pHTInfoEle = (PHT_INFORMATION_ELE)(&InfoIE[4]);
}else
pHTInfoEle = (PHT_INFORMATION_ELE)(&InfoIE[0]);
IEEE80211_DEBUG(IEEE80211_DL_HT, "<Log HT Information Element>. Called by %s\n", TitleString);
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tPrimary channel = %d\n", pHTInfoEle->ControlChl);
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tSenondary channel =");
switch(pHTInfoEle->ExtChlOffset)
{
case 0:
IEEE80211_DEBUG(IEEE80211_DL_HT, "Not Present\n");
break;
case 1:
IEEE80211_DEBUG(IEEE80211_DL_HT, "Upper channel\n");
break;
case 2:
IEEE80211_DEBUG(IEEE80211_DL_HT, "Reserved. Eooro!!!\n");
break;
case 3:
IEEE80211_DEBUG(IEEE80211_DL_HT, "Lower Channel\n");
break;
}
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tRecommended channel width = %s\n", (pHTInfoEle->RecommemdedTxWidth)?"20Mhz": "40Mhz");
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tOperation mode for protection = ");
switch(pHTInfoEle->OptMode)
{
case 0:
IEEE80211_DEBUG(IEEE80211_DL_HT, "No Protection\n");
break;
case 1:
IEEE80211_DEBUG(IEEE80211_DL_HT, "HT non-member protection mode\n");
break;
case 2:
IEEE80211_DEBUG(IEEE80211_DL_HT, "Suggest to open protection\n");
break;
case 3:
IEEE80211_DEBUG(IEEE80211_DL_HT, "HT mixed mode\n");
break;
}
IEEE80211_DEBUG(IEEE80211_DL_HT, "\tBasic MCS Rate Set = [%x][%x][%x][%x][%x]\n", pHTInfoEle->BasicMSC[0],\
pHTInfoEle->BasicMSC[1], pHTInfoEle->BasicMSC[2], pHTInfoEle->BasicMSC[3], pHTInfoEle->BasicMSC[4]);
return;
}
/*
* Return: true if station in half n mode and AP supports 40 bw
*/
bool IsHTHalfNmode40Bandwidth(struct ieee80211_device* ieee)
{
bool retValue = false;
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
if(pHTInfo->bCurrentHTSupport == false ) // wireless is n mode
retValue = false;
else if(pHTInfo->bRegBW40MHz == false) // station supports 40 bw
retValue = false;
else if(!ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev)) // station in half n mode
retValue = false;
else if(((PHT_CAPABILITY_ELE)(pHTInfo->PeerHTCapBuf))->ChlWidth) // ap support 40 bw
retValue = true;
else
retValue = false;
return retValue;
}
bool IsHTHalfNmodeSGI(struct ieee80211_device* ieee, bool is40MHz)
{
bool retValue = false;
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
if(pHTInfo->bCurrentHTSupport == false ) // wireless is n mode
retValue = false;
else if(!ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev)) // station in half n mode
retValue = false;
else if(is40MHz) // ap support 40 bw
{
if(((PHT_CAPABILITY_ELE)(pHTInfo->PeerHTCapBuf))->ShortGI40Mhz) // ap support 40 bw short GI
retValue = true;
else
retValue = false;
}
else
{
if(((PHT_CAPABILITY_ELE)(pHTInfo->PeerHTCapBuf))->ShortGI20Mhz) // ap support 40 bw short GI
retValue = true;
else
retValue = false;
}
return retValue;
}
u16 HTHalfMcsToDataRate(struct ieee80211_device* ieee, u8 nMcsRate)
{
u8 is40MHz;
u8 isShortGI;
is40MHz = (IsHTHalfNmode40Bandwidth(ieee))?1:0;
isShortGI = (IsHTHalfNmodeSGI(ieee, is40MHz))? 1:0;
return MCS_DATA_RATE[is40MHz][isShortGI][(nMcsRate&0x7f)];
}
u16 HTMcsToDataRate( struct ieee80211_device* ieee, u8 nMcsRate)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
u8 is40MHz = (pHTInfo->bCurBW40MHz)?1:0;
u8 isShortGI = (pHTInfo->bCurBW40MHz)?
((pHTInfo->bCurShortGI40MHz)?1:0):
((pHTInfo->bCurShortGI20MHz)?1:0);
return MCS_DATA_RATE[is40MHz][isShortGI][(nMcsRate&0x7f)];
}
/********************************************************************************************************************
*function: This function returns current datarate.
* input: struct ieee80211_device* ieee
* u8 nDataRate
* output: none
* return: tx rate
* notice: quite unsure about how to use this function //wb
* *****************************************************************************************************************/
u16 TxCountToDataRate( struct ieee80211_device* ieee, u8 nDataRate)
{
//PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
u16 CCKOFDMRate[12] = {0x02 , 0x04 , 0x0b , 0x16 , 0x0c , 0x12 , 0x18 , 0x24 , 0x30 , 0x48 , 0x60 , 0x6c};
u8 is40MHz = 0;
u8 isShortGI = 0;
if(nDataRate < 12)
{
return CCKOFDMRate[nDataRate];
}
else
{
if (nDataRate >= 0x10 && nDataRate <= 0x1f)//if(nDataRate > 11 && nDataRate < 28 )
{
is40MHz = 0;
isShortGI = 0;
// nDataRate = nDataRate - 12;
}
else if(nDataRate >=0x20 && nDataRate <= 0x2f ) //(27, 44)
{
is40MHz = 1;
isShortGI = 0;
//nDataRate = nDataRate - 28;
}
else if(nDataRate >= 0x30 && nDataRate <= 0x3f ) //(43, 60)
{
is40MHz = 0;
isShortGI = 1;
//nDataRate = nDataRate - 44;
}
else if(nDataRate >= 0x40 && nDataRate <= 0x4f ) //(59, 76)
{
is40MHz = 1;
isShortGI = 1;
//nDataRate = nDataRate - 60;
}
return MCS_DATA_RATE[is40MHz][isShortGI][nDataRate&0xf];
}
}
bool IsHTHalfNmodeAPs(struct ieee80211_device* ieee)
{
bool retValue = false;
struct ieee80211_network* net = &ieee->current_network;
if((memcmp(net->bssid, BELKINF5D8233V1_RALINK, 3)==0) ||
(memcmp(net->bssid, BELKINF5D82334V3_RALINK, 3)==0) ||
(memcmp(net->bssid, PCI_RALINK, 3)==0) ||
(memcmp(net->bssid, EDIMAX_RALINK, 3)==0) ||
(memcmp(net->bssid, AIRLINK_RALINK, 3)==0) ||
(net->ralink_cap_exist))
retValue = true;
else if((memcmp(net->bssid, UNKNOWN_BORADCOM, 3)==0) ||
(memcmp(net->bssid, LINKSYSWRT330_LINKSYSWRT300_BROADCOM, 3)==0)||
(memcmp(net->bssid, LINKSYSWRT350_LINKSYSWRT150_BROADCOM, 3)==0)||
(memcmp(net->bssid, NETGEAR834Bv2_BROADCOM, 3)==0) ||
(net->broadcom_cap_exist))
retValue = true;
else if(net->bssht.bdRT2RTAggregation)
retValue = true;
else
retValue = false;
return retValue;
}
/********************************************************************************************************************
*function: This function returns peer IOT.
* input: struct ieee80211_device* ieee
* output: none
* return:
* notice:
* *****************************************************************************************************************/
void HTIOTPeerDetermine(struct ieee80211_device* ieee)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
struct ieee80211_network* net = &ieee->current_network;
if(net->bssht.bdRT2RTAggregation)
pHTInfo->IOTPeer = HT_IOT_PEER_REALTEK;
else if(net->broadcom_cap_exist)
pHTInfo->IOTPeer = HT_IOT_PEER_BROADCOM;
else if((memcmp(net->bssid, UNKNOWN_BORADCOM, 3)==0) ||
(memcmp(net->bssid, LINKSYSWRT330_LINKSYSWRT300_BROADCOM, 3)==0)||
(memcmp(net->bssid, LINKSYSWRT350_LINKSYSWRT150_BROADCOM, 3)==0)||
(memcmp(net->bssid, NETGEAR834Bv2_BROADCOM, 3)==0) )
pHTInfo->IOTPeer = HT_IOT_PEER_BROADCOM;
else if((memcmp(net->bssid, BELKINF5D8233V1_RALINK, 3)==0) ||
(memcmp(net->bssid, BELKINF5D82334V3_RALINK, 3)==0) ||
(memcmp(net->bssid, PCI_RALINK, 3)==0) ||
(memcmp(net->bssid, EDIMAX_RALINK, 3)==0) ||
(memcmp(net->bssid, AIRLINK_RALINK, 3)==0) ||
net->ralink_cap_exist)
pHTInfo->IOTPeer = HT_IOT_PEER_RALINK;
else if(net->atheros_cap_exist)
pHTInfo->IOTPeer = HT_IOT_PEER_ATHEROS;
else if(memcmp(net->bssid, CISCO_BROADCOM, 3)==0)
pHTInfo->IOTPeer = HT_IOT_PEER_CISCO;
else
pHTInfo->IOTPeer = HT_IOT_PEER_UNKNOWN;
IEEE80211_DEBUG(IEEE80211_DL_IOT, "Joseph debug!! IOTPEER: %x\n", pHTInfo->IOTPeer);
}
/********************************************************************************************************************
*function: Check whether driver should declare received rate up to MCS13 only since some chipset is not good
* at receiving MCS14~15 frame from some AP.
* input: struct ieee80211_device* ieee
* u8 * PeerMacAddr
* output: none
* return: return 1 if driver should declare MCS13 only(otherwise return 0)
* *****************************************************************************************************************/
u8 HTIOTActIsDisableMCS14(struct ieee80211_device* ieee, u8* PeerMacAddr)
{
u8 ret = 0;
return ret;
}
/**
* Function: HTIOTActIsDisableMCS15
*
* Overview: Check whether driver should declare capability of receiving MCS15
*
* Input:
* PADAPTER Adapter,
*
* Output: None
* Return: true if driver should disable MCS15
* 2008.04.15 Emily
*/
bool HTIOTActIsDisableMCS15(struct ieee80211_device* ieee)
{
bool retValue = false;
#ifdef TODO
// Apply for 819u only
#if (HAL_CODE_BASE==RTL8192)
#if (DEV_BUS_TYPE == USB_INTERFACE)
// Alway disable MCS15 by Jerry Chang's request.by Emily, 2008.04.15
retValue = true;
#elif (DEV_BUS_TYPE == PCI_INTERFACE)
// Enable MCS15 if the peer is Cisco AP. by Emily, 2008.05.12
// if(pBssDesc->bCiscoCapExist)
// retValue = false;
// else
retValue = false;
#endif
#endif
#endif
// Jerry Chang suggest that 8190 1x2 does not need to disable MCS15
return retValue;
}
/**
* Function: HTIOTActIsDisableMCSTwoSpatialStream
*
* Overview: Check whether driver should declare capability of receiving All 2 ss packets
*
* Input:
* PADAPTER Adapter,
*
* Output: None
* Return: true if driver should disable all two spatial stream packet
* 2008.04.21 Emily
*/
bool HTIOTActIsDisableMCSTwoSpatialStream(struct ieee80211_device* ieee, u8 *PeerMacAddr)
{
bool retValue = false;
#ifdef TODO
// Apply for 819u only
#endif
return retValue;
}
/********************************************************************************************************************
*function: Check whether driver should disable EDCA turbo mode
* input: struct ieee80211_device* ieee
* u8* PeerMacAddr
* output: none
* return: return 1 if driver should disable EDCA turbo mode(otherwise return 0)
* *****************************************************************************************************************/
u8 HTIOTActIsDisableEDCATurbo(struct ieee80211_device* ieee, u8* PeerMacAddr)
{
u8 retValue = false; // default enable EDCA Turbo mode.
// Set specific EDCA parameter for different AP in DM handler.
return retValue;
}
/********************************************************************************************************************
*function: Check whether we need to use OFDM to sned MGNT frame for broadcom AP
* input: struct ieee80211_network *network //current network we live
* output: none
* return: return 1 if true
* *****************************************************************************************************************/
u8 HTIOTActIsMgntUseCCK6M(struct ieee80211_network *network)
{
u8 retValue = 0;
// 2008/01/25 MH Judeg if we need to use OFDM to sned MGNT frame for broadcom AP.
// 2008/01/28 MH We must prevent that we select null bssid to link.
if(network->broadcom_cap_exist)
{
retValue = 1;
}
return retValue;
}
u8 HTIOTActIsCCDFsync(u8* PeerMacAddr)
{
u8 retValue = 0;
if( (memcmp(PeerMacAddr, UNKNOWN_BORADCOM, 3)==0) ||
(memcmp(PeerMacAddr, LINKSYSWRT330_LINKSYSWRT300_BROADCOM, 3)==0) ||
(memcmp(PeerMacAddr, LINKSYSWRT350_LINKSYSWRT150_BROADCOM, 3) ==0))
{
retValue = 1;
}
return retValue;
}
void HTResetIOTSetting(
PRT_HIGH_THROUGHPUT pHTInfo
)
{
pHTInfo->IOTAction = 0;
pHTInfo->IOTPeer = HT_IOT_PEER_UNKNOWN;
}
/********************************************************************************************************************
*function: Construct Capablility Element in Beacon... if HTEnable is turned on
* input: struct ieee80211_device* ieee
* u8* posHTCap //pointer to store Capability Ele
* u8* len //store length of CE
* u8 IsEncrypt //whether encrypt, needed further
* output: none
* return: none
* notice: posHTCap can't be null and should be initialized before.
* *****************************************************************************************************************/
void HTConstructCapabilityElement(struct ieee80211_device* ieee, u8* posHTCap, u8* len, u8 IsEncrypt)
{
PRT_HIGH_THROUGHPUT pHT = ieee->pHTInfo;
PHT_CAPABILITY_ELE pCapELE = NULL;
//u8 bIsDeclareMCS13;
if ((posHTCap == NULL) || (pHT == NULL))
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "posHTCap or pHTInfo can't be null in HTConstructCapabilityElement()\n");
return;
}
memset(posHTCap, 0, *len);
if(pHT->ePeerHTSpecVer == HT_SPEC_VER_EWC)
{
u8 EWC11NHTCap[] = {0x00, 0x90, 0x4c, 0x33}; // For 11n EWC definition, 2007.07.17, by Emily
memcpy(posHTCap, EWC11NHTCap, sizeof(EWC11NHTCap));
pCapELE = (PHT_CAPABILITY_ELE)&(posHTCap[4]);
}else
{
pCapELE = (PHT_CAPABILITY_ELE)posHTCap;
}
//HT capability info
pCapELE->AdvCoding = 0; // This feature is not supported now!!
if(ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev))
{
pCapELE->ChlWidth = 0;
}
else
{
pCapELE->ChlWidth = (pHT->bRegBW40MHz?1:0);
}
// pCapELE->ChlWidth = (pHT->bRegBW40MHz?1:0);
pCapELE->MimoPwrSave = pHT->SelfMimoPs;
pCapELE->GreenField = 0; // This feature is not supported now!!
pCapELE->ShortGI20Mhz = 1; // We can receive Short GI!!
pCapELE->ShortGI40Mhz = 1; // We can receive Short GI!!
//DbgPrint("TX HT cap/info ele BW=%d SG20=%d SG40=%d\n\r",
//pCapELE->ChlWidth, pCapELE->ShortGI20Mhz, pCapELE->ShortGI40Mhz);
pCapELE->TxSTBC = 1;
pCapELE->RxSTBC = 0;
pCapELE->DelayBA = 0; // Do not support now!!
pCapELE->MaxAMSDUSize = (MAX_RECEIVE_BUFFER_SIZE>=7935)?1:0;
pCapELE->DssCCk = ((pHT->bRegBW40MHz)?(pHT->bRegSuppCCK?1:0):0);
pCapELE->PSMP = 0; // Do not support now!!
pCapELE->LSigTxopProtect = 0; // Do not support now!!
//MAC HT parameters info
// TODO: Nedd to take care of this part
IEEE80211_DEBUG(IEEE80211_DL_HT, "TX HT cap/info ele BW=%d MaxAMSDUSize:%d DssCCk:%d\n", pCapELE->ChlWidth, pCapELE->MaxAMSDUSize, pCapELE->DssCCk);
if( IsEncrypt)
{
pCapELE->MPDUDensity = 7; // 8us
pCapELE->MaxRxAMPDUFactor = 2; // 2 is for 32 K and 3 is 64K
}
else
{
pCapELE->MaxRxAMPDUFactor = 3; // 2 is for 32 K and 3 is 64K
pCapELE->MPDUDensity = 0; // no density
}
//Supported MCS set
memcpy(pCapELE->MCS, ieee->Regdot11HTOperationalRateSet, 16);
if(pHT->IOTAction & HT_IOT_ACT_DISABLE_MCS15)
pCapELE->MCS[1] &= 0x7f;
if(pHT->IOTAction & HT_IOT_ACT_DISABLE_MCS14)
pCapELE->MCS[1] &= 0xbf;
if(pHT->IOTAction & HT_IOT_ACT_DISABLE_ALL_2SS)
pCapELE->MCS[1] &= 0x00;
// 2008.06.12
// For RTL819X, if pairwisekey = wep/tkip, ap is ralink, we support only MCS0~7.
if(ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev))
{
int i;
for(i = 1; i< 16; i++)
pCapELE->MCS[i] = 0;
}
//Extended HT Capability Info
memset(&pCapELE->ExtHTCapInfo, 0, 2);
//TXBF Capabilities
memset(pCapELE->TxBFCap, 0, 4);
//Antenna Selection Capabilities
pCapELE->ASCap = 0;
//add 2 to give space for element ID and len when construct frames
if(pHT->ePeerHTSpecVer == HT_SPEC_VER_EWC)
*len = 30 + 2;
else
*len = 26 + 2;
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA | IEEE80211_DL_HT, posHTCap, *len -2);
//Print each field in detail. Driver should not print out this message by default
// HTDebugHTCapability(posHTCap, (u8*)"HTConstructCapability()");
return;
}
/********************************************************************************************************************
*function: Construct Information Element in Beacon... if HTEnable is turned on
* input: struct ieee80211_device* ieee
* u8* posHTCap //pointer to store Information Ele
* u8* len //store len of
* u8 IsEncrypt //whether encrypt, needed further
* output: none
* return: none
* notice: posHTCap can't be null and be initialized before. only AP and IBSS sta should do this
* *****************************************************************************************************************/
void HTConstructInfoElement(struct ieee80211_device* ieee, u8* posHTInfo, u8* len, u8 IsEncrypt)
{
PRT_HIGH_THROUGHPUT pHT = ieee->pHTInfo;
PHT_INFORMATION_ELE pHTInfoEle = (PHT_INFORMATION_ELE)posHTInfo;
if ((posHTInfo == NULL) || (pHTInfoEle == NULL))
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "posHTInfo or pHTInfoEle can't be null in HTConstructInfoElement()\n");
return;
}
memset(posHTInfo, 0, *len);
if ( (ieee->iw_mode == IW_MODE_ADHOC) || (ieee->iw_mode == IW_MODE_MASTER)) //ap mode is not currently supported
{
pHTInfoEle->ControlChl = ieee->current_network.channel;
pHTInfoEle->ExtChlOffset = ((pHT->bRegBW40MHz == false)?HT_EXTCHNL_OFFSET_NO_EXT:
(ieee->current_network.channel<=6)?
HT_EXTCHNL_OFFSET_UPPER:HT_EXTCHNL_OFFSET_LOWER);
pHTInfoEle->RecommemdedTxWidth = pHT->bRegBW40MHz;
pHTInfoEle->RIFS = 0;
pHTInfoEle->PSMPAccessOnly = 0;
pHTInfoEle->SrvIntGranularity = 0;
pHTInfoEle->OptMode = pHT->CurrentOpMode;
pHTInfoEle->NonGFDevPresent = 0;
pHTInfoEle->DualBeacon = 0;
pHTInfoEle->SecondaryBeacon = 0;
pHTInfoEle->LSigTxopProtectFull = 0;
pHTInfoEle->PcoActive = 0;
pHTInfoEle->PcoPhase = 0;
memset(pHTInfoEle->BasicMSC, 0, 16);
*len = 22 + 2; //same above
}
else
{
//STA should not generate High Throughput Information Element
*len = 0;
}
//IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA | IEEE80211_DL_HT, posHTInfo, *len - 2);
//HTDebugHTInfo(posHTInfo, "HTConstructInforElement");
return;
}
/*
* According to experiment, Realtek AP to STA (based on rtl8190) may achieve best performance
* if both STA and AP set limitation of aggregation size to 32K, that is, set AMPDU density to 2
* (Ref: IEEE 11n specification). However, if Realtek STA associates to other AP, STA should set
* limitation of aggregation size to 8K, otherwise, performance of traffic stream from STA to AP
* will be much less than the traffic stream from AP to STA if both of the stream runs concurrently
* at the same time.
*
* Frame Format
* Element ID Length OUI Type1 Reserved
* 1 byte 1 byte 3 bytes 1 byte 1 byte
*
* OUI = 0x00, 0xe0, 0x4c,
* Type = 0x02
* Reserved = 0x00
*
* 2007.8.21 by Emily
*/
/********************************************************************************************************************
*function: Construct Information Element in Beacon... in RT2RT condition
* input: struct ieee80211_device* ieee
* u8* posRT2RTAgg //pointer to store Information Ele
* u8* len //store len
* output: none
* return: none
* notice:
* *****************************************************************************************************************/
void HTConstructRT2RTAggElement(struct ieee80211_device* ieee, u8* posRT2RTAgg, u8* len)
{
if (posRT2RTAgg == NULL) {
IEEE80211_DEBUG(IEEE80211_DL_ERR, "posRT2RTAgg can't be null in HTConstructRT2RTAggElement()\n");
return;
}
memset(posRT2RTAgg, 0, *len);
*posRT2RTAgg++ = 0x00;
*posRT2RTAgg++ = 0xe0;
*posRT2RTAgg++ = 0x4c;
*posRT2RTAgg++ = 0x02;
*posRT2RTAgg++ = 0x01;
*posRT2RTAgg = 0x10;//*posRT2RTAgg = 0x02;
if(ieee->bSupportRemoteWakeUp) {
*posRT2RTAgg |= 0x08;//RT_HT_CAP_USE_WOW;
}
*len = 6 + 2;
return;
#ifdef TODO
#if (HAL_CODE_BASE == RTL8192 && DEV_BUS_TYPE == USB_INTERFACE)
/*
//Emily. If it is required to Ask Realtek AP to send AMPDU during AES mode, enable this
section of code.
if(IS_UNDER_11N_AES_MODE(Adapter))
{
posRT2RTAgg->Octet[5] |=RT_HT_CAP_USE_AMPDU;
}else
{
posRT2RTAgg->Octet[5] &= 0xfb;
}
*/
#else
// Do Nothing
#endif
posRT2RTAgg->Length = 6;
#endif
}
/********************************************************************************************************************
*function: Pick the right Rate Adaptive table to use
* input: struct ieee80211_device* ieee
* u8* pOperateMCS //A pointer to MCS rate bitmap
* return: always we return true
* notice:
* *****************************************************************************************************************/
u8 HT_PickMCSRate(struct ieee80211_device* ieee, u8* pOperateMCS)
{
u8 i;
if (pOperateMCS == NULL)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "pOperateMCS can't be null in HT_PickMCSRate()\n");
return false;
}
switch(ieee->mode)
{
case IEEE_A:
case IEEE_B:
case IEEE_G:
//legacy rate routine handled at selectedrate
//no MCS rate
for(i=0;i<=15;i++){
pOperateMCS[i] = 0;
}
break;
case IEEE_N_24G: //assume CCK rate ok
case IEEE_N_5G:
// Legacy part we only use 6, 5.5,2,1 for N_24G and 6 for N_5G.
// Legacy part shall be handled at SelectRateSet().
//HT part
// TODO: may be different if we have different number of antenna
pOperateMCS[0] &=RATE_ADPT_1SS_MASK; //support MCS 0~7
pOperateMCS[1] &=RATE_ADPT_2SS_MASK;
pOperateMCS[3] &=RATE_ADPT_MCS32_MASK;
break;
//should never reach here
default:
break;
}
return true;
}
/*
* Description:
* This function will get the highest speed rate in input MCS set.
*
* /param Adapter Pionter to Adapter entity
* pMCSRateSet Pointer to MCS rate bitmap
* pMCSFilter Pointer to MCS rate filter
*
* /return Highest MCS rate included in pMCSRateSet and filtered by pMCSFilter.
*
*/
/********************************************************************************************************************
*function: This function will get the highest speed rate in input MCS set.
* input: struct ieee80211_device* ieee
* u8* pMCSRateSet //Pointer to MCS rate bitmap
* u8* pMCSFilter //Pointer to MCS rate filter
* return: Highest MCS rate included in pMCSRateSet and filtered by pMCSFilter
* notice:
* *****************************************************************************************************************/
u8 HTGetHighestMCSRate(struct ieee80211_device* ieee, u8* pMCSRateSet, u8* pMCSFilter)
{
u8 i, j;
u8 bitMap;
u8 mcsRate = 0;
u8 availableMcsRate[16];
if (pMCSRateSet == NULL || pMCSFilter == NULL)
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "pMCSRateSet or pMCSFilter can't be null in HTGetHighestMCSRate()\n");
return false;
}
for(i=0; i<16; i++)
availableMcsRate[i] = pMCSRateSet[i] & pMCSFilter[i];
for(i = 0; i < 16; i++)
{
if(availableMcsRate[i] != 0)
break;
}
if(i == 16)
return false;
for(i = 0; i < 16; i++)
{
if(availableMcsRate[i] != 0)
{
bitMap = availableMcsRate[i];
for(j = 0; j < 8; j++)
{
if((bitMap%2) != 0)
{
if(HTMcsToDataRate(ieee, (8*i+j)) > HTMcsToDataRate(ieee, mcsRate))
mcsRate = (8*i+j);
}
bitMap = bitMap>>1;
}
}
}
return (mcsRate|0x80);
}
/*
**
**1.Filter our operation rate set with AP's rate set
**2.shall reference channel bandwidth, STBC, Antenna number
**3.generate rate adative table for firmware
**David 20060906
**
** \pHTSupportedCap: the connected STA's supported rate Capability element
*/
u8 HTFilterMCSRate( struct ieee80211_device* ieee, u8* pSupportMCS, u8* pOperateMCS)
{
u8 i=0;
// filter out operational rate set not supported by AP, the lenth of it is 16
for(i=0;i<=15;i++){
pOperateMCS[i] = ieee->Regdot11HTOperationalRateSet[i]&pSupportMCS[i];
}
// TODO: adjust our operational rate set according to our channel bandwidth, STBC and Antenna number
// TODO: fill suggested rate adaptive rate index and give firmware info using Tx command packet
// we also shall suggested the first start rate set according to our singal strength
HT_PickMCSRate(ieee, pOperateMCS);
// For RTL819X, if pairwisekey = wep/tkip, we support only MCS0~7.
if(ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev))
pOperateMCS[1] = 0;
//
// For RTL819X, we support only MCS0~15.
// And also, we do not know how to use MCS32 now.
//
for(i=2; i<=15; i++)
pOperateMCS[i] = 0;
return true;
}
void HTSetConnectBwMode(struct ieee80211_device* ieee, HT_CHANNEL_WIDTH Bandwidth, HT_EXTCHNL_OFFSET Offset);
void HTOnAssocRsp(struct ieee80211_device *ieee)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
PHT_CAPABILITY_ELE pPeerHTCap = NULL;
PHT_INFORMATION_ELE pPeerHTInfo = NULL;
u16 nMaxAMSDUSize = 0;
u8* pMcsFilter = NULL;
static u8 EWC11NHTCap[] = {0x00, 0x90, 0x4c, 0x33}; // For 11n EWC definition, 2007.07.17, by Emily
static u8 EWC11NHTInfo[] = {0x00, 0x90, 0x4c, 0x34}; // For 11n EWC definition, 2007.07.17, by Emily
if( pHTInfo->bCurrentHTSupport == false )
{
IEEE80211_DEBUG(IEEE80211_DL_ERR, "<=== HTOnAssocRsp(): HT_DISABLE\n");
return;
}
IEEE80211_DEBUG(IEEE80211_DL_HT, "===> HTOnAssocRsp_wq(): HT_ENABLE\n");
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, pHTInfo->PeerHTCapBuf, sizeof(HT_CAPABILITY_ELE));
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA, pHTInfo->PeerHTInfoBuf, sizeof(HT_INFORMATION_ELE));
// HTDebugHTCapability(pHTInfo->PeerHTCapBuf,"HTOnAssocRsp_wq");
// HTDebugHTInfo(pHTInfo->PeerHTInfoBuf,"HTOnAssocRsp_wq");
//
if(!memcmp(pHTInfo->PeerHTCapBuf,EWC11NHTCap, sizeof(EWC11NHTCap)))
pPeerHTCap = (PHT_CAPABILITY_ELE)(&pHTInfo->PeerHTCapBuf[4]);
else
pPeerHTCap = (PHT_CAPABILITY_ELE)(pHTInfo->PeerHTCapBuf);
if(!memcmp(pHTInfo->PeerHTInfoBuf, EWC11NHTInfo, sizeof(EWC11NHTInfo)))
pPeerHTInfo = (PHT_INFORMATION_ELE)(&pHTInfo->PeerHTInfoBuf[4]);
else
pPeerHTInfo = (PHT_INFORMATION_ELE)(pHTInfo->PeerHTInfoBuf);
////////////////////////////////////////////////////////
// Configurations:
////////////////////////////////////////////////////////
IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_HT, pPeerHTCap, sizeof(HT_CAPABILITY_ELE));
// IEEE80211_DEBUG_DATA(IEEE80211_DL_DATA|IEEE80211_DL_HT, pPeerHTInfo, sizeof(HT_INFORMATION_ELE));
// Config Supported Channel Width setting
//
HTSetConnectBwMode(ieee, (HT_CHANNEL_WIDTH)(pPeerHTCap->ChlWidth), (HT_EXTCHNL_OFFSET)(pPeerHTInfo->ExtChlOffset));
// if(pHTInfo->bCurBW40MHz == true)
pHTInfo->bCurTxBW40MHz = ((pPeerHTInfo->RecommemdedTxWidth == 1)?true:false);
//
// Update short GI/ long GI setting
//
// TODO:
pHTInfo->bCurShortGI20MHz=
((pHTInfo->bRegShortGI20MHz)?((pPeerHTCap->ShortGI20Mhz==1)?true:false):false);
pHTInfo->bCurShortGI40MHz=
((pHTInfo->bRegShortGI40MHz)?((pPeerHTCap->ShortGI40Mhz==1)?true:false):false);
//
// Config TX STBC setting
//
// TODO:
//
// Config DSSS/CCK mode in 40MHz mode
//
// TODO:
pHTInfo->bCurSuppCCK =
((pHTInfo->bRegSuppCCK)?((pPeerHTCap->DssCCk==1)?true:false):false);
//
// Config and configure A-MSDU setting
//
pHTInfo->bCurrent_AMSDU_Support = pHTInfo->bAMSDU_Support;
nMaxAMSDUSize = (pPeerHTCap->MaxAMSDUSize==0)?3839:7935;
if(pHTInfo->nAMSDU_MaxSize > nMaxAMSDUSize )
pHTInfo->nCurrent_AMSDU_MaxSize = nMaxAMSDUSize;
else
pHTInfo->nCurrent_AMSDU_MaxSize = pHTInfo->nAMSDU_MaxSize;
//
// Config A-MPDU setting
//
pHTInfo->bCurrentAMPDUEnable = pHTInfo->bAMPDUEnable;
// <1> Decide AMPDU Factor
// By Emily
if(!pHTInfo->bRegRT2RTAggregation)
{
// Decide AMPDU Factor according to protocol handshake
if(pHTInfo->AMPDU_Factor > pPeerHTCap->MaxRxAMPDUFactor)
pHTInfo->CurrentAMPDUFactor = pPeerHTCap->MaxRxAMPDUFactor;
else
pHTInfo->CurrentAMPDUFactor = pHTInfo->AMPDU_Factor;
}else
{
// Set MPDU density to 2 to Realtek AP, and set it to 0 for others
// Replace MPDU factor declared in original association response frame format. 2007.08.20 by Emily
if (ieee->current_network.bssht.bdRT2RTAggregation)
{
if( ieee->pairwise_key_type != KEY_TYPE_NA)
// Realtek may set 32k in security mode and 64k for others
pHTInfo->CurrentAMPDUFactor = pPeerHTCap->MaxRxAMPDUFactor;
else
pHTInfo->CurrentAMPDUFactor = HT_AGG_SIZE_64K;
}else
{
if(pPeerHTCap->MaxRxAMPDUFactor < HT_AGG_SIZE_32K)
pHTInfo->CurrentAMPDUFactor = pPeerHTCap->MaxRxAMPDUFactor;
else
pHTInfo->CurrentAMPDUFactor = HT_AGG_SIZE_32K;
}
}
// <2> Set AMPDU Minimum MPDU Start Spacing
// 802.11n 3.0 section 9.7d.3
if(pHTInfo->MPDU_Density > pPeerHTCap->MPDUDensity)
pHTInfo->CurrentMPDUDensity = pHTInfo->MPDU_Density;
else
pHTInfo->CurrentMPDUDensity = pPeerHTCap->MPDUDensity;
if(ieee->pairwise_key_type != KEY_TYPE_NA )
pHTInfo->CurrentMPDUDensity = 7; // 8us
// Force TX AMSDU
// Lanhsin: mark for tmp to avoid deauth by ap from s3
//if(memcmp(pMgntInfo->Bssid, NETGEAR834Bv2_BROADCOM, 3)==0)
if(0)
{
pHTInfo->bCurrentAMPDUEnable = false;
pHTInfo->ForcedAMSDUMode = HT_AGG_FORCE_ENABLE;
pHTInfo->ForcedAMSDUMaxSize = 7935;
pHTInfo->IOTAction |= HT_IOT_ACT_TX_USE_AMSDU_8K;
}
// Rx Reorder Setting
pHTInfo->bCurRxReorderEnable = pHTInfo->bRegRxReorderEnable;
//
// Filter out unsupported HT rate for this AP
// Update RATR table
// This is only for 8190 ,8192 or later product which using firmware to handle rate adaptive mechanism.
//
// Handle Ralink AP bad MCS rate set condition. Joseph.
// This fix the bug of Ralink AP. This may be removed in the future.
if(pPeerHTCap->MCS[0] == 0)
pPeerHTCap->MCS[0] = 0xff;
HTFilterMCSRate(ieee, pPeerHTCap->MCS, ieee->dot11HTOperationalRateSet);
//
// Config MIMO Power Save setting
//
pHTInfo->PeerMimoPs = pPeerHTCap->MimoPwrSave;
if(pHTInfo->PeerMimoPs == MIMO_PS_STATIC)
pMcsFilter = MCS_FILTER_1SS;
else
pMcsFilter = MCS_FILTER_ALL;
//WB add for MCS8 bug
// pMcsFilter = MCS_FILTER_1SS;
ieee->HTHighestOperaRate = HTGetHighestMCSRate(ieee, ieee->dot11HTOperationalRateSet, pMcsFilter);
ieee->HTCurrentOperaRate = ieee->HTHighestOperaRate;
//
// Config current operation mode.
//
pHTInfo->CurrentOpMode = pPeerHTInfo->OptMode;
}
void HTSetConnectBwModeCallback(struct ieee80211_device* ieee);
/********************************************************************************************************************
*function: initialize HT info(struct PRT_HIGH_THROUGHPUT)
* input: struct ieee80211_device* ieee
* output: none
* return: none
* notice: This function is called when * (1) MPInitialization Phase * (2) Receiving of Deauthentication from AP
********************************************************************************************************************/
// TODO: Should this funciton be called when receiving of Disassociation?
void HTInitializeHTInfo(struct ieee80211_device* ieee)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
//
// These parameters will be reset when receiving deauthentication packet
//
IEEE80211_DEBUG(IEEE80211_DL_HT, "===========>%s()\n", __FUNCTION__);
pHTInfo->bCurrentHTSupport = false;
// 40MHz channel support
pHTInfo->bCurBW40MHz = false;
pHTInfo->bCurTxBW40MHz = false;
// Short GI support
pHTInfo->bCurShortGI20MHz = false;
pHTInfo->bCurShortGI40MHz = false;
pHTInfo->bForcedShortGI = false;
// CCK rate support
// This flag is set to true to support CCK rate by default.
// It will be affected by "pHTInfo->bRegSuppCCK" and AP capabilities only when associate to
// 11N BSS.
pHTInfo->bCurSuppCCK = true;
// AMSDU related
pHTInfo->bCurrent_AMSDU_Support = false;
pHTInfo->nCurrent_AMSDU_MaxSize = pHTInfo->nAMSDU_MaxSize;
// AMPUD related
pHTInfo->CurrentMPDUDensity = pHTInfo->MPDU_Density;
pHTInfo->CurrentAMPDUFactor = pHTInfo->AMPDU_Factor;
// Initialize all of the parameters related to 11n
memset((void*)(&(pHTInfo->SelfHTCap)), 0, sizeof(pHTInfo->SelfHTCap));
memset((void*)(&(pHTInfo->SelfHTInfo)), 0, sizeof(pHTInfo->SelfHTInfo));
memset((void*)(&(pHTInfo->PeerHTCapBuf)), 0, sizeof(pHTInfo->PeerHTCapBuf));
memset((void*)(&(pHTInfo->PeerHTInfoBuf)), 0, sizeof(pHTInfo->PeerHTInfoBuf));
pHTInfo->bSwBwInProgress = false;
pHTInfo->ChnlOp = CHNLOP_NONE;
// Set default IEEE spec for Draft N
pHTInfo->ePeerHTSpecVer = HT_SPEC_VER_IEEE;
// Realtek proprietary aggregation mode
pHTInfo->bCurrentRT2RTAggregation = false;
pHTInfo->bCurrentRT2RTLongSlotTime = false;
pHTInfo->IOTPeer = 0;
pHTInfo->IOTAction = 0;
//MCS rate initialized here
{
u8* RegHTSuppRateSets = &(ieee->RegHTSuppRateSet[0]);
RegHTSuppRateSets[0] = 0xFF; //support MCS 0~7
RegHTSuppRateSets[1] = 0xFF; //support MCS 8~15
RegHTSuppRateSets[4] = 0x01; //support MCS 32
}
}
/********************************************************************************************************************
*function: initialize Bss HT structure(struct PBSS_HT)
* input: PBSS_HT pBssHT //to be initialized
* output: none
* return: none
* notice: This function is called when initialize network structure
********************************************************************************************************************/
void HTInitializeBssDesc(PBSS_HT pBssHT)
{
pBssHT->bdSupportHT = false;
memset(pBssHT->bdHTCapBuf, 0, sizeof(pBssHT->bdHTCapBuf));
pBssHT->bdHTCapLen = 0;
memset(pBssHT->bdHTInfoBuf, 0, sizeof(pBssHT->bdHTInfoBuf));
pBssHT->bdHTInfoLen = 0;
pBssHT->bdHTSpecVer= HT_SPEC_VER_IEEE;
pBssHT->bdRT2RTAggregation = false;
pBssHT->bdRT2RTLongSlotTime = false;
}
/********************************************************************************************************************
*function: initialize Bss HT structure(struct PBSS_HT)
* input: struct ieee80211_device *ieee
* struct ieee80211_network *pNetwork //usually current network we are live in
* output: none
* return: none
* notice: This function should ONLY be called before association
********************************************************************************************************************/
void HTResetSelfAndSavePeerSetting(struct ieee80211_device* ieee, struct ieee80211_network * pNetwork)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
// u16 nMaxAMSDUSize;
// PHT_CAPABILITY_ELE pPeerHTCap = (PHT_CAPABILITY_ELE)pNetwork->bssht.bdHTCapBuf;
// PHT_INFORMATION_ELE pPeerHTInfo = (PHT_INFORMATION_ELE)pNetwork->bssht.bdHTInfoBuf;
// u8* pMcsFilter;
u8 bIOTAction = 0;
//
// Save Peer Setting before Association
//
IEEE80211_DEBUG(IEEE80211_DL_HT, "==============>%s()\n", __FUNCTION__);
/*unmark bEnableHT flag here is the same reason why unmarked in function ieee80211_softmac_new_net. WB 2008.09.10*/
// if( pHTInfo->bEnableHT && pNetwork->bssht.bdSupportHT)
if (pNetwork->bssht.bdSupportHT)
{
pHTInfo->bCurrentHTSupport = true;
pHTInfo->ePeerHTSpecVer = pNetwork->bssht.bdHTSpecVer;
// Save HTCap and HTInfo information Element
if(pNetwork->bssht.bdHTCapLen > 0 && pNetwork->bssht.bdHTCapLen <= sizeof(pHTInfo->PeerHTCapBuf))
memcpy(pHTInfo->PeerHTCapBuf, pNetwork->bssht.bdHTCapBuf, pNetwork->bssht.bdHTCapLen);
if(pNetwork->bssht.bdHTInfoLen > 0 && pNetwork->bssht.bdHTInfoLen <= sizeof(pHTInfo->PeerHTInfoBuf))
memcpy(pHTInfo->PeerHTInfoBuf, pNetwork->bssht.bdHTInfoBuf, pNetwork->bssht.bdHTInfoLen);
// Check whether RT to RT aggregation mode is enabled
if(pHTInfo->bRegRT2RTAggregation)
{
pHTInfo->bCurrentRT2RTAggregation = pNetwork->bssht.bdRT2RTAggregation;
pHTInfo->bCurrentRT2RTLongSlotTime = pNetwork->bssht.bdRT2RTLongSlotTime;
}
else
{
pHTInfo->bCurrentRT2RTAggregation = false;
pHTInfo->bCurrentRT2RTLongSlotTime = false;
}
// Determine the IOT Peer Vendor.
HTIOTPeerDetermine(ieee);
// Decide IOT Action
// Must be called after the parameter of pHTInfo->bCurrentRT2RTAggregation is decided
pHTInfo->IOTAction = 0;
bIOTAction = HTIOTActIsDisableMCS14(ieee, pNetwork->bssid);
if(bIOTAction)
pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_MCS14;
bIOTAction = HTIOTActIsDisableMCS15(ieee);
if(bIOTAction)
pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_MCS15;
bIOTAction = HTIOTActIsDisableMCSTwoSpatialStream(ieee, pNetwork->bssid);
if(bIOTAction)
pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_ALL_2SS;
bIOTAction = HTIOTActIsDisableEDCATurbo(ieee, pNetwork->bssid);
if(bIOTAction)
pHTInfo->IOTAction |= HT_IOT_ACT_DISABLE_EDCA_TURBO;
bIOTAction = HTIOTActIsMgntUseCCK6M(pNetwork);
if(bIOTAction)
pHTInfo->IOTAction |= HT_IOT_ACT_MGNT_USE_CCK_6M;
bIOTAction = HTIOTActIsCCDFsync(pNetwork->bssid);
if(bIOTAction)
pHTInfo->IOTAction |= HT_IOT_ACT_CDD_FSYNC;
}
else
{
pHTInfo->bCurrentHTSupport = false;
pHTInfo->bCurrentRT2RTAggregation = false;
pHTInfo->bCurrentRT2RTLongSlotTime = false;
pHTInfo->IOTAction = 0;
}
}
void HTUpdateSelfAndPeerSetting(struct ieee80211_device* ieee, struct ieee80211_network * pNetwork)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
// PHT_CAPABILITY_ELE pPeerHTCap = (PHT_CAPABILITY_ELE)pNetwork->bssht.bdHTCapBuf;
PHT_INFORMATION_ELE pPeerHTInfo = (PHT_INFORMATION_ELE)pNetwork->bssht.bdHTInfoBuf;
if(pHTInfo->bCurrentHTSupport)
{
//
// Config current operation mode.
//
if(pNetwork->bssht.bdHTInfoLen != 0)
pHTInfo->CurrentOpMode = pPeerHTInfo->OptMode;
//
// <TODO: Config according to OBSS non-HT STA present!!>
//
}
}
void HTUseDefaultSetting(struct ieee80211_device* ieee)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
// u8 regBwOpMode;
if(pHTInfo->bEnableHT)
{
pHTInfo->bCurrentHTSupport = true;
pHTInfo->bCurSuppCCK = pHTInfo->bRegSuppCCK;
pHTInfo->bCurBW40MHz = pHTInfo->bRegBW40MHz;
pHTInfo->bCurShortGI20MHz= pHTInfo->bRegShortGI20MHz;
pHTInfo->bCurShortGI40MHz= pHTInfo->bRegShortGI40MHz;
pHTInfo->bCurrent_AMSDU_Support = pHTInfo->bAMSDU_Support;
pHTInfo->nCurrent_AMSDU_MaxSize = pHTInfo->nAMSDU_MaxSize;
pHTInfo->bCurrentAMPDUEnable = pHTInfo->bAMPDUEnable;
pHTInfo->CurrentAMPDUFactor = pHTInfo->AMPDU_Factor;
pHTInfo->CurrentMPDUDensity = pHTInfo->MPDU_Density;
// Set BWOpMode register
//update RATR index0
HTFilterMCSRate(ieee, ieee->Regdot11HTOperationalRateSet, ieee->dot11HTOperationalRateSet);
//function below is not implemented at all. WB
#ifdef TODO
Adapter->HalFunc.InitHalRATRTableHandler( Adapter, &pMgntInfo->dot11OperationalRateSet, pMgntInfo->dot11HTOperationalRateSet);
#endif
ieee->HTHighestOperaRate = HTGetHighestMCSRate(ieee, ieee->dot11HTOperationalRateSet, MCS_FILTER_ALL);
ieee->HTCurrentOperaRate = ieee->HTHighestOperaRate;
}
else
{
pHTInfo->bCurrentHTSupport = false;
}
return;
}
/********************************************************************************************************************
*function: check whether HT control field exists
* input: struct ieee80211_device *ieee
* u8* pFrame //coming skb->data
* output: none
* return: return true if HT control field exists(false otherwise)
* notice:
********************************************************************************************************************/
u8 HTCCheck(struct ieee80211_device* ieee, u8* pFrame)
{
if(ieee->pHTInfo->bCurrentHTSupport)
{
if( (IsQoSDataFrame(pFrame) && Frame_Order(pFrame)) == 1)
{
IEEE80211_DEBUG(IEEE80211_DL_HT, "HT CONTROL FILED EXIST!!\n");
return true;
}
}
return false;
}
//
// This function set bandwidth mode in protocol layer.
//
void HTSetConnectBwMode(struct ieee80211_device* ieee, HT_CHANNEL_WIDTH Bandwidth, HT_EXTCHNL_OFFSET Offset)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
// u32 flags = 0;
if(pHTInfo->bRegBW40MHz == false)
return;
// To reduce dummy operation
// if((pHTInfo->bCurBW40MHz==false && Bandwidth==HT_CHANNEL_WIDTH_20) ||
// (pHTInfo->bCurBW40MHz==true && Bandwidth==HT_CHANNEL_WIDTH_20_40 && Offset==pHTInfo->CurSTAExtChnlOffset))
// return;
// spin_lock_irqsave(&(ieee->bw_spinlock), flags);
if(pHTInfo->bSwBwInProgress) {
// spin_unlock_irqrestore(&(ieee->bw_spinlock), flags);
return;
}
//if in half N mode, set to 20M bandwidth please 09.08.2008 WB.
if(Bandwidth==HT_CHANNEL_WIDTH_20_40 && (!ieee->GetHalfNmodeSupportByAPsHandler(ieee->dev)))
{
// Handle Illegal extension channel offset!!
if(ieee->current_network.channel<2 && Offset==HT_EXTCHNL_OFFSET_LOWER)
Offset = HT_EXTCHNL_OFFSET_NO_EXT;
if(Offset==HT_EXTCHNL_OFFSET_UPPER || Offset==HT_EXTCHNL_OFFSET_LOWER) {
pHTInfo->bCurBW40MHz = true;
pHTInfo->CurSTAExtChnlOffset = Offset;
} else {
pHTInfo->bCurBW40MHz = false;
pHTInfo->CurSTAExtChnlOffset = HT_EXTCHNL_OFFSET_NO_EXT;
}
} else {
pHTInfo->bCurBW40MHz = false;
pHTInfo->CurSTAExtChnlOffset = HT_EXTCHNL_OFFSET_NO_EXT;
}
pHTInfo->bSwBwInProgress = true;
// TODO: 2007.7.13 by Emily Wait 2000ms in order to guarantee that switching
// bandwidth is executed after scan is finished. It is a temporal solution
// because software should ganrantee the last operation of switching bandwidth
// is executed properlly.
HTSetConnectBwModeCallback(ieee);
// spin_unlock_irqrestore(&(ieee->bw_spinlock), flags);
}
void HTSetConnectBwModeCallback(struct ieee80211_device* ieee)
{
PRT_HIGH_THROUGHPUT pHTInfo = ieee->pHTInfo;
IEEE80211_DEBUG(IEEE80211_DL_HT, "======>%s()\n", __FUNCTION__);
if(pHTInfo->bCurBW40MHz)
{
if(pHTInfo->CurSTAExtChnlOffset==HT_EXTCHNL_OFFSET_UPPER)
ieee->set_chan(ieee->dev, ieee->current_network.channel+2);
else if(pHTInfo->CurSTAExtChnlOffset==HT_EXTCHNL_OFFSET_LOWER)
ieee->set_chan(ieee->dev, ieee->current_network.channel-2);
else
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->SetBWModeHandler(ieee->dev, HT_CHANNEL_WIDTH_20_40, pHTInfo->CurSTAExtChnlOffset);
} else {
ieee->set_chan(ieee->dev, ieee->current_network.channel);
ieee->SetBWModeHandler(ieee->dev, HT_CHANNEL_WIDTH_20, HT_EXTCHNL_OFFSET_NO_EXT);
}
pHTInfo->bSwBwInProgress = false;
}
EXPORT_SYMBOL(HTUpdateSelfAndPeerSetting);
| gpl-2.0 |
MoKee/android_kernel_samsung_ks01lte | drivers/staging/wlan-ng/hfa384x_usb.c | 8118 | 110790 | /* src/prism2/driver/hfa384x_usb.c
*
* Functions that talk to the USB variantof the Intersil hfa384x MAC
*
* Copyright (C) 1999 AbsoluteValue Systems, Inc. All Rights Reserved.
* --------------------------------------------------------------------
*
* linux-wlan
*
* 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.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU 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.
*
* --------------------------------------------------------------------
*
* Inquiries regarding the linux-wlan Open Source project can be
* made directly to:
*
* AbsoluteValue Systems Inc.
* info@linux-wlan.com
* http://www.linux-wlan.com
*
* --------------------------------------------------------------------
*
* Portions of the development of this software were funded by
* Intersil Corporation as part of PRISM(R) chipset product development.
*
* --------------------------------------------------------------------
*
* This file implements functions that correspond to the prism2/hfa384x
* 802.11 MAC hardware and firmware host interface.
*
* The functions can be considered to represent several levels of
* abstraction. The lowest level functions are simply C-callable wrappers
* around the register accesses. The next higher level represents C-callable
* prism2 API functions that match the Intersil documentation as closely
* as is reasonable. The next higher layer implements common sequences
* of invocations of the API layer (e.g. write to bap, followed by cmd).
*
* Common sequences:
* hfa384x_drvr_xxx Highest level abstractions provided by the
* hfa384x code. They are driver defined wrappers
* for common sequences. These functions generally
* use the services of the lower levels.
*
* hfa384x_drvr_xxxconfig An example of the drvr level abstraction. These
* functions are wrappers for the RID get/set
* sequence. They call copy_[to|from]_bap() and
* cmd_access(). These functions operate on the
* RIDs and buffers without validation. The caller
* is responsible for that.
*
* API wrapper functions:
* hfa384x_cmd_xxx functions that provide access to the f/w commands.
* The function arguments correspond to each command
* argument, even command arguments that get packed
* into single registers. These functions _just_
* issue the command by setting the cmd/parm regs
* & reading the status/resp regs. Additional
* activities required to fully use a command
* (read/write from/to bap, get/set int status etc.)
* are implemented separately. Think of these as
* C-callable prism2 commands.
*
* Lowest Layer Functions:
* hfa384x_docmd_xxx These functions implement the sequence required
* to issue any prism2 command. Primarily used by the
* hfa384x_cmd_xxx functions.
*
* hfa384x_bap_xxx BAP read/write access functions.
* Note: we usually use BAP0 for non-interrupt context
* and BAP1 for interrupt context.
*
* hfa384x_dl_xxx download related functions.
*
* Driver State Issues:
* Note that there are two pairs of functions that manage the
* 'initialized' and 'running' states of the hw/MAC combo. The four
* functions are create(), destroy(), start(), and stop(). create()
* sets up the data structures required to support the hfa384x_*
* functions and destroy() cleans them up. The start() function gets
* the actual hardware running and enables the interrupts. The stop()
* function shuts the hardware down. The sequence should be:
* create()
* start()
* .
* . Do interesting things w/ the hardware
* .
* stop()
* destroy()
*
* Note that destroy() can be called without calling stop() first.
* --------------------------------------------------------------------
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/wireless.h>
#include <linux/netdevice.h>
#include <linux/timer.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <asm/byteorder.h>
#include <linux/bitops.h>
#include <linux/list.h>
#include <linux/usb.h>
#include <linux/byteorder/generic.h>
#define SUBMIT_URB(u, f) usb_submit_urb(u, f)
#include "p80211types.h"
#include "p80211hdr.h"
#include "p80211mgmt.h"
#include "p80211conv.h"
#include "p80211msg.h"
#include "p80211netdev.h"
#include "p80211req.h"
#include "p80211metadef.h"
#include "p80211metastruct.h"
#include "hfa384x.h"
#include "prism2mgmt.h"
enum cmd_mode {
DOWAIT = 0,
DOASYNC
};
#define THROTTLE_JIFFIES (HZ/8)
#define URB_ASYNC_UNLINK 0
#define USB_QUEUE_BULK 0
#define ROUNDUP64(a) (((a)+63)&~63)
#ifdef DEBUG_USB
static void dbprint_urb(struct urb *urb);
#endif
static void
hfa384x_int_rxmonitor(wlandevice_t *wlandev, hfa384x_usb_rxfrm_t *rxfrm);
static void hfa384x_usb_defer(struct work_struct *data);
static int submit_rx_urb(hfa384x_t *hw, gfp_t flags);
static int submit_tx_urb(hfa384x_t *hw, struct urb *tx_urb, gfp_t flags);
/*---------------------------------------------------*/
/* Callbacks */
static void hfa384x_usbout_callback(struct urb *urb);
static void hfa384x_ctlxout_callback(struct urb *urb);
static void hfa384x_usbin_callback(struct urb *urb);
static void
hfa384x_usbin_txcompl(wlandevice_t *wlandev, hfa384x_usbin_t * usbin);
static void hfa384x_usbin_rx(wlandevice_t *wlandev, struct sk_buff *skb);
static void hfa384x_usbin_info(wlandevice_t *wlandev, hfa384x_usbin_t * usbin);
static void
hfa384x_usbout_tx(wlandevice_t *wlandev, hfa384x_usbout_t *usbout);
static void hfa384x_usbin_ctlx(hfa384x_t *hw, hfa384x_usbin_t *usbin,
int urb_status);
/*---------------------------------------------------*/
/* Functions to support the prism2 usb command queue */
static void hfa384x_usbctlxq_run(hfa384x_t *hw);
static void hfa384x_usbctlx_reqtimerfn(unsigned long data);
static void hfa384x_usbctlx_resptimerfn(unsigned long data);
static void hfa384x_usb_throttlefn(unsigned long data);
static void hfa384x_usbctlx_completion_task(unsigned long data);
static void hfa384x_usbctlx_reaper_task(unsigned long data);
static int hfa384x_usbctlx_submit(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx);
static void unlocked_usbctlx_complete(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx);
struct usbctlx_completor {
int (*complete) (struct usbctlx_completor *);
};
static int
hfa384x_usbctlx_complete_sync(hfa384x_t *hw,
hfa384x_usbctlx_t *ctlx,
struct usbctlx_completor *completor);
static int
unlocked_usbctlx_cancel_async(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx);
static void hfa384x_cb_status(hfa384x_t *hw, const hfa384x_usbctlx_t *ctlx);
static void hfa384x_cb_rrid(hfa384x_t *hw, const hfa384x_usbctlx_t *ctlx);
static int
usbctlx_get_status(const hfa384x_usb_cmdresp_t *cmdresp,
hfa384x_cmdresult_t *result);
static void
usbctlx_get_rridresult(const hfa384x_usb_rridresp_t *rridresp,
hfa384x_rridresult_t *result);
/*---------------------------------------------------*/
/* Low level req/resp CTLX formatters and submitters */
static int
hfa384x_docmd(hfa384x_t *hw,
enum cmd_mode mode,
hfa384x_metacmd_t *cmd,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data);
static int
hfa384x_dorrid(hfa384x_t *hw,
enum cmd_mode mode,
u16 rid,
void *riddata,
unsigned int riddatalen,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data);
static int
hfa384x_dowrid(hfa384x_t *hw,
enum cmd_mode mode,
u16 rid,
void *riddata,
unsigned int riddatalen,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data);
static int
hfa384x_dormem(hfa384x_t *hw,
enum cmd_mode mode,
u16 page,
u16 offset,
void *data,
unsigned int len,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data);
static int
hfa384x_dowmem(hfa384x_t *hw,
enum cmd_mode mode,
u16 page,
u16 offset,
void *data,
unsigned int len,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data);
static int hfa384x_isgood_pdrcode(u16 pdrcode);
static inline const char *ctlxstr(CTLX_STATE s)
{
static const char *ctlx_str[] = {
"Initial state",
"Complete",
"Request failed",
"Request pending",
"Request packet submitted",
"Request packet completed",
"Response packet completed"
};
return ctlx_str[s];
};
static inline hfa384x_usbctlx_t *get_active_ctlx(hfa384x_t * hw)
{
return list_entry(hw->ctlxq.active.next, hfa384x_usbctlx_t, list);
}
#ifdef DEBUG_USB
void dbprint_urb(struct urb *urb)
{
pr_debug("urb->pipe=0x%08x\n", urb->pipe);
pr_debug("urb->status=0x%08x\n", urb->status);
pr_debug("urb->transfer_flags=0x%08x\n", urb->transfer_flags);
pr_debug("urb->transfer_buffer=0x%08x\n",
(unsigned int)urb->transfer_buffer);
pr_debug("urb->transfer_buffer_length=0x%08x\n",
urb->transfer_buffer_length);
pr_debug("urb->actual_length=0x%08x\n", urb->actual_length);
pr_debug("urb->bandwidth=0x%08x\n", urb->bandwidth);
pr_debug("urb->setup_packet(ctl)=0x%08x\n",
(unsigned int)urb->setup_packet);
pr_debug("urb->start_frame(iso/irq)=0x%08x\n", urb->start_frame);
pr_debug("urb->interval(irq)=0x%08x\n", urb->interval);
pr_debug("urb->error_count(iso)=0x%08x\n", urb->error_count);
pr_debug("urb->timeout=0x%08x\n", urb->timeout);
pr_debug("urb->context=0x%08x\n", (unsigned int)urb->context);
pr_debug("urb->complete=0x%08x\n", (unsigned int)urb->complete);
}
#endif
/*----------------------------------------------------------------
* submit_rx_urb
*
* Listen for input data on the BULK-IN pipe. If the pipe has
* stalled then schedule it to be reset.
*
* Arguments:
* hw device struct
* memflags memory allocation flags
*
* Returns:
* error code from submission
*
* Call context:
* Any
----------------------------------------------------------------*/
static int submit_rx_urb(hfa384x_t *hw, gfp_t memflags)
{
struct sk_buff *skb;
int result;
skb = dev_alloc_skb(sizeof(hfa384x_usbin_t));
if (skb == NULL) {
result = -ENOMEM;
goto done;
}
/* Post the IN urb */
usb_fill_bulk_urb(&hw->rx_urb, hw->usb,
hw->endp_in,
skb->data, sizeof(hfa384x_usbin_t),
hfa384x_usbin_callback, hw->wlandev);
hw->rx_urb_skb = skb;
result = -ENOLINK;
if (!hw->wlandev->hwremoved &&
!test_bit(WORK_RX_HALT, &hw->usb_flags)) {
result = SUBMIT_URB(&hw->rx_urb, memflags);
/* Check whether we need to reset the RX pipe */
if (result == -EPIPE) {
printk(KERN_WARNING
"%s rx pipe stalled: requesting reset\n",
hw->wlandev->netdev->name);
if (!test_and_set_bit(WORK_RX_HALT, &hw->usb_flags))
schedule_work(&hw->usb_work);
}
}
/* Don't leak memory if anything should go wrong */
if (result != 0) {
dev_kfree_skb(skb);
hw->rx_urb_skb = NULL;
}
done:
return result;
}
/*----------------------------------------------------------------
* submit_tx_urb
*
* Prepares and submits the URB of transmitted data. If the
* submission fails then it will schedule the output pipe to
* be reset.
*
* Arguments:
* hw device struct
* tx_urb URB of data for tranmission
* memflags memory allocation flags
*
* Returns:
* error code from submission
*
* Call context:
* Any
----------------------------------------------------------------*/
static int submit_tx_urb(hfa384x_t *hw, struct urb *tx_urb, gfp_t memflags)
{
struct net_device *netdev = hw->wlandev->netdev;
int result;
result = -ENOLINK;
if (netif_running(netdev)) {
if (!hw->wlandev->hwremoved
&& !test_bit(WORK_TX_HALT, &hw->usb_flags)) {
result = SUBMIT_URB(tx_urb, memflags);
/* Test whether we need to reset the TX pipe */
if (result == -EPIPE) {
printk(KERN_WARNING
"%s tx pipe stalled: requesting reset\n",
netdev->name);
set_bit(WORK_TX_HALT, &hw->usb_flags);
schedule_work(&hw->usb_work);
} else if (result == 0) {
netif_stop_queue(netdev);
}
}
}
return result;
}
/*----------------------------------------------------------------
* hfa394x_usb_defer
*
* There are some things that the USB stack cannot do while
* in interrupt context, so we arrange this function to run
* in process context.
*
* Arguments:
* hw device structure
*
* Returns:
* nothing
*
* Call context:
* process (by design)
----------------------------------------------------------------*/
static void hfa384x_usb_defer(struct work_struct *data)
{
hfa384x_t *hw = container_of(data, struct hfa384x, usb_work);
struct net_device *netdev = hw->wlandev->netdev;
/* Don't bother trying to reset anything if the plug
* has been pulled ...
*/
if (hw->wlandev->hwremoved)
return;
/* Reception has stopped: try to reset the input pipe */
if (test_bit(WORK_RX_HALT, &hw->usb_flags)) {
int ret;
usb_kill_urb(&hw->rx_urb); /* Cannot be holding spinlock! */
ret = usb_clear_halt(hw->usb, hw->endp_in);
if (ret != 0) {
printk(KERN_ERR
"Failed to clear rx pipe for %s: err=%d\n",
netdev->name, ret);
} else {
printk(KERN_INFO "%s rx pipe reset complete.\n",
netdev->name);
clear_bit(WORK_RX_HALT, &hw->usb_flags);
set_bit(WORK_RX_RESUME, &hw->usb_flags);
}
}
/* Resume receiving data back from the device. */
if (test_bit(WORK_RX_RESUME, &hw->usb_flags)) {
int ret;
ret = submit_rx_urb(hw, GFP_KERNEL);
if (ret != 0) {
printk(KERN_ERR
"Failed to resume %s rx pipe.\n", netdev->name);
} else {
clear_bit(WORK_RX_RESUME, &hw->usb_flags);
}
}
/* Transmission has stopped: try to reset the output pipe */
if (test_bit(WORK_TX_HALT, &hw->usb_flags)) {
int ret;
usb_kill_urb(&hw->tx_urb);
ret = usb_clear_halt(hw->usb, hw->endp_out);
if (ret != 0) {
printk(KERN_ERR
"Failed to clear tx pipe for %s: err=%d\n",
netdev->name, ret);
} else {
printk(KERN_INFO "%s tx pipe reset complete.\n",
netdev->name);
clear_bit(WORK_TX_HALT, &hw->usb_flags);
set_bit(WORK_TX_RESUME, &hw->usb_flags);
/* Stopping the BULK-OUT pipe also blocked
* us from sending any more CTLX URBs, so
* we need to re-run our queue ...
*/
hfa384x_usbctlxq_run(hw);
}
}
/* Resume transmitting. */
if (test_and_clear_bit(WORK_TX_RESUME, &hw->usb_flags))
netif_wake_queue(hw->wlandev->netdev);
}
/*----------------------------------------------------------------
* hfa384x_create
*
* Sets up the hfa384x_t data structure for use. Note this
* does _not_ initialize the actual hardware, just the data structures
* we use to keep track of its state.
*
* Arguments:
* hw device structure
* irq device irq number
* iobase i/o base address for register access
* membase memory base address for register access
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
void hfa384x_create(hfa384x_t *hw, struct usb_device *usb)
{
memset(hw, 0, sizeof(hfa384x_t));
hw->usb = usb;
/* set up the endpoints */
hw->endp_in = usb_rcvbulkpipe(usb, 1);
hw->endp_out = usb_sndbulkpipe(usb, 2);
/* Set up the waitq */
init_waitqueue_head(&hw->cmdq);
/* Initialize the command queue */
spin_lock_init(&hw->ctlxq.lock);
INIT_LIST_HEAD(&hw->ctlxq.pending);
INIT_LIST_HEAD(&hw->ctlxq.active);
INIT_LIST_HEAD(&hw->ctlxq.completing);
INIT_LIST_HEAD(&hw->ctlxq.reapable);
/* Initialize the authentication queue */
skb_queue_head_init(&hw->authq);
tasklet_init(&hw->reaper_bh,
hfa384x_usbctlx_reaper_task, (unsigned long)hw);
tasklet_init(&hw->completion_bh,
hfa384x_usbctlx_completion_task, (unsigned long)hw);
INIT_WORK(&hw->link_bh, prism2sta_processing_defer);
INIT_WORK(&hw->usb_work, hfa384x_usb_defer);
init_timer(&hw->throttle);
hw->throttle.function = hfa384x_usb_throttlefn;
hw->throttle.data = (unsigned long)hw;
init_timer(&hw->resptimer);
hw->resptimer.function = hfa384x_usbctlx_resptimerfn;
hw->resptimer.data = (unsigned long)hw;
init_timer(&hw->reqtimer);
hw->reqtimer.function = hfa384x_usbctlx_reqtimerfn;
hw->reqtimer.data = (unsigned long)hw;
usb_init_urb(&hw->rx_urb);
usb_init_urb(&hw->tx_urb);
usb_init_urb(&hw->ctlx_urb);
hw->link_status = HFA384x_LINK_NOTCONNECTED;
hw->state = HFA384x_STATE_INIT;
INIT_WORK(&hw->commsqual_bh, prism2sta_commsqual_defer);
init_timer(&hw->commsqual_timer);
hw->commsqual_timer.data = (unsigned long)hw;
hw->commsqual_timer.function = prism2sta_commsqual_timer;
}
/*----------------------------------------------------------------
* hfa384x_destroy
*
* Partner to hfa384x_create(). This function cleans up the hw
* structure so that it can be freed by the caller using a simple
* kfree. Currently, this function is just a placeholder. If, at some
* point in the future, an hw in the 'shutdown' state requires a 'deep'
* kfree, this is where it should be done. Note that if this function
* is called on a _running_ hw structure, the drvr_stop() function is
* called.
*
* Arguments:
* hw device structure
*
* Returns:
* nothing, this function is not allowed to fail.
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
void hfa384x_destroy(hfa384x_t *hw)
{
struct sk_buff *skb;
if (hw->state == HFA384x_STATE_RUNNING)
hfa384x_drvr_stop(hw);
hw->state = HFA384x_STATE_PREINIT;
kfree(hw->scanresults);
hw->scanresults = NULL;
/* Now to clean out the auth queue */
while ((skb = skb_dequeue(&hw->authq)))
dev_kfree_skb(skb);
}
static hfa384x_usbctlx_t *usbctlx_alloc(void)
{
hfa384x_usbctlx_t *ctlx;
ctlx = kmalloc(sizeof(*ctlx), in_interrupt() ? GFP_ATOMIC : GFP_KERNEL);
if (ctlx != NULL) {
memset(ctlx, 0, sizeof(*ctlx));
init_completion(&ctlx->done);
}
return ctlx;
}
static int
usbctlx_get_status(const hfa384x_usb_cmdresp_t *cmdresp,
hfa384x_cmdresult_t *result)
{
result->status = le16_to_cpu(cmdresp->status);
result->resp0 = le16_to_cpu(cmdresp->resp0);
result->resp1 = le16_to_cpu(cmdresp->resp1);
result->resp2 = le16_to_cpu(cmdresp->resp2);
pr_debug("cmdresult:status=0x%04x "
"resp0=0x%04x resp1=0x%04x resp2=0x%04x\n",
result->status, result->resp0, result->resp1, result->resp2);
return result->status & HFA384x_STATUS_RESULT;
}
static void
usbctlx_get_rridresult(const hfa384x_usb_rridresp_t *rridresp,
hfa384x_rridresult_t *result)
{
result->rid = le16_to_cpu(rridresp->rid);
result->riddata = rridresp->data;
result->riddata_len = ((le16_to_cpu(rridresp->frmlen) - 1) * 2);
}
/*----------------------------------------------------------------
* Completor object:
* This completor must be passed to hfa384x_usbctlx_complete_sync()
* when processing a CTLX that returns a hfa384x_cmdresult_t structure.
----------------------------------------------------------------*/
struct usbctlx_cmd_completor {
struct usbctlx_completor head;
const hfa384x_usb_cmdresp_t *cmdresp;
hfa384x_cmdresult_t *result;
};
static inline int usbctlx_cmd_completor_fn(struct usbctlx_completor *head)
{
struct usbctlx_cmd_completor *complete;
complete = (struct usbctlx_cmd_completor *) head;
return usbctlx_get_status(complete->cmdresp, complete->result);
}
static inline struct usbctlx_completor *init_cmd_completor(
struct usbctlx_cmd_completor
*completor,
const hfa384x_usb_cmdresp_t
*cmdresp,
hfa384x_cmdresult_t *result)
{
completor->head.complete = usbctlx_cmd_completor_fn;
completor->cmdresp = cmdresp;
completor->result = result;
return &(completor->head);
}
/*----------------------------------------------------------------
* Completor object:
* This completor must be passed to hfa384x_usbctlx_complete_sync()
* when processing a CTLX that reads a RID.
----------------------------------------------------------------*/
struct usbctlx_rrid_completor {
struct usbctlx_completor head;
const hfa384x_usb_rridresp_t *rridresp;
void *riddata;
unsigned int riddatalen;
};
static int usbctlx_rrid_completor_fn(struct usbctlx_completor *head)
{
struct usbctlx_rrid_completor *complete;
hfa384x_rridresult_t rridresult;
complete = (struct usbctlx_rrid_completor *) head;
usbctlx_get_rridresult(complete->rridresp, &rridresult);
/* Validate the length, note body len calculation in bytes */
if (rridresult.riddata_len != complete->riddatalen) {
printk(KERN_WARNING
"RID len mismatch, rid=0x%04x hlen=%d fwlen=%d\n",
rridresult.rid,
complete->riddatalen, rridresult.riddata_len);
return -ENODATA;
}
memcpy(complete->riddata, rridresult.riddata, complete->riddatalen);
return 0;
}
static inline struct usbctlx_completor *init_rrid_completor(
struct usbctlx_rrid_completor
*completor,
const hfa384x_usb_rridresp_t
*rridresp,
void *riddata,
unsigned int riddatalen)
{
completor->head.complete = usbctlx_rrid_completor_fn;
completor->rridresp = rridresp;
completor->riddata = riddata;
completor->riddatalen = riddatalen;
return &(completor->head);
}
/*----------------------------------------------------------------
* Completor object:
* Interprets the results of a synchronous RID-write
----------------------------------------------------------------*/
typedef struct usbctlx_cmd_completor usbctlx_wrid_completor_t;
#define init_wrid_completor init_cmd_completor
/*----------------------------------------------------------------
* Completor object:
* Interprets the results of a synchronous memory-write
----------------------------------------------------------------*/
typedef struct usbctlx_cmd_completor usbctlx_wmem_completor_t;
#define init_wmem_completor init_cmd_completor
/*----------------------------------------------------------------
* Completor object:
* Interprets the results of a synchronous memory-read
----------------------------------------------------------------*/
struct usbctlx_rmem_completor {
struct usbctlx_completor head;
const hfa384x_usb_rmemresp_t *rmemresp;
void *data;
unsigned int len;
};
typedef struct usbctlx_rmem_completor usbctlx_rmem_completor_t;
static int usbctlx_rmem_completor_fn(struct usbctlx_completor *head)
{
usbctlx_rmem_completor_t *complete = (usbctlx_rmem_completor_t *) head;
pr_debug("rmemresp:len=%d\n", complete->rmemresp->frmlen);
memcpy(complete->data, complete->rmemresp->data, complete->len);
return 0;
}
static inline struct usbctlx_completor *init_rmem_completor(
usbctlx_rmem_completor_t
*completor,
hfa384x_usb_rmemresp_t
*rmemresp,
void *data,
unsigned int len)
{
completor->head.complete = usbctlx_rmem_completor_fn;
completor->rmemresp = rmemresp;
completor->data = data;
completor->len = len;
return &(completor->head);
}
/*----------------------------------------------------------------
* hfa384x_cb_status
*
* Ctlx_complete handler for async CMD type control exchanges.
* mark the hw struct as such.
*
* Note: If the handling is changed here, it should probably be
* changed in docmd as well.
*
* Arguments:
* hw hw struct
* ctlx completed CTLX
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_cb_status(hfa384x_t *hw, const hfa384x_usbctlx_t *ctlx)
{
if (ctlx->usercb != NULL) {
hfa384x_cmdresult_t cmdresult;
if (ctlx->state != CTLX_COMPLETE) {
memset(&cmdresult, 0, sizeof(cmdresult));
cmdresult.status =
HFA384x_STATUS_RESULT_SET(HFA384x_CMD_ERR);
} else {
usbctlx_get_status(&ctlx->inbuf.cmdresp, &cmdresult);
}
ctlx->usercb(hw, &cmdresult, ctlx->usercb_data);
}
}
/*----------------------------------------------------------------
* hfa384x_cb_rrid
*
* CTLX completion handler for async RRID type control exchanges.
*
* Note: If the handling is changed here, it should probably be
* changed in dorrid as well.
*
* Arguments:
* hw hw struct
* ctlx completed CTLX
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_cb_rrid(hfa384x_t *hw, const hfa384x_usbctlx_t *ctlx)
{
if (ctlx->usercb != NULL) {
hfa384x_rridresult_t rridresult;
if (ctlx->state != CTLX_COMPLETE) {
memset(&rridresult, 0, sizeof(rridresult));
rridresult.rid = le16_to_cpu(ctlx->outbuf.rridreq.rid);
} else {
usbctlx_get_rridresult(&ctlx->inbuf.rridresp,
&rridresult);
}
ctlx->usercb(hw, &rridresult, ctlx->usercb_data);
}
}
static inline int hfa384x_docmd_wait(hfa384x_t *hw, hfa384x_metacmd_t *cmd)
{
return hfa384x_docmd(hw, DOWAIT, cmd, NULL, NULL, NULL);
}
static inline int
hfa384x_docmd_async(hfa384x_t *hw,
hfa384x_metacmd_t *cmd,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data)
{
return hfa384x_docmd(hw, DOASYNC, cmd, cmdcb, usercb, usercb_data);
}
static inline int
hfa384x_dorrid_wait(hfa384x_t *hw, u16 rid, void *riddata,
unsigned int riddatalen)
{
return hfa384x_dorrid(hw, DOWAIT,
rid, riddata, riddatalen, NULL, NULL, NULL);
}
static inline int
hfa384x_dorrid_async(hfa384x_t *hw,
u16 rid, void *riddata, unsigned int riddatalen,
ctlx_cmdcb_t cmdcb,
ctlx_usercb_t usercb, void *usercb_data)
{
return hfa384x_dorrid(hw, DOASYNC,
rid, riddata, riddatalen,
cmdcb, usercb, usercb_data);
}
static inline int
hfa384x_dowrid_wait(hfa384x_t *hw, u16 rid, void *riddata,
unsigned int riddatalen)
{
return hfa384x_dowrid(hw, DOWAIT,
rid, riddata, riddatalen, NULL, NULL, NULL);
}
static inline int
hfa384x_dowrid_async(hfa384x_t *hw,
u16 rid, void *riddata, unsigned int riddatalen,
ctlx_cmdcb_t cmdcb,
ctlx_usercb_t usercb, void *usercb_data)
{
return hfa384x_dowrid(hw, DOASYNC,
rid, riddata, riddatalen,
cmdcb, usercb, usercb_data);
}
static inline int
hfa384x_dormem_wait(hfa384x_t *hw,
u16 page, u16 offset, void *data, unsigned int len)
{
return hfa384x_dormem(hw, DOWAIT,
page, offset, data, len, NULL, NULL, NULL);
}
static inline int
hfa384x_dormem_async(hfa384x_t *hw,
u16 page, u16 offset, void *data, unsigned int len,
ctlx_cmdcb_t cmdcb,
ctlx_usercb_t usercb, void *usercb_data)
{
return hfa384x_dormem(hw, DOASYNC,
page, offset, data, len,
cmdcb, usercb, usercb_data);
}
static inline int
hfa384x_dowmem_wait(hfa384x_t *hw,
u16 page, u16 offset, void *data, unsigned int len)
{
return hfa384x_dowmem(hw, DOWAIT,
page, offset, data, len, NULL, NULL, NULL);
}
static inline int
hfa384x_dowmem_async(hfa384x_t *hw,
u16 page,
u16 offset,
void *data,
unsigned int len,
ctlx_cmdcb_t cmdcb,
ctlx_usercb_t usercb, void *usercb_data)
{
return hfa384x_dowmem(hw, DOASYNC,
page, offset, data, len,
cmdcb, usercb, usercb_data);
}
/*----------------------------------------------------------------
* hfa384x_cmd_initialize
*
* Issues the initialize command and sets the hw->state based
* on the result.
*
* Arguments:
* hw device structure
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_cmd_initialize(hfa384x_t *hw)
{
int result = 0;
int i;
hfa384x_metacmd_t cmd;
cmd.cmd = HFA384x_CMDCODE_INIT;
cmd.parm0 = 0;
cmd.parm1 = 0;
cmd.parm2 = 0;
result = hfa384x_docmd_wait(hw, &cmd);
pr_debug("cmdresp.init: "
"status=0x%04x, resp0=0x%04x, "
"resp1=0x%04x, resp2=0x%04x\n",
cmd.result.status,
cmd.result.resp0, cmd.result.resp1, cmd.result.resp2);
if (result == 0) {
for (i = 0; i < HFA384x_NUMPORTS_MAX; i++)
hw->port_enabled[i] = 0;
}
hw->link_status = HFA384x_LINK_NOTCONNECTED;
return result;
}
/*----------------------------------------------------------------
* hfa384x_cmd_disable
*
* Issues the disable command to stop communications on one of
* the MACs 'ports'.
*
* Arguments:
* hw device structure
* macport MAC port number (host order)
*
* Returns:
* 0 success
* >0 f/w reported failure - f/w status code
* <0 driver reported error (timeout|bad arg)
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_cmd_disable(hfa384x_t *hw, u16 macport)
{
int result = 0;
hfa384x_metacmd_t cmd;
cmd.cmd = HFA384x_CMD_CMDCODE_SET(HFA384x_CMDCODE_DISABLE) |
HFA384x_CMD_MACPORT_SET(macport);
cmd.parm0 = 0;
cmd.parm1 = 0;
cmd.parm2 = 0;
result = hfa384x_docmd_wait(hw, &cmd);
return result;
}
/*----------------------------------------------------------------
* hfa384x_cmd_enable
*
* Issues the enable command to enable communications on one of
* the MACs 'ports'.
*
* Arguments:
* hw device structure
* macport MAC port number
*
* Returns:
* 0 success
* >0 f/w reported failure - f/w status code
* <0 driver reported error (timeout|bad arg)
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_cmd_enable(hfa384x_t *hw, u16 macport)
{
int result = 0;
hfa384x_metacmd_t cmd;
cmd.cmd = HFA384x_CMD_CMDCODE_SET(HFA384x_CMDCODE_ENABLE) |
HFA384x_CMD_MACPORT_SET(macport);
cmd.parm0 = 0;
cmd.parm1 = 0;
cmd.parm2 = 0;
result = hfa384x_docmd_wait(hw, &cmd);
return result;
}
/*----------------------------------------------------------------
* hfa384x_cmd_monitor
*
* Enables the 'monitor mode' of the MAC. Here's the description of
* monitor mode that I've received thus far:
*
* "The "monitor mode" of operation is that the MAC passes all
* frames for which the PLCP checks are correct. All received
* MPDUs are passed to the host with MAC Port = 7, with a
* receive status of good, FCS error, or undecryptable. Passing
* certain MPDUs is a violation of the 802.11 standard, but useful
* for a debugging tool." Normal communication is not possible
* while monitor mode is enabled.
*
* Arguments:
* hw device structure
* enable a code (0x0b|0x0f) that enables/disables
* monitor mode. (host order)
*
* Returns:
* 0 success
* >0 f/w reported failure - f/w status code
* <0 driver reported error (timeout|bad arg)
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_cmd_monitor(hfa384x_t *hw, u16 enable)
{
int result = 0;
hfa384x_metacmd_t cmd;
cmd.cmd = HFA384x_CMD_CMDCODE_SET(HFA384x_CMDCODE_MONITOR) |
HFA384x_CMD_AINFO_SET(enable);
cmd.parm0 = 0;
cmd.parm1 = 0;
cmd.parm2 = 0;
result = hfa384x_docmd_wait(hw, &cmd);
return result;
}
/*----------------------------------------------------------------
* hfa384x_cmd_download
*
* Sets the controls for the MAC controller code/data download
* process. The arguments set the mode and address associated
* with a download. Note that the aux registers should be enabled
* prior to setting one of the download enable modes.
*
* Arguments:
* hw device structure
* mode 0 - Disable programming and begin code exec
* 1 - Enable volatile mem programming
* 2 - Enable non-volatile mem programming
* 3 - Program non-volatile section from NV download
* buffer.
* (host order)
* lowaddr
* highaddr For mode 1, sets the high & low order bits of
* the "destination address". This address will be
* the execution start address when download is
* subsequently disabled.
* For mode 2, sets the high & low order bits of
* the destination in NV ram.
* For modes 0 & 3, should be zero. (host order)
* NOTE: these are CMD format.
* codelen Length of the data to write in mode 2,
* zero otherwise. (host order)
*
* Returns:
* 0 success
* >0 f/w reported failure - f/w status code
* <0 driver reported error (timeout|bad arg)
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_cmd_download(hfa384x_t *hw, u16 mode, u16 lowaddr,
u16 highaddr, u16 codelen)
{
int result = 0;
hfa384x_metacmd_t cmd;
pr_debug("mode=%d, lowaddr=0x%04x, highaddr=0x%04x, codelen=%d\n",
mode, lowaddr, highaddr, codelen);
cmd.cmd = (HFA384x_CMD_CMDCODE_SET(HFA384x_CMDCODE_DOWNLD) |
HFA384x_CMD_PROGMODE_SET(mode));
cmd.parm0 = lowaddr;
cmd.parm1 = highaddr;
cmd.parm2 = codelen;
result = hfa384x_docmd_wait(hw, &cmd);
return result;
}
/*----------------------------------------------------------------
* hfa384x_corereset
*
* Perform a reset of the hfa38xx MAC core. We assume that the hw
* structure is in its "created" state. That is, it is initialized
* with proper values. Note that if a reset is done after the
* device has been active for awhile, the caller might have to clean
* up some leftover cruft in the hw structure.
*
* Arguments:
* hw device structure
* holdtime how long (in ms) to hold the reset
* settletime how long (in ms) to wait after releasing
* the reset
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_corereset(hfa384x_t *hw, int holdtime, int settletime, int genesis)
{
int result = 0;
result = usb_reset_device(hw->usb);
if (result < 0) {
printk(KERN_ERR "usb_reset_device() failed, result=%d.\n",
result);
}
return result;
}
/*----------------------------------------------------------------
* hfa384x_usbctlx_complete_sync
*
* Waits for a synchronous CTLX object to complete,
* and then handles the response.
*
* Arguments:
* hw device structure
* ctlx CTLX ptr
* completor functor object to decide what to
* do with the CTLX's result.
*
* Returns:
* 0 Success
* -ERESTARTSYS Interrupted by a signal
* -EIO CTLX failed
* -ENODEV Adapter was unplugged
* ??? Result from completor
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
static int hfa384x_usbctlx_complete_sync(hfa384x_t *hw,
hfa384x_usbctlx_t *ctlx,
struct usbctlx_completor *completor)
{
unsigned long flags;
int result;
result = wait_for_completion_interruptible(&ctlx->done);
spin_lock_irqsave(&hw->ctlxq.lock, flags);
/*
* We can only handle the CTLX if the USB disconnect
* function has not run yet ...
*/
cleanup:
if (hw->wlandev->hwremoved) {
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
result = -ENODEV;
} else if (result != 0) {
int runqueue = 0;
/*
* We were probably interrupted, so delete
* this CTLX asynchronously, kill the timers
* and the URB, and then start the next
* pending CTLX.
*
* NOTE: We can only delete the timers and
* the URB if this CTLX is active.
*/
if (ctlx == get_active_ctlx(hw)) {
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
del_singleshot_timer_sync(&hw->reqtimer);
del_singleshot_timer_sync(&hw->resptimer);
hw->req_timer_done = 1;
hw->resp_timer_done = 1;
usb_kill_urb(&hw->ctlx_urb);
spin_lock_irqsave(&hw->ctlxq.lock, flags);
runqueue = 1;
/*
* This scenario is so unlikely that I'm
* happy with a grubby "goto" solution ...
*/
if (hw->wlandev->hwremoved)
goto cleanup;
}
/*
* The completion task will send this CTLX
* to the reaper the next time it runs. We
* are no longer in a hurry.
*/
ctlx->reapable = 1;
ctlx->state = CTLX_REQ_FAILED;
list_move_tail(&ctlx->list, &hw->ctlxq.completing);
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
if (runqueue)
hfa384x_usbctlxq_run(hw);
} else {
if (ctlx->state == CTLX_COMPLETE) {
result = completor->complete(completor);
} else {
printk(KERN_WARNING "CTLX[%d] error: state(%s)\n",
le16_to_cpu(ctlx->outbuf.type),
ctlxstr(ctlx->state));
result = -EIO;
}
list_del(&ctlx->list);
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
kfree(ctlx);
}
return result;
}
/*----------------------------------------------------------------
* hfa384x_docmd
*
* Constructs a command CTLX and submits it.
*
* NOTE: Any changes to the 'post-submit' code in this function
* need to be carried over to hfa384x_cbcmd() since the handling
* is virtually identical.
*
* Arguments:
* hw device structure
* mode DOWAIT or DOASYNC
* cmd cmd structure. Includes all arguments and result
* data points. All in host order. in host order
* cmdcb command-specific callback
* usercb user callback for async calls, NULL for DOWAIT calls
* usercb_data user supplied data pointer for async calls, NULL
* for DOASYNC calls
*
* Returns:
* 0 success
* -EIO CTLX failure
* -ERESTARTSYS Awakened on signal
* >0 command indicated error, Status and Resp0-2 are
* in hw structure.
*
* Side effects:
*
*
* Call context:
* process
----------------------------------------------------------------*/
static int
hfa384x_docmd(hfa384x_t *hw,
enum cmd_mode mode,
hfa384x_metacmd_t *cmd,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data)
{
int result;
hfa384x_usbctlx_t *ctlx;
ctlx = usbctlx_alloc();
if (ctlx == NULL) {
result = -ENOMEM;
goto done;
}
/* Initialize the command */
ctlx->outbuf.cmdreq.type = cpu_to_le16(HFA384x_USB_CMDREQ);
ctlx->outbuf.cmdreq.cmd = cpu_to_le16(cmd->cmd);
ctlx->outbuf.cmdreq.parm0 = cpu_to_le16(cmd->parm0);
ctlx->outbuf.cmdreq.parm1 = cpu_to_le16(cmd->parm1);
ctlx->outbuf.cmdreq.parm2 = cpu_to_le16(cmd->parm2);
ctlx->outbufsize = sizeof(ctlx->outbuf.cmdreq);
pr_debug("cmdreq: cmd=0x%04x "
"parm0=0x%04x parm1=0x%04x parm2=0x%04x\n",
cmd->cmd, cmd->parm0, cmd->parm1, cmd->parm2);
ctlx->reapable = mode;
ctlx->cmdcb = cmdcb;
ctlx->usercb = usercb;
ctlx->usercb_data = usercb_data;
result = hfa384x_usbctlx_submit(hw, ctlx);
if (result != 0) {
kfree(ctlx);
} else if (mode == DOWAIT) {
struct usbctlx_cmd_completor completor;
result =
hfa384x_usbctlx_complete_sync(hw, ctlx,
init_cmd_completor(&completor,
&ctlx->
inbuf.
cmdresp,
&cmd->
result));
}
done:
return result;
}
/*----------------------------------------------------------------
* hfa384x_dorrid
*
* Constructs a read rid CTLX and issues it.
*
* NOTE: Any changes to the 'post-submit' code in this function
* need to be carried over to hfa384x_cbrrid() since the handling
* is virtually identical.
*
* Arguments:
* hw device structure
* mode DOWAIT or DOASYNC
* rid Read RID number (host order)
* riddata Caller supplied buffer that MAC formatted RID.data
* record will be written to for DOWAIT calls. Should
* be NULL for DOASYNC calls.
* riddatalen Buffer length for DOWAIT calls. Zero for DOASYNC calls.
* cmdcb command callback for async calls, NULL for DOWAIT calls
* usercb user callback for async calls, NULL for DOWAIT calls
* usercb_data user supplied data pointer for async calls, NULL
* for DOWAIT calls
*
* Returns:
* 0 success
* -EIO CTLX failure
* -ERESTARTSYS Awakened on signal
* -ENODATA riddatalen != macdatalen
* >0 command indicated error, Status and Resp0-2 are
* in hw structure.
*
* Side effects:
*
* Call context:
* interrupt (DOASYNC)
* process (DOWAIT or DOASYNC)
----------------------------------------------------------------*/
static int
hfa384x_dorrid(hfa384x_t *hw,
enum cmd_mode mode,
u16 rid,
void *riddata,
unsigned int riddatalen,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data)
{
int result;
hfa384x_usbctlx_t *ctlx;
ctlx = usbctlx_alloc();
if (ctlx == NULL) {
result = -ENOMEM;
goto done;
}
/* Initialize the command */
ctlx->outbuf.rridreq.type = cpu_to_le16(HFA384x_USB_RRIDREQ);
ctlx->outbuf.rridreq.frmlen =
cpu_to_le16(sizeof(ctlx->outbuf.rridreq.rid));
ctlx->outbuf.rridreq.rid = cpu_to_le16(rid);
ctlx->outbufsize = sizeof(ctlx->outbuf.rridreq);
ctlx->reapable = mode;
ctlx->cmdcb = cmdcb;
ctlx->usercb = usercb;
ctlx->usercb_data = usercb_data;
/* Submit the CTLX */
result = hfa384x_usbctlx_submit(hw, ctlx);
if (result != 0) {
kfree(ctlx);
} else if (mode == DOWAIT) {
struct usbctlx_rrid_completor completor;
result =
hfa384x_usbctlx_complete_sync(hw, ctlx,
init_rrid_completor
(&completor,
&ctlx->inbuf.rridresp,
riddata, riddatalen));
}
done:
return result;
}
/*----------------------------------------------------------------
* hfa384x_dowrid
*
* Constructs a write rid CTLX and issues it.
*
* NOTE: Any changes to the 'post-submit' code in this function
* need to be carried over to hfa384x_cbwrid() since the handling
* is virtually identical.
*
* Arguments:
* hw device structure
* enum cmd_mode DOWAIT or DOASYNC
* rid RID code
* riddata Data portion of RID formatted for MAC
* riddatalen Length of the data portion in bytes
* cmdcb command callback for async calls, NULL for DOWAIT calls
* usercb user callback for async calls, NULL for DOWAIT calls
* usercb_data user supplied data pointer for async calls
*
* Returns:
* 0 success
* -ETIMEDOUT timed out waiting for register ready or
* command completion
* >0 command indicated error, Status and Resp0-2 are
* in hw structure.
*
* Side effects:
*
* Call context:
* interrupt (DOASYNC)
* process (DOWAIT or DOASYNC)
----------------------------------------------------------------*/
static int
hfa384x_dowrid(hfa384x_t *hw,
enum cmd_mode mode,
u16 rid,
void *riddata,
unsigned int riddatalen,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data)
{
int result;
hfa384x_usbctlx_t *ctlx;
ctlx = usbctlx_alloc();
if (ctlx == NULL) {
result = -ENOMEM;
goto done;
}
/* Initialize the command */
ctlx->outbuf.wridreq.type = cpu_to_le16(HFA384x_USB_WRIDREQ);
ctlx->outbuf.wridreq.frmlen = cpu_to_le16((sizeof
(ctlx->outbuf.wridreq.rid) +
riddatalen + 1) / 2);
ctlx->outbuf.wridreq.rid = cpu_to_le16(rid);
memcpy(ctlx->outbuf.wridreq.data, riddata, riddatalen);
ctlx->outbufsize = sizeof(ctlx->outbuf.wridreq.type) +
sizeof(ctlx->outbuf.wridreq.frmlen) +
sizeof(ctlx->outbuf.wridreq.rid) + riddatalen;
ctlx->reapable = mode;
ctlx->cmdcb = cmdcb;
ctlx->usercb = usercb;
ctlx->usercb_data = usercb_data;
/* Submit the CTLX */
result = hfa384x_usbctlx_submit(hw, ctlx);
if (result != 0) {
kfree(ctlx);
} else if (mode == DOWAIT) {
usbctlx_wrid_completor_t completor;
hfa384x_cmdresult_t wridresult;
result = hfa384x_usbctlx_complete_sync(hw,
ctlx,
init_wrid_completor
(&completor,
&ctlx->inbuf.wridresp,
&wridresult));
}
done:
return result;
}
/*----------------------------------------------------------------
* hfa384x_dormem
*
* Constructs a readmem CTLX and issues it.
*
* NOTE: Any changes to the 'post-submit' code in this function
* need to be carried over to hfa384x_cbrmem() since the handling
* is virtually identical.
*
* Arguments:
* hw device structure
* mode DOWAIT or DOASYNC
* page MAC address space page (CMD format)
* offset MAC address space offset
* data Ptr to data buffer to receive read
* len Length of the data to read (max == 2048)
* cmdcb command callback for async calls, NULL for DOWAIT calls
* usercb user callback for async calls, NULL for DOWAIT calls
* usercb_data user supplied data pointer for async calls
*
* Returns:
* 0 success
* -ETIMEDOUT timed out waiting for register ready or
* command completion
* >0 command indicated error, Status and Resp0-2 are
* in hw structure.
*
* Side effects:
*
* Call context:
* interrupt (DOASYNC)
* process (DOWAIT or DOASYNC)
----------------------------------------------------------------*/
static int
hfa384x_dormem(hfa384x_t *hw,
enum cmd_mode mode,
u16 page,
u16 offset,
void *data,
unsigned int len,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data)
{
int result;
hfa384x_usbctlx_t *ctlx;
ctlx = usbctlx_alloc();
if (ctlx == NULL) {
result = -ENOMEM;
goto done;
}
/* Initialize the command */
ctlx->outbuf.rmemreq.type = cpu_to_le16(HFA384x_USB_RMEMREQ);
ctlx->outbuf.rmemreq.frmlen =
cpu_to_le16(sizeof(ctlx->outbuf.rmemreq.offset) +
sizeof(ctlx->outbuf.rmemreq.page) + len);
ctlx->outbuf.rmemreq.offset = cpu_to_le16(offset);
ctlx->outbuf.rmemreq.page = cpu_to_le16(page);
ctlx->outbufsize = sizeof(ctlx->outbuf.rmemreq);
pr_debug("type=0x%04x frmlen=%d offset=0x%04x page=0x%04x\n",
ctlx->outbuf.rmemreq.type,
ctlx->outbuf.rmemreq.frmlen,
ctlx->outbuf.rmemreq.offset, ctlx->outbuf.rmemreq.page);
pr_debug("pktsize=%zd\n", ROUNDUP64(sizeof(ctlx->outbuf.rmemreq)));
ctlx->reapable = mode;
ctlx->cmdcb = cmdcb;
ctlx->usercb = usercb;
ctlx->usercb_data = usercb_data;
result = hfa384x_usbctlx_submit(hw, ctlx);
if (result != 0) {
kfree(ctlx);
} else if (mode == DOWAIT) {
usbctlx_rmem_completor_t completor;
result =
hfa384x_usbctlx_complete_sync(hw, ctlx,
init_rmem_completor
(&completor,
&ctlx->inbuf.rmemresp, data,
len));
}
done:
return result;
}
/*----------------------------------------------------------------
* hfa384x_dowmem
*
* Constructs a writemem CTLX and issues it.
*
* NOTE: Any changes to the 'post-submit' code in this function
* need to be carried over to hfa384x_cbwmem() since the handling
* is virtually identical.
*
* Arguments:
* hw device structure
* mode DOWAIT or DOASYNC
* page MAC address space page (CMD format)
* offset MAC address space offset
* data Ptr to data buffer containing write data
* len Length of the data to read (max == 2048)
* cmdcb command callback for async calls, NULL for DOWAIT calls
* usercb user callback for async calls, NULL for DOWAIT calls
* usercb_data user supplied data pointer for async calls.
*
* Returns:
* 0 success
* -ETIMEDOUT timed out waiting for register ready or
* command completion
* >0 command indicated error, Status and Resp0-2 are
* in hw structure.
*
* Side effects:
*
* Call context:
* interrupt (DOWAIT)
* process (DOWAIT or DOASYNC)
----------------------------------------------------------------*/
static int
hfa384x_dowmem(hfa384x_t *hw,
enum cmd_mode mode,
u16 page,
u16 offset,
void *data,
unsigned int len,
ctlx_cmdcb_t cmdcb, ctlx_usercb_t usercb, void *usercb_data)
{
int result;
hfa384x_usbctlx_t *ctlx;
pr_debug("page=0x%04x offset=0x%04x len=%d\n", page, offset, len);
ctlx = usbctlx_alloc();
if (ctlx == NULL) {
result = -ENOMEM;
goto done;
}
/* Initialize the command */
ctlx->outbuf.wmemreq.type = cpu_to_le16(HFA384x_USB_WMEMREQ);
ctlx->outbuf.wmemreq.frmlen =
cpu_to_le16(sizeof(ctlx->outbuf.wmemreq.offset) +
sizeof(ctlx->outbuf.wmemreq.page) + len);
ctlx->outbuf.wmemreq.offset = cpu_to_le16(offset);
ctlx->outbuf.wmemreq.page = cpu_to_le16(page);
memcpy(ctlx->outbuf.wmemreq.data, data, len);
ctlx->outbufsize = sizeof(ctlx->outbuf.wmemreq.type) +
sizeof(ctlx->outbuf.wmemreq.frmlen) +
sizeof(ctlx->outbuf.wmemreq.offset) +
sizeof(ctlx->outbuf.wmemreq.page) + len;
ctlx->reapable = mode;
ctlx->cmdcb = cmdcb;
ctlx->usercb = usercb;
ctlx->usercb_data = usercb_data;
result = hfa384x_usbctlx_submit(hw, ctlx);
if (result != 0) {
kfree(ctlx);
} else if (mode == DOWAIT) {
usbctlx_wmem_completor_t completor;
hfa384x_cmdresult_t wmemresult;
result = hfa384x_usbctlx_complete_sync(hw,
ctlx,
init_wmem_completor
(&completor,
&ctlx->inbuf.wmemresp,
&wmemresult));
}
done:
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_commtallies
*
* Send a commtallies inquiry to the MAC. Note that this is an async
* call that will result in an info frame arriving sometime later.
*
* Arguments:
* hw device structure
*
* Returns:
* zero success.
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_commtallies(hfa384x_t *hw)
{
hfa384x_metacmd_t cmd;
cmd.cmd = HFA384x_CMDCODE_INQ;
cmd.parm0 = HFA384x_IT_COMMTALLIES;
cmd.parm1 = 0;
cmd.parm2 = 0;
hfa384x_docmd_async(hw, &cmd, NULL, NULL, NULL);
return 0;
}
/*----------------------------------------------------------------
* hfa384x_drvr_disable
*
* Issues the disable command to stop communications on one of
* the MACs 'ports'. Only macport 0 is valid for stations.
* APs may also disable macports 1-6. Only ports that have been
* previously enabled may be disabled.
*
* Arguments:
* hw device structure
* macport MAC port number (host order)
*
* Returns:
* 0 success
* >0 f/w reported failure - f/w status code
* <0 driver reported error (timeout|bad arg)
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_disable(hfa384x_t *hw, u16 macport)
{
int result = 0;
if ((!hw->isap && macport != 0) ||
(hw->isap && !(macport <= HFA384x_PORTID_MAX)) ||
!(hw->port_enabled[macport])) {
result = -EINVAL;
} else {
result = hfa384x_cmd_disable(hw, macport);
if (result == 0)
hw->port_enabled[macport] = 0;
}
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_enable
*
* Issues the enable command to enable communications on one of
* the MACs 'ports'. Only macport 0 is valid for stations.
* APs may also enable macports 1-6. Only ports that are currently
* disabled may be enabled.
*
* Arguments:
* hw device structure
* macport MAC port number
*
* Returns:
* 0 success
* >0 f/w reported failure - f/w status code
* <0 driver reported error (timeout|bad arg)
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_enable(hfa384x_t *hw, u16 macport)
{
int result = 0;
if ((!hw->isap && macport != 0) ||
(hw->isap && !(macport <= HFA384x_PORTID_MAX)) ||
(hw->port_enabled[macport])) {
result = -EINVAL;
} else {
result = hfa384x_cmd_enable(hw, macport);
if (result == 0)
hw->port_enabled[macport] = 1;
}
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_flashdl_enable
*
* Begins the flash download state. Checks to see that we're not
* already in a download state and that a port isn't enabled.
* Sets the download state and retrieves the flash download
* buffer location, buffer size, and timeout length.
*
* Arguments:
* hw device structure
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_flashdl_enable(hfa384x_t *hw)
{
int result = 0;
int i;
/* Check that a port isn't active */
for (i = 0; i < HFA384x_PORTID_MAX; i++) {
if (hw->port_enabled[i]) {
pr_debug("called when port enabled.\n");
return -EINVAL;
}
}
/* Check that we're not already in a download state */
if (hw->dlstate != HFA384x_DLSTATE_DISABLED)
return -EINVAL;
/* Retrieve the buffer loc&size and timeout */
result = hfa384x_drvr_getconfig(hw, HFA384x_RID_DOWNLOADBUFFER,
&(hw->bufinfo), sizeof(hw->bufinfo));
if (result)
return result;
hw->bufinfo.page = le16_to_cpu(hw->bufinfo.page);
hw->bufinfo.offset = le16_to_cpu(hw->bufinfo.offset);
hw->bufinfo.len = le16_to_cpu(hw->bufinfo.len);
result = hfa384x_drvr_getconfig16(hw, HFA384x_RID_MAXLOADTIME,
&(hw->dltimeout));
if (result)
return result;
hw->dltimeout = le16_to_cpu(hw->dltimeout);
pr_debug("flashdl_enable\n");
hw->dlstate = HFA384x_DLSTATE_FLASHENABLED;
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_flashdl_disable
*
* Ends the flash download state. Note that this will cause the MAC
* firmware to restart.
*
* Arguments:
* hw device structure
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_flashdl_disable(hfa384x_t *hw)
{
/* Check that we're already in the download state */
if (hw->dlstate != HFA384x_DLSTATE_FLASHENABLED)
return -EINVAL;
pr_debug("flashdl_enable\n");
/* There isn't much we can do at this point, so I don't */
/* bother w/ the return value */
hfa384x_cmd_download(hw, HFA384x_PROGMODE_DISABLE, 0, 0, 0);
hw->dlstate = HFA384x_DLSTATE_DISABLED;
return 0;
}
/*----------------------------------------------------------------
* hfa384x_drvr_flashdl_write
*
* Performs a FLASH download of a chunk of data. First checks to see
* that we're in the FLASH download state, then sets the download
* mode, uses the aux functions to 1) copy the data to the flash
* buffer, 2) sets the download 'write flash' mode, 3) readback and
* compare. Lather rinse, repeat as many times an necessary to get
* all the given data into flash.
* When all data has been written using this function (possibly
* repeatedly), call drvr_flashdl_disable() to end the download state
* and restart the MAC.
*
* Arguments:
* hw device structure
* daddr Card address to write to. (host order)
* buf Ptr to data to write.
* len Length of data (host order).
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_flashdl_write(hfa384x_t *hw, u32 daddr, void *buf, u32 len)
{
int result = 0;
u32 dlbufaddr;
int nburns;
u32 burnlen;
u32 burndaddr;
u16 burnlo;
u16 burnhi;
int nwrites;
u8 *writebuf;
u16 writepage;
u16 writeoffset;
u32 writelen;
int i;
int j;
pr_debug("daddr=0x%08x len=%d\n", daddr, len);
/* Check that we're in the flash download state */
if (hw->dlstate != HFA384x_DLSTATE_FLASHENABLED)
return -EINVAL;
printk(KERN_INFO "Download %d bytes to flash @0x%06x\n", len, daddr);
/* Convert to flat address for arithmetic */
/* NOTE: dlbuffer RID stores the address in AUX format */
dlbufaddr =
HFA384x_ADDR_AUX_MKFLAT(hw->bufinfo.page, hw->bufinfo.offset);
pr_debug("dlbuf.page=0x%04x dlbuf.offset=0x%04x dlbufaddr=0x%08x\n",
hw->bufinfo.page, hw->bufinfo.offset, dlbufaddr);
#if 0
printk(KERN_WARNING "dlbuf@0x%06lx len=%d to=%d\n", dlbufaddr,
hw->bufinfo.len, hw->dltimeout);
#endif
/* Calculations to determine how many fills of the dlbuffer to do
* and how many USB wmemreq's to do for each fill. At this point
* in time, the dlbuffer size and the wmemreq size are the same.
* Therefore, nwrites should always be 1. The extra complexity
* here is a hedge against future changes.
*/
/* Figure out how many times to do the flash programming */
nburns = len / hw->bufinfo.len;
nburns += (len % hw->bufinfo.len) ? 1 : 0;
/* For each flash program cycle, how many USB wmemreq's are needed? */
nwrites = hw->bufinfo.len / HFA384x_USB_RWMEM_MAXLEN;
nwrites += (hw->bufinfo.len % HFA384x_USB_RWMEM_MAXLEN) ? 1 : 0;
/* For each burn */
for (i = 0; i < nburns; i++) {
/* Get the dest address and len */
burnlen = (len - (hw->bufinfo.len * i)) > hw->bufinfo.len ?
hw->bufinfo.len : (len - (hw->bufinfo.len * i));
burndaddr = daddr + (hw->bufinfo.len * i);
burnlo = HFA384x_ADDR_CMD_MKOFF(burndaddr);
burnhi = HFA384x_ADDR_CMD_MKPAGE(burndaddr);
printk(KERN_INFO "Writing %d bytes to flash @0x%06x\n",
burnlen, burndaddr);
/* Set the download mode */
result = hfa384x_cmd_download(hw, HFA384x_PROGMODE_NV,
burnlo, burnhi, burnlen);
if (result) {
printk(KERN_ERR "download(NV,lo=%x,hi=%x,len=%x) "
"cmd failed, result=%d. Aborting d/l\n",
burnlo, burnhi, burnlen, result);
goto exit_proc;
}
/* copy the data to the flash download buffer */
for (j = 0; j < nwrites; j++) {
writebuf = buf +
(i * hw->bufinfo.len) +
(j * HFA384x_USB_RWMEM_MAXLEN);
writepage = HFA384x_ADDR_CMD_MKPAGE(dlbufaddr +
(j * HFA384x_USB_RWMEM_MAXLEN));
writeoffset = HFA384x_ADDR_CMD_MKOFF(dlbufaddr +
(j * HFA384x_USB_RWMEM_MAXLEN));
writelen = burnlen - (j * HFA384x_USB_RWMEM_MAXLEN);
writelen = writelen > HFA384x_USB_RWMEM_MAXLEN ?
HFA384x_USB_RWMEM_MAXLEN : writelen;
result = hfa384x_dowmem_wait(hw,
writepage,
writeoffset,
writebuf, writelen);
}
/* set the download 'write flash' mode */
result = hfa384x_cmd_download(hw,
HFA384x_PROGMODE_NVWRITE,
0, 0, 0);
if (result) {
printk(KERN_ERR
"download(NVWRITE,lo=%x,hi=%x,len=%x) "
"cmd failed, result=%d. Aborting d/l\n",
burnlo, burnhi, burnlen, result);
goto exit_proc;
}
/* TODO: We really should do a readback and compare. */
}
exit_proc:
/* Leave the firmware in the 'post-prog' mode. flashdl_disable will */
/* actually disable programming mode. Remember, that will cause the */
/* the firmware to effectively reset itself. */
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_getconfig
*
* Performs the sequence necessary to read a config/info item.
*
* Arguments:
* hw device structure
* rid config/info record id (host order)
* buf host side record buffer. Upon return it will
* contain the body portion of the record (minus the
* RID and len).
* len buffer length (in bytes, should match record length)
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
* -ENODATA length mismatch between argument and retrieved
* record.
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_getconfig(hfa384x_t *hw, u16 rid, void *buf, u16 len)
{
int result;
result = hfa384x_dorrid_wait(hw, rid, buf, len);
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_getconfig_async
*
* Performs the sequence necessary to perform an async read of
* of a config/info item.
*
* Arguments:
* hw device structure
* rid config/info record id (host order)
* buf host side record buffer. Upon return it will
* contain the body portion of the record (minus the
* RID and len).
* len buffer length (in bytes, should match record length)
* cbfn caller supplied callback, called when the command
* is done (successful or not).
* cbfndata pointer to some caller supplied data that will be
* passed in as an argument to the cbfn.
*
* Returns:
* nothing the cbfn gets a status argument identifying if
* any errors occur.
* Side effects:
* Queues an hfa384x_usbcmd_t for subsequent execution.
*
* Call context:
* Any
----------------------------------------------------------------*/
int
hfa384x_drvr_getconfig_async(hfa384x_t *hw,
u16 rid, ctlx_usercb_t usercb, void *usercb_data)
{
return hfa384x_dorrid_async(hw, rid, NULL, 0,
hfa384x_cb_rrid, usercb, usercb_data);
}
/*----------------------------------------------------------------
* hfa384x_drvr_setconfig_async
*
* Performs the sequence necessary to write a config/info item.
*
* Arguments:
* hw device structure
* rid config/info record id (in host order)
* buf host side record buffer
* len buffer length (in bytes)
* usercb completion callback
* usercb_data completion callback argument
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int
hfa384x_drvr_setconfig_async(hfa384x_t *hw,
u16 rid,
void *buf,
u16 len, ctlx_usercb_t usercb, void *usercb_data)
{
return hfa384x_dowrid_async(hw, rid, buf, len,
hfa384x_cb_status, usercb, usercb_data);
}
/*----------------------------------------------------------------
* hfa384x_drvr_ramdl_disable
*
* Ends the ram download state.
*
* Arguments:
* hw device structure
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_ramdl_disable(hfa384x_t *hw)
{
/* Check that we're already in the download state */
if (hw->dlstate != HFA384x_DLSTATE_RAMENABLED)
return -EINVAL;
pr_debug("ramdl_disable()\n");
/* There isn't much we can do at this point, so I don't */
/* bother w/ the return value */
hfa384x_cmd_download(hw, HFA384x_PROGMODE_DISABLE, 0, 0, 0);
hw->dlstate = HFA384x_DLSTATE_DISABLED;
return 0;
}
/*----------------------------------------------------------------
* hfa384x_drvr_ramdl_enable
*
* Begins the ram download state. Checks to see that we're not
* already in a download state and that a port isn't enabled.
* Sets the download state and calls cmd_download with the
* ENABLE_VOLATILE subcommand and the exeaddr argument.
*
* Arguments:
* hw device structure
* exeaddr the card execution address that will be
* jumped to when ramdl_disable() is called
* (host order).
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_ramdl_enable(hfa384x_t *hw, u32 exeaddr)
{
int result = 0;
u16 lowaddr;
u16 hiaddr;
int i;
/* Check that a port isn't active */
for (i = 0; i < HFA384x_PORTID_MAX; i++) {
if (hw->port_enabled[i]) {
printk(KERN_ERR
"Can't download with a macport enabled.\n");
return -EINVAL;
}
}
/* Check that we're not already in a download state */
if (hw->dlstate != HFA384x_DLSTATE_DISABLED) {
printk(KERN_ERR "Download state not disabled.\n");
return -EINVAL;
}
pr_debug("ramdl_enable, exeaddr=0x%08x\n", exeaddr);
/* Call the download(1,addr) function */
lowaddr = HFA384x_ADDR_CMD_MKOFF(exeaddr);
hiaddr = HFA384x_ADDR_CMD_MKPAGE(exeaddr);
result = hfa384x_cmd_download(hw, HFA384x_PROGMODE_RAM,
lowaddr, hiaddr, 0);
if (result == 0) {
/* Set the download state */
hw->dlstate = HFA384x_DLSTATE_RAMENABLED;
} else {
pr_debug("cmd_download(0x%04x, 0x%04x) failed, result=%d.\n",
lowaddr, hiaddr, result);
}
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_ramdl_write
*
* Performs a RAM download of a chunk of data. First checks to see
* that we're in the RAM download state, then uses the [read|write]mem USB
* commands to 1) copy the data, 2) readback and compare. The download
* state is unaffected. When all data has been written using
* this function, call drvr_ramdl_disable() to end the download state
* and restart the MAC.
*
* Arguments:
* hw device structure
* daddr Card address to write to. (host order)
* buf Ptr to data to write.
* len Length of data (host order).
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_ramdl_write(hfa384x_t *hw, u32 daddr, void *buf, u32 len)
{
int result = 0;
int nwrites;
u8 *data = buf;
int i;
u32 curraddr;
u16 currpage;
u16 curroffset;
u16 currlen;
/* Check that we're in the ram download state */
if (hw->dlstate != HFA384x_DLSTATE_RAMENABLED)
return -EINVAL;
printk(KERN_INFO "Writing %d bytes to ram @0x%06x\n", len, daddr);
/* How many dowmem calls? */
nwrites = len / HFA384x_USB_RWMEM_MAXLEN;
nwrites += len % HFA384x_USB_RWMEM_MAXLEN ? 1 : 0;
/* Do blocking wmem's */
for (i = 0; i < nwrites; i++) {
/* make address args */
curraddr = daddr + (i * HFA384x_USB_RWMEM_MAXLEN);
currpage = HFA384x_ADDR_CMD_MKPAGE(curraddr);
curroffset = HFA384x_ADDR_CMD_MKOFF(curraddr);
currlen = len - (i * HFA384x_USB_RWMEM_MAXLEN);
if (currlen > HFA384x_USB_RWMEM_MAXLEN)
currlen = HFA384x_USB_RWMEM_MAXLEN;
/* Do blocking ctlx */
result = hfa384x_dowmem_wait(hw,
currpage,
curroffset,
data +
(i * HFA384x_USB_RWMEM_MAXLEN),
currlen);
if (result)
break;
/* TODO: We really should have a readback. */
}
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_readpda
*
* Performs the sequence to read the PDA space. Note there is no
* drvr_writepda() function. Writing a PDA is
* generally implemented by a calling component via calls to
* cmd_download and writing to the flash download buffer via the
* aux regs.
*
* Arguments:
* hw device structure
* buf buffer to store PDA in
* len buffer length
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
* -ETIMEDOUT timout waiting for the cmd regs to become
* available, or waiting for the control reg
* to indicate the Aux port is enabled.
* -ENODATA the buffer does NOT contain a valid PDA.
* Either the card PDA is bad, or the auxdata
* reads are giving us garbage.
*
* Side effects:
*
* Call context:
* process or non-card interrupt.
----------------------------------------------------------------*/
int hfa384x_drvr_readpda(hfa384x_t *hw, void *buf, unsigned int len)
{
int result = 0;
u16 *pda = buf;
int pdaok = 0;
int morepdrs = 1;
int currpdr = 0; /* word offset of the current pdr */
size_t i;
u16 pdrlen; /* pdr length in bytes, host order */
u16 pdrcode; /* pdr code, host order */
u16 currpage;
u16 curroffset;
struct pdaloc {
u32 cardaddr;
u16 auxctl;
} pdaloc[] = {
{
HFA3842_PDA_BASE, 0}, {
HFA3841_PDA_BASE, 0}, {
HFA3841_PDA_BOGUS_BASE, 0}
};
/* Read the pda from each known address. */
for (i = 0; i < ARRAY_SIZE(pdaloc); i++) {
/* Make address */
currpage = HFA384x_ADDR_CMD_MKPAGE(pdaloc[i].cardaddr);
curroffset = HFA384x_ADDR_CMD_MKOFF(pdaloc[i].cardaddr);
/* units of bytes */
result = hfa384x_dormem_wait(hw, currpage, curroffset, buf,
len);
if (result) {
printk(KERN_WARNING
"Read from index %zd failed, continuing\n", i);
continue;
}
/* Test for garbage */
pdaok = 1; /* initially assume good */
morepdrs = 1;
while (pdaok && morepdrs) {
pdrlen = le16_to_cpu(pda[currpdr]) * 2;
pdrcode = le16_to_cpu(pda[currpdr + 1]);
/* Test the record length */
if (pdrlen > HFA384x_PDR_LEN_MAX || pdrlen == 0) {
printk(KERN_ERR "pdrlen invalid=%d\n", pdrlen);
pdaok = 0;
break;
}
/* Test the code */
if (!hfa384x_isgood_pdrcode(pdrcode)) {
printk(KERN_ERR "pdrcode invalid=%d\n",
pdrcode);
pdaok = 0;
break;
}
/* Test for completion */
if (pdrcode == HFA384x_PDR_END_OF_PDA)
morepdrs = 0;
/* Move to the next pdr (if necessary) */
if (morepdrs) {
/* note the access to pda[], need words here */
currpdr += le16_to_cpu(pda[currpdr]) + 1;
}
}
if (pdaok) {
printk(KERN_INFO
"PDA Read from 0x%08x in %s space.\n",
pdaloc[i].cardaddr,
pdaloc[i].auxctl == 0 ? "EXTDS" :
pdaloc[i].auxctl == 1 ? "NV" :
pdaloc[i].auxctl == 2 ? "PHY" :
pdaloc[i].auxctl == 3 ? "ICSRAM" :
"<bogus auxctl>");
break;
}
}
result = pdaok ? 0 : -ENODATA;
if (result)
pr_debug("Failure: pda is not okay\n");
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_setconfig
*
* Performs the sequence necessary to write a config/info item.
*
* Arguments:
* hw device structure
* rid config/info record id (in host order)
* buf host side record buffer
* len buffer length (in bytes)
*
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_setconfig(hfa384x_t *hw, u16 rid, void *buf, u16 len)
{
return hfa384x_dowrid_wait(hw, rid, buf, len);
}
/*----------------------------------------------------------------
* hfa384x_drvr_start
*
* Issues the MAC initialize command, sets up some data structures,
* and enables the interrupts. After this function completes, the
* low-level stuff should be ready for any/all commands.
*
* Arguments:
* hw device structure
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_start(hfa384x_t *hw)
{
int result, result1, result2;
u16 status;
might_sleep();
/* Clear endpoint stalls - but only do this if the endpoint
* is showing a stall status. Some prism2 cards seem to behave
* badly if a clear_halt is called when the endpoint is already
* ok
*/
result =
usb_get_status(hw->usb, USB_RECIP_ENDPOINT, hw->endp_in, &status);
if (result < 0) {
printk(KERN_ERR "Cannot get bulk in endpoint status.\n");
goto done;
}
if ((status == 1) && usb_clear_halt(hw->usb, hw->endp_in))
printk(KERN_ERR "Failed to reset bulk in endpoint.\n");
result =
usb_get_status(hw->usb, USB_RECIP_ENDPOINT, hw->endp_out, &status);
if (result < 0) {
printk(KERN_ERR "Cannot get bulk out endpoint status.\n");
goto done;
}
if ((status == 1) && usb_clear_halt(hw->usb, hw->endp_out))
printk(KERN_ERR "Failed to reset bulk out endpoint.\n");
/* Synchronous unlink, in case we're trying to restart the driver */
usb_kill_urb(&hw->rx_urb);
/* Post the IN urb */
result = submit_rx_urb(hw, GFP_KERNEL);
if (result != 0) {
printk(KERN_ERR
"Fatal, failed to submit RX URB, result=%d\n", result);
goto done;
}
/* Call initialize twice, with a 1 second sleep in between.
* This is a nasty work-around since many prism2 cards seem to
* need time to settle after an init from cold. The second
* call to initialize in theory is not necessary - but we call
* it anyway as a double insurance policy:
* 1) If the first init should fail, the second may well succeed
* and the card can still be used
* 2) It helps ensures all is well with the card after the first
* init and settle time.
*/
result1 = hfa384x_cmd_initialize(hw);
msleep(1000);
result = result2 = hfa384x_cmd_initialize(hw);
if (result1 != 0) {
if (result2 != 0) {
printk(KERN_ERR
"cmd_initialize() failed on two attempts, results %d and %d\n",
result1, result2);
usb_kill_urb(&hw->rx_urb);
goto done;
} else {
pr_debug("First cmd_initialize() failed (result %d),\n",
result1);
pr_debug("but second attempt succeeded. All should be ok\n");
}
} else if (result2 != 0) {
printk(KERN_WARNING "First cmd_initialize() succeeded, but second attempt failed (result=%d)\n",
result2);
printk(KERN_WARNING
"Most likely the card will be functional\n");
goto done;
}
hw->state = HFA384x_STATE_RUNNING;
done:
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_stop
*
* Shuts down the MAC to the point where it is safe to unload the
* driver. Any subsystem that may be holding a data or function
* ptr into the driver must be cleared/deinitialized.
*
* Arguments:
* hw device structure
* Returns:
* 0 success
* >0 f/w reported error - f/w status code
* <0 driver reported error
*
* Side effects:
*
* Call context:
* process
----------------------------------------------------------------*/
int hfa384x_drvr_stop(hfa384x_t *hw)
{
int result = 0;
int i;
might_sleep();
/* There's no need for spinlocks here. The USB "disconnect"
* function sets this "removed" flag and then calls us.
*/
if (!hw->wlandev->hwremoved) {
/* Call initialize to leave the MAC in its 'reset' state */
hfa384x_cmd_initialize(hw);
/* Cancel the rxurb */
usb_kill_urb(&hw->rx_urb);
}
hw->link_status = HFA384x_LINK_NOTCONNECTED;
hw->state = HFA384x_STATE_INIT;
del_timer_sync(&hw->commsqual_timer);
/* Clear all the port status */
for (i = 0; i < HFA384x_NUMPORTS_MAX; i++)
hw->port_enabled[i] = 0;
return result;
}
/*----------------------------------------------------------------
* hfa384x_drvr_txframe
*
* Takes a frame from prism2sta and queues it for transmission.
*
* Arguments:
* hw device structure
* skb packet buffer struct. Contains an 802.11
* data frame.
* p80211_hdr points to the 802.11 header for the packet.
* Returns:
* 0 Success and more buffs available
* 1 Success but no more buffs
* 2 Allocation failure
* 4 Buffer full or queue busy
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
int hfa384x_drvr_txframe(hfa384x_t *hw, struct sk_buff *skb,
union p80211_hdr *p80211_hdr,
struct p80211_metawep *p80211_wep)
{
int usbpktlen = sizeof(hfa384x_tx_frame_t);
int result;
int ret;
char *ptr;
if (hw->tx_urb.status == -EINPROGRESS) {
printk(KERN_WARNING "TX URB already in use\n");
result = 3;
goto exit;
}
/* Build Tx frame structure */
/* Set up the control field */
memset(&hw->txbuff.txfrm.desc, 0, sizeof(hw->txbuff.txfrm.desc));
/* Setup the usb type field */
hw->txbuff.type = cpu_to_le16(HFA384x_USB_TXFRM);
/* Set up the sw_support field to identify this frame */
hw->txbuff.txfrm.desc.sw_support = 0x0123;
/* Tx complete and Tx exception disable per dleach. Might be causing
* buf depletion
*/
/* #define DOEXC SLP -- doboth breaks horribly under load, doexc less so. */
#if defined(DOBOTH)
hw->txbuff.txfrm.desc.tx_control =
HFA384x_TX_MACPORT_SET(0) | HFA384x_TX_STRUCTYPE_SET(1) |
HFA384x_TX_TXEX_SET(1) | HFA384x_TX_TXOK_SET(1);
#elif defined(DOEXC)
hw->txbuff.txfrm.desc.tx_control =
HFA384x_TX_MACPORT_SET(0) | HFA384x_TX_STRUCTYPE_SET(1) |
HFA384x_TX_TXEX_SET(1) | HFA384x_TX_TXOK_SET(0);
#else
hw->txbuff.txfrm.desc.tx_control =
HFA384x_TX_MACPORT_SET(0) | HFA384x_TX_STRUCTYPE_SET(1) |
HFA384x_TX_TXEX_SET(0) | HFA384x_TX_TXOK_SET(0);
#endif
hw->txbuff.txfrm.desc.tx_control =
cpu_to_le16(hw->txbuff.txfrm.desc.tx_control);
/* copy the header over to the txdesc */
memcpy(&(hw->txbuff.txfrm.desc.frame_control), p80211_hdr,
sizeof(union p80211_hdr));
/* if we're using host WEP, increase size by IV+ICV */
if (p80211_wep->data) {
hw->txbuff.txfrm.desc.data_len = cpu_to_le16(skb->len + 8);
usbpktlen += 8;
} else {
hw->txbuff.txfrm.desc.data_len = cpu_to_le16(skb->len);
}
usbpktlen += skb->len;
/* copy over the WEP IV if we are using host WEP */
ptr = hw->txbuff.txfrm.data;
if (p80211_wep->data) {
memcpy(ptr, p80211_wep->iv, sizeof(p80211_wep->iv));
ptr += sizeof(p80211_wep->iv);
memcpy(ptr, p80211_wep->data, skb->len);
} else {
memcpy(ptr, skb->data, skb->len);
}
/* copy over the packet data */
ptr += skb->len;
/* copy over the WEP ICV if we are using host WEP */
if (p80211_wep->data)
memcpy(ptr, p80211_wep->icv, sizeof(p80211_wep->icv));
/* Send the USB packet */
usb_fill_bulk_urb(&(hw->tx_urb), hw->usb,
hw->endp_out,
&(hw->txbuff), ROUNDUP64(usbpktlen),
hfa384x_usbout_callback, hw->wlandev);
hw->tx_urb.transfer_flags |= USB_QUEUE_BULK;
result = 1;
ret = submit_tx_urb(hw, &hw->tx_urb, GFP_ATOMIC);
if (ret != 0) {
printk(KERN_ERR "submit_tx_urb() failed, error=%d\n", ret);
result = 3;
}
exit:
return result;
}
void hfa384x_tx_timeout(wlandevice_t *wlandev)
{
hfa384x_t *hw = wlandev->priv;
unsigned long flags;
spin_lock_irqsave(&hw->ctlxq.lock, flags);
if (!hw->wlandev->hwremoved) {
int sched;
sched = !test_and_set_bit(WORK_TX_HALT, &hw->usb_flags);
sched |= !test_and_set_bit(WORK_RX_HALT, &hw->usb_flags);
if (sched)
schedule_work(&hw->usb_work);
}
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
}
/*----------------------------------------------------------------
* hfa384x_usbctlx_reaper_task
*
* Tasklet to delete dead CTLX objects
*
* Arguments:
* data ptr to a hfa384x_t
*
* Returns:
*
* Call context:
* Interrupt
----------------------------------------------------------------*/
static void hfa384x_usbctlx_reaper_task(unsigned long data)
{
hfa384x_t *hw = (hfa384x_t *) data;
struct list_head *entry;
struct list_head *temp;
unsigned long flags;
spin_lock_irqsave(&hw->ctlxq.lock, flags);
/* This list is guaranteed to be empty if someone
* has unplugged the adapter.
*/
list_for_each_safe(entry, temp, &hw->ctlxq.reapable) {
hfa384x_usbctlx_t *ctlx;
ctlx = list_entry(entry, hfa384x_usbctlx_t, list);
list_del(&ctlx->list);
kfree(ctlx);
}
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
}
/*----------------------------------------------------------------
* hfa384x_usbctlx_completion_task
*
* Tasklet to call completion handlers for returned CTLXs
*
* Arguments:
* data ptr to hfa384x_t
*
* Returns:
* Nothing
*
* Call context:
* Interrupt
----------------------------------------------------------------*/
static void hfa384x_usbctlx_completion_task(unsigned long data)
{
hfa384x_t *hw = (hfa384x_t *) data;
struct list_head *entry;
struct list_head *temp;
unsigned long flags;
int reap = 0;
spin_lock_irqsave(&hw->ctlxq.lock, flags);
/* This list is guaranteed to be empty if someone
* has unplugged the adapter ...
*/
list_for_each_safe(entry, temp, &hw->ctlxq.completing) {
hfa384x_usbctlx_t *ctlx;
ctlx = list_entry(entry, hfa384x_usbctlx_t, list);
/* Call the completion function that this
* command was assigned, assuming it has one.
*/
if (ctlx->cmdcb != NULL) {
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
ctlx->cmdcb(hw, ctlx);
spin_lock_irqsave(&hw->ctlxq.lock, flags);
/* Make sure we don't try and complete
* this CTLX more than once!
*/
ctlx->cmdcb = NULL;
/* Did someone yank the adapter out
* while our list was (briefly) unlocked?
*/
if (hw->wlandev->hwremoved) {
reap = 0;
break;
}
}
/*
* "Reapable" CTLXs are ones which don't have any
* threads waiting for them to die. Hence they must
* be delivered to The Reaper!
*/
if (ctlx->reapable) {
/* Move the CTLX off the "completing" list (hopefully)
* on to the "reapable" list where the reaper task
* can find it. And "reapable" means that this CTLX
* isn't sitting on a wait-queue somewhere.
*/
list_move_tail(&ctlx->list, &hw->ctlxq.reapable);
reap = 1;
}
complete(&ctlx->done);
}
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
if (reap)
tasklet_schedule(&hw->reaper_bh);
}
/*----------------------------------------------------------------
* unlocked_usbctlx_cancel_async
*
* Mark the CTLX dead asynchronously, and ensure that the
* next command on the queue is run afterwards.
*
* Arguments:
* hw ptr to the hfa384x_t structure
* ctlx ptr to a CTLX structure
*
* Returns:
* 0 the CTLX's URB is inactive
* -EINPROGRESS the URB is currently being unlinked
*
* Call context:
* Either process or interrupt, but presumably interrupt
----------------------------------------------------------------*/
static int unlocked_usbctlx_cancel_async(hfa384x_t *hw,
hfa384x_usbctlx_t *ctlx)
{
int ret;
/*
* Try to delete the URB containing our request packet.
* If we succeed, then its completion handler will be
* called with a status of -ECONNRESET.
*/
hw->ctlx_urb.transfer_flags |= URB_ASYNC_UNLINK;
ret = usb_unlink_urb(&hw->ctlx_urb);
if (ret != -EINPROGRESS) {
/*
* The OUT URB had either already completed
* or was still in the pending queue, so the
* URB's completion function will not be called.
* We will have to complete the CTLX ourselves.
*/
ctlx->state = CTLX_REQ_FAILED;
unlocked_usbctlx_complete(hw, ctlx);
ret = 0;
}
return ret;
}
/*----------------------------------------------------------------
* unlocked_usbctlx_complete
*
* A CTLX has completed. It may have been successful, it may not
* have been. At this point, the CTLX should be quiescent. The URBs
* aren't active and the timers should have been stopped.
*
* The CTLX is migrated to the "completing" queue, and the completing
* tasklet is scheduled.
*
* Arguments:
* hw ptr to a hfa384x_t structure
* ctlx ptr to a ctlx structure
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* Either, assume interrupt
----------------------------------------------------------------*/
static void unlocked_usbctlx_complete(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx)
{
/* Timers have been stopped, and ctlx should be in
* a terminal state. Retire it from the "active"
* queue.
*/
list_move_tail(&ctlx->list, &hw->ctlxq.completing);
tasklet_schedule(&hw->completion_bh);
switch (ctlx->state) {
case CTLX_COMPLETE:
case CTLX_REQ_FAILED:
/* This are the correct terminating states. */
break;
default:
printk(KERN_ERR "CTLX[%d] not in a terminating state(%s)\n",
le16_to_cpu(ctlx->outbuf.type), ctlxstr(ctlx->state));
break;
} /* switch */
}
/*----------------------------------------------------------------
* hfa384x_usbctlxq_run
*
* Checks to see if the head item is running. If not, starts it.
*
* Arguments:
* hw ptr to hfa384x_t
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* any
----------------------------------------------------------------*/
static void hfa384x_usbctlxq_run(hfa384x_t *hw)
{
unsigned long flags;
/* acquire lock */
spin_lock_irqsave(&hw->ctlxq.lock, flags);
/* Only one active CTLX at any one time, because there's no
* other (reliable) way to match the response URB to the
* correct CTLX.
*
* Don't touch any of these CTLXs if the hardware
* has been removed or the USB subsystem is stalled.
*/
if (!list_empty(&hw->ctlxq.active) ||
test_bit(WORK_TX_HALT, &hw->usb_flags) || hw->wlandev->hwremoved)
goto unlock;
while (!list_empty(&hw->ctlxq.pending)) {
hfa384x_usbctlx_t *head;
int result;
/* This is the first pending command */
head = list_entry(hw->ctlxq.pending.next,
hfa384x_usbctlx_t, list);
/* We need to split this off to avoid a race condition */
list_move_tail(&head->list, &hw->ctlxq.active);
/* Fill the out packet */
usb_fill_bulk_urb(&(hw->ctlx_urb), hw->usb,
hw->endp_out,
&(head->outbuf), ROUNDUP64(head->outbufsize),
hfa384x_ctlxout_callback, hw);
hw->ctlx_urb.transfer_flags |= USB_QUEUE_BULK;
/* Now submit the URB and update the CTLX's state */
result = SUBMIT_URB(&hw->ctlx_urb, GFP_ATOMIC);
if (result == 0) {
/* This CTLX is now running on the active queue */
head->state = CTLX_REQ_SUBMITTED;
/* Start the OUT wait timer */
hw->req_timer_done = 0;
hw->reqtimer.expires = jiffies + HZ;
add_timer(&hw->reqtimer);
/* Start the IN wait timer */
hw->resp_timer_done = 0;
hw->resptimer.expires = jiffies + 2 * HZ;
add_timer(&hw->resptimer);
break;
}
if (result == -EPIPE) {
/* The OUT pipe needs resetting, so put
* this CTLX back in the "pending" queue
* and schedule a reset ...
*/
printk(KERN_WARNING
"%s tx pipe stalled: requesting reset\n",
hw->wlandev->netdev->name);
list_move(&head->list, &hw->ctlxq.pending);
set_bit(WORK_TX_HALT, &hw->usb_flags);
schedule_work(&hw->usb_work);
break;
}
if (result == -ESHUTDOWN) {
printk(KERN_WARNING "%s urb shutdown!\n",
hw->wlandev->netdev->name);
break;
}
printk(KERN_ERR "Failed to submit CTLX[%d]: error=%d\n",
le16_to_cpu(head->outbuf.type), result);
unlocked_usbctlx_complete(hw, head);
} /* while */
unlock:
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
}
/*----------------------------------------------------------------
* hfa384x_usbin_callback
*
* Callback for URBs on the BULKIN endpoint.
*
* Arguments:
* urb ptr to the completed urb
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_usbin_callback(struct urb *urb)
{
wlandevice_t *wlandev = urb->context;
hfa384x_t *hw;
hfa384x_usbin_t *usbin = (hfa384x_usbin_t *) urb->transfer_buffer;
struct sk_buff *skb = NULL;
int result;
int urb_status;
u16 type;
enum USBIN_ACTION {
HANDLE,
RESUBMIT,
ABORT
} action;
if (!wlandev || !wlandev->netdev || wlandev->hwremoved)
goto exit;
hw = wlandev->priv;
if (!hw)
goto exit;
skb = hw->rx_urb_skb;
BUG_ON(!skb || (skb->data != urb->transfer_buffer));
hw->rx_urb_skb = NULL;
/* Check for error conditions within the URB */
switch (urb->status) {
case 0:
action = HANDLE;
/* Check for short packet */
if (urb->actual_length == 0) {
++(wlandev->linux_stats.rx_errors);
++(wlandev->linux_stats.rx_length_errors);
action = RESUBMIT;
}
break;
case -EPIPE:
printk(KERN_WARNING "%s rx pipe stalled: requesting reset\n",
wlandev->netdev->name);
if (!test_and_set_bit(WORK_RX_HALT, &hw->usb_flags))
schedule_work(&hw->usb_work);
++(wlandev->linux_stats.rx_errors);
action = ABORT;
break;
case -EILSEQ:
case -ETIMEDOUT:
case -EPROTO:
if (!test_and_set_bit(THROTTLE_RX, &hw->usb_flags) &&
!timer_pending(&hw->throttle)) {
mod_timer(&hw->throttle, jiffies + THROTTLE_JIFFIES);
}
++(wlandev->linux_stats.rx_errors);
action = ABORT;
break;
case -EOVERFLOW:
++(wlandev->linux_stats.rx_over_errors);
action = RESUBMIT;
break;
case -ENODEV:
case -ESHUTDOWN:
pr_debug("status=%d, device removed.\n", urb->status);
action = ABORT;
break;
case -ENOENT:
case -ECONNRESET:
pr_debug("status=%d, urb explicitly unlinked.\n", urb->status);
action = ABORT;
break;
default:
pr_debug("urb status=%d, transfer flags=0x%x\n",
urb->status, urb->transfer_flags);
++(wlandev->linux_stats.rx_errors);
action = RESUBMIT;
break;
}
urb_status = urb->status;
if (action != ABORT) {
/* Repost the RX URB */
result = submit_rx_urb(hw, GFP_ATOMIC);
if (result != 0) {
printk(KERN_ERR
"Fatal, failed to resubmit rx_urb. error=%d\n",
result);
}
}
/* Handle any USB-IN packet */
/* Note: the check of the sw_support field, the type field doesn't
* have bit 12 set like the docs suggest.
*/
type = le16_to_cpu(usbin->type);
if (HFA384x_USB_ISRXFRM(type)) {
if (action == HANDLE) {
if (usbin->txfrm.desc.sw_support == 0x0123) {
hfa384x_usbin_txcompl(wlandev, usbin);
} else {
skb_put(skb, sizeof(*usbin));
hfa384x_usbin_rx(wlandev, skb);
skb = NULL;
}
}
goto exit;
}
if (HFA384x_USB_ISTXFRM(type)) {
if (action == HANDLE)
hfa384x_usbin_txcompl(wlandev, usbin);
goto exit;
}
switch (type) {
case HFA384x_USB_INFOFRM:
if (action == ABORT)
goto exit;
if (action == HANDLE)
hfa384x_usbin_info(wlandev, usbin);
break;
case HFA384x_USB_CMDRESP:
case HFA384x_USB_WRIDRESP:
case HFA384x_USB_RRIDRESP:
case HFA384x_USB_WMEMRESP:
case HFA384x_USB_RMEMRESP:
/* ALWAYS, ALWAYS, ALWAYS handle this CTLX!!!! */
hfa384x_usbin_ctlx(hw, usbin, urb_status);
break;
case HFA384x_USB_BUFAVAIL:
pr_debug("Received BUFAVAIL packet, frmlen=%d\n",
usbin->bufavail.frmlen);
break;
case HFA384x_USB_ERROR:
pr_debug("Received USB_ERROR packet, errortype=%d\n",
usbin->usberror.errortype);
break;
default:
pr_debug("Unrecognized USBIN packet, type=%x, status=%d\n",
usbin->type, urb_status);
break;
} /* switch */
exit:
if (skb)
dev_kfree_skb(skb);
}
/*----------------------------------------------------------------
* hfa384x_usbin_ctlx
*
* We've received a URB containing a Prism2 "response" message.
* This message needs to be matched up with a CTLX on the active
* queue and our state updated accordingly.
*
* Arguments:
* hw ptr to hfa384x_t
* usbin ptr to USB IN packet
* urb_status status of this Bulk-In URB
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_usbin_ctlx(hfa384x_t *hw, hfa384x_usbin_t *usbin,
int urb_status)
{
hfa384x_usbctlx_t *ctlx;
int run_queue = 0;
unsigned long flags;
retry:
spin_lock_irqsave(&hw->ctlxq.lock, flags);
/* There can be only one CTLX on the active queue
* at any one time, and this is the CTLX that the
* timers are waiting for.
*/
if (list_empty(&hw->ctlxq.active))
goto unlock;
/* Remove the "response timeout". It's possible that
* we are already too late, and that the timeout is
* already running. And that's just too bad for us,
* because we could lose our CTLX from the active
* queue here ...
*/
if (del_timer(&hw->resptimer) == 0) {
if (hw->resp_timer_done == 0) {
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
goto retry;
}
} else {
hw->resp_timer_done = 1;
}
ctlx = get_active_ctlx(hw);
if (urb_status != 0) {
/*
* Bad CTLX, so get rid of it. But we only
* remove it from the active queue if we're no
* longer expecting the OUT URB to complete.
*/
if (unlocked_usbctlx_cancel_async(hw, ctlx) == 0)
run_queue = 1;
} else {
const u16 intype = (usbin->type & ~cpu_to_le16(0x8000));
/*
* Check that our message is what we're expecting ...
*/
if (ctlx->outbuf.type != intype) {
printk(KERN_WARNING
"Expected IN[%d], received IN[%d] - ignored.\n",
le16_to_cpu(ctlx->outbuf.type),
le16_to_cpu(intype));
goto unlock;
}
/* This URB has succeeded, so grab the data ... */
memcpy(&ctlx->inbuf, usbin, sizeof(ctlx->inbuf));
switch (ctlx->state) {
case CTLX_REQ_SUBMITTED:
/*
* We have received our response URB before
* our request has been acknowledged. Odd,
* but our OUT URB is still alive...
*/
pr_debug("Causality violation: please reboot Universe\n");
ctlx->state = CTLX_RESP_COMPLETE;
break;
case CTLX_REQ_COMPLETE:
/*
* This is the usual path: our request
* has already been acknowledged, and
* now we have received the reply too.
*/
ctlx->state = CTLX_COMPLETE;
unlocked_usbctlx_complete(hw, ctlx);
run_queue = 1;
break;
default:
/*
* Throw this CTLX away ...
*/
printk(KERN_ERR
"Matched IN URB, CTLX[%d] in invalid state(%s)."
" Discarded.\n",
le16_to_cpu(ctlx->outbuf.type),
ctlxstr(ctlx->state));
if (unlocked_usbctlx_cancel_async(hw, ctlx) == 0)
run_queue = 1;
break;
} /* switch */
}
unlock:
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
if (run_queue)
hfa384x_usbctlxq_run(hw);
}
/*----------------------------------------------------------------
* hfa384x_usbin_txcompl
*
* At this point we have the results of a previous transmit.
*
* Arguments:
* wlandev wlan device
* usbin ptr to the usb transfer buffer
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_usbin_txcompl(wlandevice_t *wlandev,
hfa384x_usbin_t *usbin)
{
u16 status;
status = le16_to_cpu(usbin->type); /* yeah I know it says type... */
/* Was there an error? */
if (HFA384x_TXSTATUS_ISERROR(status))
prism2sta_ev_txexc(wlandev, status);
else
prism2sta_ev_tx(wlandev, status);
}
/*----------------------------------------------------------------
* hfa384x_usbin_rx
*
* At this point we have a successful received a rx frame packet.
*
* Arguments:
* wlandev wlan device
* usbin ptr to the usb transfer buffer
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_usbin_rx(wlandevice_t *wlandev, struct sk_buff *skb)
{
hfa384x_usbin_t *usbin = (hfa384x_usbin_t *) skb->data;
hfa384x_t *hw = wlandev->priv;
int hdrlen;
struct p80211_rxmeta *rxmeta;
u16 data_len;
u16 fc;
/* Byte order convert once up front. */
usbin->rxfrm.desc.status = le16_to_cpu(usbin->rxfrm.desc.status);
usbin->rxfrm.desc.time = le32_to_cpu(usbin->rxfrm.desc.time);
/* Now handle frame based on port# */
switch (HFA384x_RXSTATUS_MACPORT_GET(usbin->rxfrm.desc.status)) {
case 0:
fc = le16_to_cpu(usbin->rxfrm.desc.frame_control);
/* If exclude and we receive an unencrypted, drop it */
if ((wlandev->hostwep & HOSTWEP_EXCLUDEUNENCRYPTED) &&
!WLAN_GET_FC_ISWEP(fc)) {
goto done;
}
data_len = le16_to_cpu(usbin->rxfrm.desc.data_len);
/* How much header data do we have? */
hdrlen = p80211_headerlen(fc);
/* Pull off the descriptor */
skb_pull(skb, sizeof(hfa384x_rx_frame_t));
/* Now shunt the header block up against the data block
* with an "overlapping" copy
*/
memmove(skb_push(skb, hdrlen),
&usbin->rxfrm.desc.frame_control, hdrlen);
skb->dev = wlandev->netdev;
skb->dev->last_rx = jiffies;
/* And set the frame length properly */
skb_trim(skb, data_len + hdrlen);
/* The prism2 series does not return the CRC */
memset(skb_put(skb, WLAN_CRC_LEN), 0xff, WLAN_CRC_LEN);
skb_reset_mac_header(skb);
/* Attach the rxmeta, set some stuff */
p80211skb_rxmeta_attach(wlandev, skb);
rxmeta = P80211SKB_RXMETA(skb);
rxmeta->mactime = usbin->rxfrm.desc.time;
rxmeta->rxrate = usbin->rxfrm.desc.rate;
rxmeta->signal = usbin->rxfrm.desc.signal - hw->dbmadjust;
rxmeta->noise = usbin->rxfrm.desc.silence - hw->dbmadjust;
prism2sta_ev_rx(wlandev, skb);
break;
case 7:
if (!HFA384x_RXSTATUS_ISFCSERR(usbin->rxfrm.desc.status)) {
/* Copy to wlansnif skb */
hfa384x_int_rxmonitor(wlandev, &usbin->rxfrm);
dev_kfree_skb(skb);
} else {
pr_debug("Received monitor frame: FCSerr set\n");
}
break;
default:
printk(KERN_WARNING "Received frame on unsupported port=%d\n",
HFA384x_RXSTATUS_MACPORT_GET(usbin->rxfrm.desc.status));
goto done;
break;
}
done:
return;
}
/*----------------------------------------------------------------
* hfa384x_int_rxmonitor
*
* Helper function for int_rx. Handles monitor frames.
* Note that this function allocates space for the FCS and sets it
* to 0xffffffff. The hfa384x doesn't give us the FCS value but the
* higher layers expect it. 0xffffffff is used as a flag to indicate
* the FCS is bogus.
*
* Arguments:
* wlandev wlan device structure
* rxfrm rx descriptor read from card in int_rx
*
* Returns:
* nothing
*
* Side effects:
* Allocates an skb and passes it up via the PF_PACKET interface.
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_int_rxmonitor(wlandevice_t *wlandev,
hfa384x_usb_rxfrm_t *rxfrm)
{
hfa384x_rx_frame_t *rxdesc = &(rxfrm->desc);
unsigned int hdrlen = 0;
unsigned int datalen = 0;
unsigned int skblen = 0;
u8 *datap;
u16 fc;
struct sk_buff *skb;
hfa384x_t *hw = wlandev->priv;
/* Remember the status, time, and data_len fields are in host order */
/* Figure out how big the frame is */
fc = le16_to_cpu(rxdesc->frame_control);
hdrlen = p80211_headerlen(fc);
datalen = le16_to_cpu(rxdesc->data_len);
/* Allocate an ind message+framesize skb */
skblen = sizeof(struct p80211_caphdr) + hdrlen + datalen + WLAN_CRC_LEN;
/* sanity check the length */
if (skblen >
(sizeof(struct p80211_caphdr) +
WLAN_HDR_A4_LEN + WLAN_DATA_MAXLEN + WLAN_CRC_LEN)) {
pr_debug("overlen frm: len=%zd\n",
skblen - sizeof(struct p80211_caphdr));
}
skb = dev_alloc_skb(skblen);
if (skb == NULL) {
printk(KERN_ERR
"alloc_skb failed trying to allocate %d bytes\n",
skblen);
return;
}
/* only prepend the prism header if in the right mode */
if ((wlandev->netdev->type == ARPHRD_IEEE80211_PRISM) &&
(hw->sniffhdr != 0)) {
struct p80211_caphdr *caphdr;
/* The NEW header format! */
datap = skb_put(skb, sizeof(struct p80211_caphdr));
caphdr = (struct p80211_caphdr *) datap;
caphdr->version = htonl(P80211CAPTURE_VERSION);
caphdr->length = htonl(sizeof(struct p80211_caphdr));
caphdr->mactime = __cpu_to_be64(rxdesc->time) * 1000;
caphdr->hosttime = __cpu_to_be64(jiffies);
caphdr->phytype = htonl(4); /* dss_dot11_b */
caphdr->channel = htonl(hw->sniff_channel);
caphdr->datarate = htonl(rxdesc->rate);
caphdr->antenna = htonl(0); /* unknown */
caphdr->priority = htonl(0); /* unknown */
caphdr->ssi_type = htonl(3); /* rssi_raw */
caphdr->ssi_signal = htonl(rxdesc->signal);
caphdr->ssi_noise = htonl(rxdesc->silence);
caphdr->preamble = htonl(0); /* unknown */
caphdr->encoding = htonl(1); /* cck */
}
/* Copy the 802.11 header to the skb
(ctl frames may be less than a full header) */
datap = skb_put(skb, hdrlen);
memcpy(datap, &(rxdesc->frame_control), hdrlen);
/* If any, copy the data from the card to the skb */
if (datalen > 0) {
datap = skb_put(skb, datalen);
memcpy(datap, rxfrm->data, datalen);
/* check for unencrypted stuff if WEP bit set. */
if (*(datap - hdrlen + 1) & 0x40) /* wep set */
if ((*(datap) == 0xaa) && (*(datap + 1) == 0xaa))
/* clear wep; it's the 802.2 header! */
*(datap - hdrlen + 1) &= 0xbf;
}
if (hw->sniff_fcs) {
/* Set the FCS */
datap = skb_put(skb, WLAN_CRC_LEN);
memset(datap, 0xff, WLAN_CRC_LEN);
}
/* pass it back up */
prism2sta_ev_rx(wlandev, skb);
return;
}
/*----------------------------------------------------------------
* hfa384x_usbin_info
*
* At this point we have a successful received a Prism2 info frame.
*
* Arguments:
* wlandev wlan device
* usbin ptr to the usb transfer buffer
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_usbin_info(wlandevice_t *wlandev, hfa384x_usbin_t *usbin)
{
usbin->infofrm.info.framelen =
le16_to_cpu(usbin->infofrm.info.framelen);
prism2sta_ev_info(wlandev, &usbin->infofrm.info);
}
/*----------------------------------------------------------------
* hfa384x_usbout_callback
*
* Callback for URBs on the BULKOUT endpoint.
*
* Arguments:
* urb ptr to the completed urb
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_usbout_callback(struct urb *urb)
{
wlandevice_t *wlandev = urb->context;
hfa384x_usbout_t *usbout = urb->transfer_buffer;
#ifdef DEBUG_USB
dbprint_urb(urb);
#endif
if (wlandev && wlandev->netdev) {
switch (urb->status) {
case 0:
hfa384x_usbout_tx(wlandev, usbout);
break;
case -EPIPE:
{
hfa384x_t *hw = wlandev->priv;
printk(KERN_WARNING
"%s tx pipe stalled: requesting reset\n",
wlandev->netdev->name);
if (!test_and_set_bit
(WORK_TX_HALT, &hw->usb_flags))
schedule_work(&hw->usb_work);
++(wlandev->linux_stats.tx_errors);
break;
}
case -EPROTO:
case -ETIMEDOUT:
case -EILSEQ:
{
hfa384x_t *hw = wlandev->priv;
if (!test_and_set_bit
(THROTTLE_TX, &hw->usb_flags)
&& !timer_pending(&hw->throttle)) {
mod_timer(&hw->throttle,
jiffies + THROTTLE_JIFFIES);
}
++(wlandev->linux_stats.tx_errors);
netif_stop_queue(wlandev->netdev);
break;
}
case -ENOENT:
case -ESHUTDOWN:
/* Ignorable errors */
break;
default:
printk(KERN_INFO "unknown urb->status=%d\n",
urb->status);
++(wlandev->linux_stats.tx_errors);
break;
} /* switch */
}
}
/*----------------------------------------------------------------
* hfa384x_ctlxout_callback
*
* Callback for control data on the BULKOUT endpoint.
*
* Arguments:
* urb ptr to the completed urb
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_ctlxout_callback(struct urb *urb)
{
hfa384x_t *hw = urb->context;
int delete_resptimer = 0;
int timer_ok = 1;
int run_queue = 0;
hfa384x_usbctlx_t *ctlx;
unsigned long flags;
pr_debug("urb->status=%d\n", urb->status);
#ifdef DEBUG_USB
dbprint_urb(urb);
#endif
if ((urb->status == -ESHUTDOWN) ||
(urb->status == -ENODEV) || (hw == NULL))
goto done;
retry:
spin_lock_irqsave(&hw->ctlxq.lock, flags);
/*
* Only one CTLX at a time on the "active" list, and
* none at all if we are unplugged. However, we can
* rely on the disconnect function to clean everything
* up if someone unplugged the adapter.
*/
if (list_empty(&hw->ctlxq.active)) {
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
goto done;
}
/*
* Having something on the "active" queue means
* that we have timers to worry about ...
*/
if (del_timer(&hw->reqtimer) == 0) {
if (hw->req_timer_done == 0) {
/*
* This timer was actually running while we
* were trying to delete it. Let it terminate
* gracefully instead.
*/
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
goto retry;
}
} else {
hw->req_timer_done = 1;
}
ctlx = get_active_ctlx(hw);
if (urb->status == 0) {
/* Request portion of a CTLX is successful */
switch (ctlx->state) {
case CTLX_REQ_SUBMITTED:
/* This OUT-ACK received before IN */
ctlx->state = CTLX_REQ_COMPLETE;
break;
case CTLX_RESP_COMPLETE:
/* IN already received before this OUT-ACK,
* so this command must now be complete.
*/
ctlx->state = CTLX_COMPLETE;
unlocked_usbctlx_complete(hw, ctlx);
run_queue = 1;
break;
default:
/* This is NOT a valid CTLX "success" state! */
printk(KERN_ERR
"Illegal CTLX[%d] success state(%s, %d) in OUT URB\n",
le16_to_cpu(ctlx->outbuf.type),
ctlxstr(ctlx->state), urb->status);
break;
} /* switch */
} else {
/* If the pipe has stalled then we need to reset it */
if ((urb->status == -EPIPE) &&
!test_and_set_bit(WORK_TX_HALT, &hw->usb_flags)) {
printk(KERN_WARNING
"%s tx pipe stalled: requesting reset\n",
hw->wlandev->netdev->name);
schedule_work(&hw->usb_work);
}
/* If someone cancels the OUT URB then its status
* should be either -ECONNRESET or -ENOENT.
*/
ctlx->state = CTLX_REQ_FAILED;
unlocked_usbctlx_complete(hw, ctlx);
delete_resptimer = 1;
run_queue = 1;
}
delresp:
if (delete_resptimer) {
timer_ok = del_timer(&hw->resptimer);
if (timer_ok != 0)
hw->resp_timer_done = 1;
}
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
if (!timer_ok && (hw->resp_timer_done == 0)) {
spin_lock_irqsave(&hw->ctlxq.lock, flags);
goto delresp;
}
if (run_queue)
hfa384x_usbctlxq_run(hw);
done:
;
}
/*----------------------------------------------------------------
* hfa384x_usbctlx_reqtimerfn
*
* Timer response function for CTLX request timeouts. If this
* function is called, it means that the callback for the OUT
* URB containing a Prism2.x XXX_Request was never called.
*
* Arguments:
* data a ptr to the hfa384x_t
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_usbctlx_reqtimerfn(unsigned long data)
{
hfa384x_t *hw = (hfa384x_t *) data;
unsigned long flags;
spin_lock_irqsave(&hw->ctlxq.lock, flags);
hw->req_timer_done = 1;
/* Removing the hardware automatically empties
* the active list ...
*/
if (!list_empty(&hw->ctlxq.active)) {
/*
* We must ensure that our URB is removed from
* the system, if it hasn't already expired.
*/
hw->ctlx_urb.transfer_flags |= URB_ASYNC_UNLINK;
if (usb_unlink_urb(&hw->ctlx_urb) == -EINPROGRESS) {
hfa384x_usbctlx_t *ctlx = get_active_ctlx(hw);
ctlx->state = CTLX_REQ_FAILED;
/* This URB was active, but has now been
* cancelled. It will now have a status of
* -ECONNRESET in the callback function.
*
* We are cancelling this CTLX, so we're
* not going to need to wait for a response.
* The URB's callback function will check
* that this timer is truly dead.
*/
if (del_timer(&hw->resptimer) != 0)
hw->resp_timer_done = 1;
}
}
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
}
/*----------------------------------------------------------------
* hfa384x_usbctlx_resptimerfn
*
* Timer response function for CTLX response timeouts. If this
* function is called, it means that the callback for the IN
* URB containing a Prism2.x XXX_Response was never called.
*
* Arguments:
* data a ptr to the hfa384x_t
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_usbctlx_resptimerfn(unsigned long data)
{
hfa384x_t *hw = (hfa384x_t *) data;
unsigned long flags;
spin_lock_irqsave(&hw->ctlxq.lock, flags);
hw->resp_timer_done = 1;
/* The active list will be empty if the
* adapter has been unplugged ...
*/
if (!list_empty(&hw->ctlxq.active)) {
hfa384x_usbctlx_t *ctlx = get_active_ctlx(hw);
if (unlocked_usbctlx_cancel_async(hw, ctlx) == 0) {
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
hfa384x_usbctlxq_run(hw);
goto done;
}
}
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
done:
;
}
/*----------------------------------------------------------------
* hfa384x_usb_throttlefn
*
*
* Arguments:
* data ptr to hw
*
* Returns:
* Nothing
*
* Side effects:
*
* Call context:
* Interrupt
----------------------------------------------------------------*/
static void hfa384x_usb_throttlefn(unsigned long data)
{
hfa384x_t *hw = (hfa384x_t *) data;
unsigned long flags;
spin_lock_irqsave(&hw->ctlxq.lock, flags);
/*
* We need to check BOTH the RX and the TX throttle controls,
* so we use the bitwise OR instead of the logical OR.
*/
pr_debug("flags=0x%lx\n", hw->usb_flags);
if (!hw->wlandev->hwremoved &&
((test_and_clear_bit(THROTTLE_RX, &hw->usb_flags) &&
!test_and_set_bit(WORK_RX_RESUME, &hw->usb_flags))
|
(test_and_clear_bit(THROTTLE_TX, &hw->usb_flags) &&
!test_and_set_bit(WORK_TX_RESUME, &hw->usb_flags))
)) {
schedule_work(&hw->usb_work);
}
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
}
/*----------------------------------------------------------------
* hfa384x_usbctlx_submit
*
* Called from the doxxx functions to submit a CTLX to the queue
*
* Arguments:
* hw ptr to the hw struct
* ctlx ctlx structure to enqueue
*
* Returns:
* -ENODEV if the adapter is unplugged
* 0
*
* Side effects:
*
* Call context:
* process or interrupt
----------------------------------------------------------------*/
static int hfa384x_usbctlx_submit(hfa384x_t *hw, hfa384x_usbctlx_t *ctlx)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&hw->ctlxq.lock, flags);
if (hw->wlandev->hwremoved) {
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
ret = -ENODEV;
} else {
ctlx->state = CTLX_PENDING;
list_add_tail(&ctlx->list, &hw->ctlxq.pending);
spin_unlock_irqrestore(&hw->ctlxq.lock, flags);
hfa384x_usbctlxq_run(hw);
ret = 0;
}
return ret;
}
/*----------------------------------------------------------------
* hfa384x_usbout_tx
*
* At this point we have finished a send of a frame. Mark the URB
* as available and call ev_alloc to notify higher layers we're
* ready for more.
*
* Arguments:
* wlandev wlan device
* usbout ptr to the usb transfer buffer
*
* Returns:
* nothing
*
* Side effects:
*
* Call context:
* interrupt
----------------------------------------------------------------*/
static void hfa384x_usbout_tx(wlandevice_t *wlandev, hfa384x_usbout_t *usbout)
{
prism2sta_ev_alloc(wlandev);
}
/*----------------------------------------------------------------
* hfa384x_isgood_pdrcore
*
* Quick check of PDR codes.
*
* Arguments:
* pdrcode PDR code number (host order)
*
* Returns:
* zero not good.
* one is good.
*
* Side effects:
*
* Call context:
----------------------------------------------------------------*/
static int hfa384x_isgood_pdrcode(u16 pdrcode)
{
switch (pdrcode) {
case HFA384x_PDR_END_OF_PDA:
case HFA384x_PDR_PCB_PARTNUM:
case HFA384x_PDR_PDAVER:
case HFA384x_PDR_NIC_SERIAL:
case HFA384x_PDR_MKK_MEASUREMENTS:
case HFA384x_PDR_NIC_RAMSIZE:
case HFA384x_PDR_MFISUPRANGE:
case HFA384x_PDR_CFISUPRANGE:
case HFA384x_PDR_NICID:
case HFA384x_PDR_MAC_ADDRESS:
case HFA384x_PDR_REGDOMAIN:
case HFA384x_PDR_ALLOWED_CHANNEL:
case HFA384x_PDR_DEFAULT_CHANNEL:
case HFA384x_PDR_TEMPTYPE:
case HFA384x_PDR_IFR_SETTING:
case HFA384x_PDR_RFR_SETTING:
case HFA384x_PDR_HFA3861_BASELINE:
case HFA384x_PDR_HFA3861_SHADOW:
case HFA384x_PDR_HFA3861_IFRF:
case HFA384x_PDR_HFA3861_CHCALSP:
case HFA384x_PDR_HFA3861_CHCALI:
case HFA384x_PDR_3842_NIC_CONFIG:
case HFA384x_PDR_USB_ID:
case HFA384x_PDR_PCI_ID:
case HFA384x_PDR_PCI_IFCONF:
case HFA384x_PDR_PCI_PMCONF:
case HFA384x_PDR_RFENRGY:
case HFA384x_PDR_HFA3861_MANF_TESTSP:
case HFA384x_PDR_HFA3861_MANF_TESTI:
/* code is OK */
return 1;
break;
default:
if (pdrcode < 0x1000) {
/* code is OK, but we don't know exactly what it is */
pr_debug("Encountered unknown PDR#=0x%04x, "
"assuming it's ok.\n", pdrcode);
return 1;
} else {
/* bad code */
pr_debug("Encountered unknown PDR#=0x%04x, "
"(>=0x1000), assuming it's bad.\n", pdrcode);
return 0;
}
break;
}
return 0; /* avoid compiler warnings */
}
| gpl-2.0 |
megraf/asuswrt-merlin | release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/infiniband/core/addr.c | 183 | 11496 | /*
* Copyright (c) 2005 Voltaire Inc. All rights reserved.
* Copyright (c) 2002-2005, Network Appliance, Inc. All rights reserved.
* Copyright (c) 1999-2005, Mellanox Technologies, Inc. All rights reserved.
* Copyright (c) 2005 Intel Corporation. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/mutex.h>
#include <linux/inetdevice.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <net/arp.h>
#include <net/neighbour.h>
#include <net/route.h>
#include <net/netevent.h>
#include <net/addrconf.h>
#include <net/ip6_route.h>
#include <rdma/ib_addr.h>
MODULE_AUTHOR("Sean Hefty");
MODULE_DESCRIPTION("IB Address Translation");
MODULE_LICENSE("Dual BSD/GPL");
struct addr_req {
struct list_head list;
struct sockaddr_storage src_addr;
struct sockaddr_storage dst_addr;
struct rdma_dev_addr *addr;
struct rdma_addr_client *client;
void *context;
void (*callback)(int status, struct sockaddr *src_addr,
struct rdma_dev_addr *addr, void *context);
unsigned long timeout;
int status;
};
static void process_req(struct work_struct *work);
static DEFINE_MUTEX(lock);
static LIST_HEAD(req_list);
static DECLARE_DELAYED_WORK(work, process_req);
static struct workqueue_struct *addr_wq;
void rdma_addr_register_client(struct rdma_addr_client *client)
{
atomic_set(&client->refcount, 1);
init_completion(&client->comp);
}
EXPORT_SYMBOL(rdma_addr_register_client);
static inline void put_client(struct rdma_addr_client *client)
{
if (atomic_dec_and_test(&client->refcount))
complete(&client->comp);
}
void rdma_addr_unregister_client(struct rdma_addr_client *client)
{
put_client(client);
wait_for_completion(&client->comp);
}
EXPORT_SYMBOL(rdma_addr_unregister_client);
int rdma_copy_addr(struct rdma_dev_addr *dev_addr, struct net_device *dev,
const unsigned char *dst_dev_addr)
{
dev_addr->dev_type = dev->type;
memcpy(dev_addr->src_dev_addr, dev->dev_addr, MAX_ADDR_LEN);
memcpy(dev_addr->broadcast, dev->broadcast, MAX_ADDR_LEN);
if (dst_dev_addr)
memcpy(dev_addr->dst_dev_addr, dst_dev_addr, MAX_ADDR_LEN);
dev_addr->bound_dev_if = dev->ifindex;
return 0;
}
EXPORT_SYMBOL(rdma_copy_addr);
int rdma_translate_ip(struct sockaddr *addr, struct rdma_dev_addr *dev_addr)
{
struct net_device *dev;
int ret = -EADDRNOTAVAIL;
if (dev_addr->bound_dev_if) {
dev = dev_get_by_index(&init_net, dev_addr->bound_dev_if);
if (!dev)
return -ENODEV;
ret = rdma_copy_addr(dev_addr, dev, NULL);
dev_put(dev);
return ret;
}
switch (addr->sa_family) {
case AF_INET:
dev = ip_dev_find(&init_net,
((struct sockaddr_in *) addr)->sin_addr.s_addr);
if (!dev)
return ret;
ret = rdma_copy_addr(dev_addr, dev, NULL);
dev_put(dev);
break;
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
case AF_INET6:
read_lock(&dev_base_lock);
for_each_netdev(&init_net, dev) {
if (ipv6_chk_addr(&init_net,
&((struct sockaddr_in6 *) addr)->sin6_addr,
dev, 1)) {
ret = rdma_copy_addr(dev_addr, dev, NULL);
break;
}
}
read_unlock(&dev_base_lock);
break;
#endif
}
return ret;
}
EXPORT_SYMBOL(rdma_translate_ip);
static void set_timeout(unsigned long time)
{
unsigned long delay;
cancel_delayed_work(&work);
delay = time - jiffies;
if ((long)delay <= 0)
delay = 1;
queue_delayed_work(addr_wq, &work, delay);
}
static void queue_req(struct addr_req *req)
{
struct addr_req *temp_req;
mutex_lock(&lock);
list_for_each_entry_reverse(temp_req, &req_list, list) {
if (time_after_eq(req->timeout, temp_req->timeout))
break;
}
list_add(&req->list, &temp_req->list);
if (req_list.next == &req->list)
set_timeout(req->timeout);
mutex_unlock(&lock);
}
static int addr4_resolve(struct sockaddr_in *src_in,
struct sockaddr_in *dst_in,
struct rdma_dev_addr *addr)
{
__be32 src_ip = src_in->sin_addr.s_addr;
__be32 dst_ip = dst_in->sin_addr.s_addr;
struct flowi fl;
struct rtable *rt;
struct neighbour *neigh;
int ret;
memset(&fl, 0, sizeof fl);
fl.nl_u.ip4_u.daddr = dst_ip;
fl.nl_u.ip4_u.saddr = src_ip;
fl.oif = addr->bound_dev_if;
ret = ip_route_output_key(&init_net, &rt, &fl);
if (ret)
goto out;
src_in->sin_family = AF_INET;
src_in->sin_addr.s_addr = rt->rt_src;
if (rt->idev->dev->flags & IFF_LOOPBACK) {
ret = rdma_translate_ip((struct sockaddr *) dst_in, addr);
if (!ret)
memcpy(addr->dst_dev_addr, addr->src_dev_addr, MAX_ADDR_LEN);
goto put;
}
/* If the device does ARP internally, return 'done' */
if (rt->idev->dev->flags & IFF_NOARP) {
rdma_copy_addr(addr, rt->idev->dev, NULL);
goto put;
}
neigh = neigh_lookup(&arp_tbl, &rt->rt_gateway, rt->idev->dev);
if (!neigh || !(neigh->nud_state & NUD_VALID)) {
neigh_event_send(rt->dst.neighbour, NULL);
ret = -ENODATA;
if (neigh)
goto release;
goto put;
}
ret = rdma_copy_addr(addr, neigh->dev, neigh->ha);
release:
neigh_release(neigh);
put:
ip_rt_put(rt);
out:
return ret;
}
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
static int addr6_resolve(struct sockaddr_in6 *src_in,
struct sockaddr_in6 *dst_in,
struct rdma_dev_addr *addr)
{
struct flowi fl;
struct neighbour *neigh;
struct dst_entry *dst;
int ret;
memset(&fl, 0, sizeof fl);
ipv6_addr_copy(&fl.fl6_dst, &dst_in->sin6_addr);
ipv6_addr_copy(&fl.fl6_src, &src_in->sin6_addr);
fl.oif = addr->bound_dev_if;
dst = ip6_route_output(&init_net, NULL, &fl);
if ((ret = dst->error))
goto put;
if (ipv6_addr_any(&fl.fl6_src)) {
ret = ipv6_dev_get_saddr(&init_net, ip6_dst_idev(dst)->dev,
&fl.fl6_dst, 0, &fl.fl6_src);
if (ret)
goto put;
src_in->sin6_family = AF_INET6;
ipv6_addr_copy(&src_in->sin6_addr, &fl.fl6_src);
}
if (dst->dev->flags & IFF_LOOPBACK) {
ret = rdma_translate_ip((struct sockaddr *) dst_in, addr);
if (!ret)
memcpy(addr->dst_dev_addr, addr->src_dev_addr, MAX_ADDR_LEN);
goto put;
}
/* If the device does ARP internally, return 'done' */
if (dst->dev->flags & IFF_NOARP) {
ret = rdma_copy_addr(addr, dst->dev, NULL);
goto put;
}
neigh = dst->neighbour;
if (!neigh || !(neigh->nud_state & NUD_VALID)) {
neigh_event_send(dst->neighbour, NULL);
ret = -ENODATA;
goto put;
}
ret = rdma_copy_addr(addr, dst->dev, neigh->ha);
put:
dst_release(dst);
return ret;
}
#else
static int addr6_resolve(struct sockaddr_in6 *src_in,
struct sockaddr_in6 *dst_in,
struct rdma_dev_addr *addr)
{
return -EADDRNOTAVAIL;
}
#endif
static int addr_resolve(struct sockaddr *src_in,
struct sockaddr *dst_in,
struct rdma_dev_addr *addr)
{
if (src_in->sa_family == AF_INET) {
return addr4_resolve((struct sockaddr_in *) src_in,
(struct sockaddr_in *) dst_in, addr);
} else
return addr6_resolve((struct sockaddr_in6 *) src_in,
(struct sockaddr_in6 *) dst_in, addr);
}
static void process_req(struct work_struct *work)
{
struct addr_req *req, *temp_req;
struct sockaddr *src_in, *dst_in;
struct list_head done_list;
INIT_LIST_HEAD(&done_list);
mutex_lock(&lock);
list_for_each_entry_safe(req, temp_req, &req_list, list) {
if (req->status == -ENODATA) {
src_in = (struct sockaddr *) &req->src_addr;
dst_in = (struct sockaddr *) &req->dst_addr;
req->status = addr_resolve(src_in, dst_in, req->addr);
if (req->status && time_after_eq(jiffies, req->timeout))
req->status = -ETIMEDOUT;
else if (req->status == -ENODATA)
continue;
}
list_move_tail(&req->list, &done_list);
}
if (!list_empty(&req_list)) {
req = list_entry(req_list.next, struct addr_req, list);
set_timeout(req->timeout);
}
mutex_unlock(&lock);
list_for_each_entry_safe(req, temp_req, &done_list, list) {
list_del(&req->list);
req->callback(req->status, (struct sockaddr *) &req->src_addr,
req->addr, req->context);
put_client(req->client);
kfree(req);
}
}
int rdma_resolve_ip(struct rdma_addr_client *client,
struct sockaddr *src_addr, struct sockaddr *dst_addr,
struct rdma_dev_addr *addr, int timeout_ms,
void (*callback)(int status, struct sockaddr *src_addr,
struct rdma_dev_addr *addr, void *context),
void *context)
{
struct sockaddr *src_in, *dst_in;
struct addr_req *req;
int ret = 0;
req = kzalloc(sizeof *req, GFP_KERNEL);
if (!req)
return -ENOMEM;
src_in = (struct sockaddr *) &req->src_addr;
dst_in = (struct sockaddr *) &req->dst_addr;
if (src_addr) {
if (src_addr->sa_family != dst_addr->sa_family) {
ret = -EINVAL;
goto err;
}
memcpy(src_in, src_addr, ip_addr_size(src_addr));
} else {
src_in->sa_family = dst_addr->sa_family;
}
memcpy(dst_in, dst_addr, ip_addr_size(dst_addr));
req->addr = addr;
req->callback = callback;
req->context = context;
req->client = client;
atomic_inc(&client->refcount);
req->status = addr_resolve(src_in, dst_in, addr);
switch (req->status) {
case 0:
req->timeout = jiffies;
queue_req(req);
break;
case -ENODATA:
req->timeout = msecs_to_jiffies(timeout_ms) + jiffies;
queue_req(req);
break;
default:
ret = req->status;
atomic_dec(&client->refcount);
goto err;
}
return ret;
err:
kfree(req);
return ret;
}
EXPORT_SYMBOL(rdma_resolve_ip);
void rdma_addr_cancel(struct rdma_dev_addr *addr)
{
struct addr_req *req, *temp_req;
mutex_lock(&lock);
list_for_each_entry_safe(req, temp_req, &req_list, list) {
if (req->addr == addr) {
req->status = -ECANCELED;
req->timeout = jiffies;
list_move(&req->list, &req_list);
set_timeout(req->timeout);
break;
}
}
mutex_unlock(&lock);
}
EXPORT_SYMBOL(rdma_addr_cancel);
static int netevent_callback(struct notifier_block *self, unsigned long event,
void *ctx)
{
if (event == NETEVENT_NEIGH_UPDATE) {
struct neighbour *neigh = ctx;
if (neigh->nud_state & NUD_VALID) {
set_timeout(jiffies);
}
}
return 0;
}
static struct notifier_block nb = {
.notifier_call = netevent_callback
};
static int __init addr_init(void)
{
addr_wq = create_singlethread_workqueue("ib_addr");
if (!addr_wq)
return -ENOMEM;
register_netevent_notifier(&nb);
return 0;
}
static void __exit addr_cleanup(void)
{
unregister_netevent_notifier(&nb);
destroy_workqueue(addr_wq);
}
module_init(addr_init);
module_exit(addr_cleanup);
| gpl-2.0 |
LunarG/steamos_kernel | sound/usb/endpoint.c | 439 | 29963 | /*
* 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/gfp.h>
#include <linux/init.h>
#include <linux/ratelimit.h>
#include <linux/usb.h>
#include <linux/usb/audio.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "usbaudio.h"
#include "helper.h"
#include "card.h"
#include "endpoint.h"
#include "pcm.h"
#include "quirks.h"
#define EP_FLAG_ACTIVATED 0
#define EP_FLAG_RUNNING 1
#define EP_FLAG_STOPPING 2
/*
* snd_usb_endpoint is a model that abstracts everything related to an
* USB endpoint and its streaming.
*
* There are functions to activate and deactivate the streaming URBs and
* optional callbacks to let the pcm logic handle the actual content of the
* packets for playback and record. Thus, the bus streaming and the audio
* handlers are fully decoupled.
*
* There are two different types of endpoints in audio applications.
*
* SND_USB_ENDPOINT_TYPE_DATA handles full audio data payload for both
* inbound and outbound traffic.
*
* SND_USB_ENDPOINT_TYPE_SYNC endpoints are for inbound traffic only and
* expect the payload to carry Q10.14 / Q16.16 formatted sync information
* (3 or 4 bytes).
*
* Each endpoint has to be configured prior to being used by calling
* snd_usb_endpoint_set_params().
*
* The model incorporates a reference counting, so that multiple users
* can call snd_usb_endpoint_start() and snd_usb_endpoint_stop(), and
* only the first user will effectively start the URBs, and only the last
* one to stop it will tear the URBs down again.
*/
/*
* convert a sampling rate into our full speed format (fs/1000 in Q16.16)
* this will overflow at approx 524 kHz
*/
static inline unsigned get_usb_full_speed_rate(unsigned int rate)
{
return ((rate << 13) + 62) / 125;
}
/*
* convert a sampling rate into USB high speed format (fs/8000 in Q16.16)
* this will overflow at approx 4 MHz
*/
static inline unsigned get_usb_high_speed_rate(unsigned int rate)
{
return ((rate << 10) + 62) / 125;
}
/*
* release a urb data
*/
static void release_urb_ctx(struct snd_urb_ctx *u)
{
if (u->buffer_size)
usb_free_coherent(u->ep->chip->dev, u->buffer_size,
u->urb->transfer_buffer,
u->urb->transfer_dma);
usb_free_urb(u->urb);
u->urb = NULL;
}
static const char *usb_error_string(int err)
{
switch (err) {
case -ENODEV:
return "no device";
case -ENOENT:
return "endpoint not enabled";
case -EPIPE:
return "endpoint stalled";
case -ENOSPC:
return "not enough bandwidth";
case -ESHUTDOWN:
return "device disabled";
case -EHOSTUNREACH:
return "device suspended";
case -EINVAL:
case -EAGAIN:
case -EFBIG:
case -EMSGSIZE:
return "internal error";
default:
return "unknown error";
}
}
/**
* snd_usb_endpoint_implicit_feedback_sink: Report endpoint usage type
*
* @ep: The snd_usb_endpoint
*
* Determine whether an endpoint is driven by an implicit feedback
* data endpoint source.
*/
int snd_usb_endpoint_implicit_feedback_sink(struct snd_usb_endpoint *ep)
{
return ep->sync_master &&
ep->sync_master->type == SND_USB_ENDPOINT_TYPE_DATA &&
ep->type == SND_USB_ENDPOINT_TYPE_DATA &&
usb_pipeout(ep->pipe);
}
/*
* For streaming based on information derived from sync endpoints,
* prepare_outbound_urb_sizes() will call next_packet_size() to
* determine the number of samples to be sent in the next packet.
*
* For implicit feedback, next_packet_size() is unused.
*/
int snd_usb_endpoint_next_packet_size(struct snd_usb_endpoint *ep)
{
unsigned long flags;
int ret;
if (ep->fill_max)
return ep->maxframesize;
spin_lock_irqsave(&ep->lock, flags);
ep->phase = (ep->phase & 0xffff)
+ (ep->freqm << ep->datainterval);
ret = min(ep->phase >> 16, ep->maxframesize);
spin_unlock_irqrestore(&ep->lock, flags);
return ret;
}
static void retire_outbound_urb(struct snd_usb_endpoint *ep,
struct snd_urb_ctx *urb_ctx)
{
if (ep->retire_data_urb)
ep->retire_data_urb(ep->data_subs, urb_ctx->urb);
}
static void retire_inbound_urb(struct snd_usb_endpoint *ep,
struct snd_urb_ctx *urb_ctx)
{
struct urb *urb = urb_ctx->urb;
if (unlikely(ep->skip_packets > 0)) {
ep->skip_packets--;
return;
}
if (ep->sync_slave)
snd_usb_handle_sync_urb(ep->sync_slave, ep, urb);
if (ep->retire_data_urb)
ep->retire_data_urb(ep->data_subs, urb);
}
/*
* Prepare a PLAYBACK urb for submission to the bus.
*/
static void prepare_outbound_urb(struct snd_usb_endpoint *ep,
struct snd_urb_ctx *ctx)
{
int i;
struct urb *urb = ctx->urb;
unsigned char *cp = urb->transfer_buffer;
urb->dev = ep->chip->dev; /* we need to set this at each time */
switch (ep->type) {
case SND_USB_ENDPOINT_TYPE_DATA:
if (ep->prepare_data_urb) {
ep->prepare_data_urb(ep->data_subs, urb);
} else {
/* no data provider, so send silence */
unsigned int offs = 0;
for (i = 0; i < ctx->packets; ++i) {
int counts;
if (ctx->packet_size[i])
counts = ctx->packet_size[i];
else
counts = snd_usb_endpoint_next_packet_size(ep);
urb->iso_frame_desc[i].offset = offs * ep->stride;
urb->iso_frame_desc[i].length = counts * ep->stride;
offs += counts;
}
urb->number_of_packets = ctx->packets;
urb->transfer_buffer_length = offs * ep->stride;
memset(urb->transfer_buffer, ep->silence_value,
offs * ep->stride);
}
break;
case SND_USB_ENDPOINT_TYPE_SYNC:
if (snd_usb_get_speed(ep->chip->dev) >= USB_SPEED_HIGH) {
/*
* fill the length and offset of each urb descriptor.
* the fixed 12.13 frequency is passed as 16.16 through the pipe.
*/
urb->iso_frame_desc[0].length = 4;
urb->iso_frame_desc[0].offset = 0;
cp[0] = ep->freqn;
cp[1] = ep->freqn >> 8;
cp[2] = ep->freqn >> 16;
cp[3] = ep->freqn >> 24;
} else {
/*
* fill the length and offset of each urb descriptor.
* the fixed 10.14 frequency is passed through the pipe.
*/
urb->iso_frame_desc[0].length = 3;
urb->iso_frame_desc[0].offset = 0;
cp[0] = ep->freqn >> 2;
cp[1] = ep->freqn >> 10;
cp[2] = ep->freqn >> 18;
}
break;
}
}
/*
* Prepare a CAPTURE or SYNC urb for submission to the bus.
*/
static inline void prepare_inbound_urb(struct snd_usb_endpoint *ep,
struct snd_urb_ctx *urb_ctx)
{
int i, offs;
struct urb *urb = urb_ctx->urb;
urb->dev = ep->chip->dev; /* we need to set this at each time */
switch (ep->type) {
case SND_USB_ENDPOINT_TYPE_DATA:
offs = 0;
for (i = 0; i < urb_ctx->packets; i++) {
urb->iso_frame_desc[i].offset = offs;
urb->iso_frame_desc[i].length = ep->curpacksize;
offs += ep->curpacksize;
}
urb->transfer_buffer_length = offs;
urb->number_of_packets = urb_ctx->packets;
break;
case SND_USB_ENDPOINT_TYPE_SYNC:
urb->iso_frame_desc[0].length = min(4u, ep->syncmaxsize);
urb->iso_frame_desc[0].offset = 0;
break;
}
}
/*
* Send output urbs that have been prepared previously. URBs are dequeued
* from ep->ready_playback_urbs and in case there there aren't any available
* or there are no packets that have been prepared, this function does
* nothing.
*
* The reason why the functionality of sending and preparing URBs is separated
* is that host controllers don't guarantee the order in which they return
* inbound and outbound packets to their submitters.
*
* This function is only used for implicit feedback endpoints. For endpoints
* driven by dedicated sync endpoints, URBs are immediately re-submitted
* from their completion handler.
*/
static void queue_pending_output_urbs(struct snd_usb_endpoint *ep)
{
while (test_bit(EP_FLAG_RUNNING, &ep->flags)) {
unsigned long flags;
struct snd_usb_packet_info *uninitialized_var(packet);
struct snd_urb_ctx *ctx = NULL;
struct urb *urb;
int err, i;
spin_lock_irqsave(&ep->lock, flags);
if (ep->next_packet_read_pos != ep->next_packet_write_pos) {
packet = ep->next_packet + ep->next_packet_read_pos;
ep->next_packet_read_pos++;
ep->next_packet_read_pos %= MAX_URBS;
/* take URB out of FIFO */
if (!list_empty(&ep->ready_playback_urbs))
ctx = list_first_entry(&ep->ready_playback_urbs,
struct snd_urb_ctx, ready_list);
}
spin_unlock_irqrestore(&ep->lock, flags);
if (ctx == NULL)
return;
list_del_init(&ctx->ready_list);
urb = ctx->urb;
/* copy over the length information */
for (i = 0; i < packet->packets; i++)
ctx->packet_size[i] = packet->packet_size[i];
/* call the data handler to fill in playback data */
prepare_outbound_urb(ep, ctx);
err = usb_submit_urb(ctx->urb, GFP_ATOMIC);
if (err < 0)
snd_printk(KERN_ERR "Unable to submit urb #%d: %d (urb %p)\n",
ctx->index, err, ctx->urb);
else
set_bit(ctx->index, &ep->active_mask);
}
}
/*
* complete callback for urbs
*/
static void snd_complete_urb(struct urb *urb)
{
struct snd_urb_ctx *ctx = urb->context;
struct snd_usb_endpoint *ep = ctx->ep;
int err;
if (unlikely(urb->status == -ENOENT || /* unlinked */
urb->status == -ENODEV || /* device removed */
urb->status == -ECONNRESET || /* unlinked */
urb->status == -ESHUTDOWN || /* device disabled */
ep->chip->shutdown)) /* device disconnected */
goto exit_clear;
if (usb_pipeout(ep->pipe)) {
retire_outbound_urb(ep, ctx);
/* can be stopped during retire callback */
if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
goto exit_clear;
if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
unsigned long flags;
spin_lock_irqsave(&ep->lock, flags);
list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
spin_unlock_irqrestore(&ep->lock, flags);
queue_pending_output_urbs(ep);
goto exit_clear;
}
prepare_outbound_urb(ep, ctx);
} else {
retire_inbound_urb(ep, ctx);
/* can be stopped during retire callback */
if (unlikely(!test_bit(EP_FLAG_RUNNING, &ep->flags)))
goto exit_clear;
prepare_inbound_urb(ep, ctx);
}
err = usb_submit_urb(urb, GFP_ATOMIC);
if (err == 0)
return;
snd_printk(KERN_ERR "cannot submit urb (err = %d)\n", err);
//snd_pcm_stop(substream, SNDRV_PCM_STATE_XRUN);
exit_clear:
clear_bit(ctx->index, &ep->active_mask);
}
/**
* snd_usb_add_endpoint: Add an endpoint to an USB audio chip
*
* @chip: The chip
* @alts: The USB host interface
* @ep_num: The number of the endpoint to use
* @direction: SNDRV_PCM_STREAM_PLAYBACK or SNDRV_PCM_STREAM_CAPTURE
* @type: SND_USB_ENDPOINT_TYPE_DATA or SND_USB_ENDPOINT_TYPE_SYNC
*
* If the requested endpoint has not been added to the given chip before,
* a new instance is created. Otherwise, a pointer to the previoulsy
* created instance is returned. In case of any error, NULL is returned.
*
* New endpoints will be added to chip->ep_list and must be freed by
* calling snd_usb_endpoint_free().
*/
struct snd_usb_endpoint *snd_usb_add_endpoint(struct snd_usb_audio *chip,
struct usb_host_interface *alts,
int ep_num, int direction, int type)
{
struct snd_usb_endpoint *ep;
int is_playback = direction == SNDRV_PCM_STREAM_PLAYBACK;
mutex_lock(&chip->mutex);
list_for_each_entry(ep, &chip->ep_list, list) {
if (ep->ep_num == ep_num &&
ep->iface == alts->desc.bInterfaceNumber &&
ep->alt_idx == alts->desc.bAlternateSetting) {
snd_printdd(KERN_DEBUG "Re-using EP %x in iface %d,%d @%p\n",
ep_num, ep->iface, ep->alt_idx, ep);
goto __exit_unlock;
}
}
snd_printdd(KERN_DEBUG "Creating new %s %s endpoint #%x\n",
is_playback ? "playback" : "capture",
type == SND_USB_ENDPOINT_TYPE_DATA ? "data" : "sync",
ep_num);
ep = kzalloc(sizeof(*ep), GFP_KERNEL);
if (!ep)
goto __exit_unlock;
ep->chip = chip;
spin_lock_init(&ep->lock);
ep->type = type;
ep->ep_num = ep_num;
ep->iface = alts->desc.bInterfaceNumber;
ep->alt_idx = alts->desc.bAlternateSetting;
INIT_LIST_HEAD(&ep->ready_playback_urbs);
ep_num &= USB_ENDPOINT_NUMBER_MASK;
if (is_playback)
ep->pipe = usb_sndisocpipe(chip->dev, ep_num);
else
ep->pipe = usb_rcvisocpipe(chip->dev, ep_num);
if (type == SND_USB_ENDPOINT_TYPE_SYNC) {
if (get_endpoint(alts, 1)->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE &&
get_endpoint(alts, 1)->bRefresh >= 1 &&
get_endpoint(alts, 1)->bRefresh <= 9)
ep->syncinterval = get_endpoint(alts, 1)->bRefresh;
else if (snd_usb_get_speed(chip->dev) == USB_SPEED_FULL)
ep->syncinterval = 1;
else if (get_endpoint(alts, 1)->bInterval >= 1 &&
get_endpoint(alts, 1)->bInterval <= 16)
ep->syncinterval = get_endpoint(alts, 1)->bInterval - 1;
else
ep->syncinterval = 3;
ep->syncmaxsize = le16_to_cpu(get_endpoint(alts, 1)->wMaxPacketSize);
}
list_add_tail(&ep->list, &chip->ep_list);
__exit_unlock:
mutex_unlock(&chip->mutex);
return ep;
}
/*
* wait until all urbs are processed.
*/
static int wait_clear_urbs(struct snd_usb_endpoint *ep)
{
unsigned long end_time = jiffies + msecs_to_jiffies(1000);
int alive;
do {
alive = bitmap_weight(&ep->active_mask, ep->nurbs);
if (!alive)
break;
schedule_timeout_uninterruptible(1);
} while (time_before(jiffies, end_time));
if (alive)
snd_printk(KERN_ERR "timeout: still %d active urbs on EP #%x\n",
alive, ep->ep_num);
clear_bit(EP_FLAG_STOPPING, &ep->flags);
return 0;
}
/* sync the pending stop operation;
* this function itself doesn't trigger the stop operation
*/
void snd_usb_endpoint_sync_pending_stop(struct snd_usb_endpoint *ep)
{
if (ep && test_bit(EP_FLAG_STOPPING, &ep->flags))
wait_clear_urbs(ep);
}
/*
* unlink active urbs.
*/
static int deactivate_urbs(struct snd_usb_endpoint *ep, bool force)
{
unsigned int i;
if (!force && ep->chip->shutdown) /* to be sure... */
return -EBADFD;
clear_bit(EP_FLAG_RUNNING, &ep->flags);
INIT_LIST_HEAD(&ep->ready_playback_urbs);
ep->next_packet_read_pos = 0;
ep->next_packet_write_pos = 0;
for (i = 0; i < ep->nurbs; i++) {
if (test_bit(i, &ep->active_mask)) {
if (!test_and_set_bit(i, &ep->unlink_mask)) {
struct urb *u = ep->urb[i].urb;
usb_unlink_urb(u);
}
}
}
return 0;
}
/*
* release an endpoint's urbs
*/
static void release_urbs(struct snd_usb_endpoint *ep, int force)
{
int i;
/* route incoming urbs to nirvana */
ep->retire_data_urb = NULL;
ep->prepare_data_urb = NULL;
/* stop urbs */
deactivate_urbs(ep, force);
wait_clear_urbs(ep);
for (i = 0; i < ep->nurbs; i++)
release_urb_ctx(&ep->urb[i]);
if (ep->syncbuf)
usb_free_coherent(ep->chip->dev, SYNC_URBS * 4,
ep->syncbuf, ep->sync_dma);
ep->syncbuf = NULL;
ep->nurbs = 0;
}
/*
* configure a data endpoint
*/
static int data_ep_set_params(struct snd_usb_endpoint *ep,
snd_pcm_format_t pcm_format,
unsigned int channels,
unsigned int period_bytes,
struct audioformat *fmt,
struct snd_usb_endpoint *sync_ep)
{
unsigned int maxsize, i, urb_packs, total_packs, packs_per_ms;
int is_playback = usb_pipeout(ep->pipe);
int frame_bits = snd_pcm_format_physical_width(pcm_format) * channels;
if (pcm_format == SNDRV_PCM_FORMAT_DSD_U16_LE && fmt->dsd_dop) {
/*
* When operating in DSD DOP mode, the size of a sample frame
* in hardware differs from the actual physical format width
* because we need to make room for the DOP markers.
*/
frame_bits += channels << 3;
}
ep->datainterval = fmt->datainterval;
ep->stride = frame_bits >> 3;
ep->silence_value = pcm_format == SNDRV_PCM_FORMAT_U8 ? 0x80 : 0;
/* assume max. frequency is 25% higher than nominal */
ep->freqmax = ep->freqn + (ep->freqn >> 2);
maxsize = ((ep->freqmax + 0xffff) * (frame_bits >> 3))
>> (16 - ep->datainterval);
/* but wMaxPacketSize might reduce this */
if (ep->maxpacksize && ep->maxpacksize < maxsize) {
/* whatever fits into a max. size packet */
maxsize = ep->maxpacksize;
ep->freqmax = (maxsize / (frame_bits >> 3))
<< (16 - ep->datainterval);
}
if (ep->fill_max)
ep->curpacksize = ep->maxpacksize;
else
ep->curpacksize = maxsize;
if (snd_usb_get_speed(ep->chip->dev) != USB_SPEED_FULL)
packs_per_ms = 8 >> ep->datainterval;
else
packs_per_ms = 1;
if (is_playback && !snd_usb_endpoint_implicit_feedback_sink(ep)) {
urb_packs = max(ep->chip->nrpacks, 1);
urb_packs = min(urb_packs, (unsigned int) MAX_PACKS);
} else {
urb_packs = 1;
}
urb_packs *= packs_per_ms;
if (sync_ep && !snd_usb_endpoint_implicit_feedback_sink(ep))
urb_packs = min(urb_packs, 1U << sync_ep->syncinterval);
/* decide how many packets to be used */
if (is_playback && !snd_usb_endpoint_implicit_feedback_sink(ep)) {
unsigned int minsize, maxpacks;
/* determine how small a packet can be */
minsize = (ep->freqn >> (16 - ep->datainterval))
* (frame_bits >> 3);
/* with sync from device, assume it can be 12% lower */
if (sync_ep)
minsize -= minsize >> 3;
minsize = max(minsize, 1u);
total_packs = (period_bytes + minsize - 1) / minsize;
/* we need at least two URBs for queueing */
if (total_packs < 2) {
total_packs = 2;
} else {
/* and we don't want too long a queue either */
maxpacks = max(MAX_QUEUE * packs_per_ms, urb_packs * 2);
total_packs = min(total_packs, maxpacks);
}
} else {
while (urb_packs > 1 && urb_packs * maxsize >= period_bytes)
urb_packs >>= 1;
total_packs = MAX_URBS * urb_packs;
}
ep->nurbs = (total_packs + urb_packs - 1) / urb_packs;
if (ep->nurbs > MAX_URBS) {
/* too much... */
ep->nurbs = MAX_URBS;
total_packs = MAX_URBS * urb_packs;
} else if (ep->nurbs < 2) {
/* too little - we need at least two packets
* to ensure contiguous playback/capture
*/
ep->nurbs = 2;
}
/* allocate and initialize data urbs */
for (i = 0; i < ep->nurbs; i++) {
struct snd_urb_ctx *u = &ep->urb[i];
u->index = i;
u->ep = ep;
u->packets = (i + 1) * total_packs / ep->nurbs
- i * total_packs / ep->nurbs;
u->buffer_size = maxsize * u->packets;
if (fmt->fmt_type == UAC_FORMAT_TYPE_II)
u->packets++; /* for transfer delimiter */
u->urb = usb_alloc_urb(u->packets, GFP_KERNEL);
if (!u->urb)
goto out_of_memory;
u->urb->transfer_buffer =
usb_alloc_coherent(ep->chip->dev, u->buffer_size,
GFP_KERNEL, &u->urb->transfer_dma);
if (!u->urb->transfer_buffer)
goto out_of_memory;
u->urb->pipe = ep->pipe;
u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
u->urb->interval = 1 << ep->datainterval;
u->urb->context = u;
u->urb->complete = snd_complete_urb;
INIT_LIST_HEAD(&u->ready_list);
}
return 0;
out_of_memory:
release_urbs(ep, 0);
return -ENOMEM;
}
/*
* configure a sync endpoint
*/
static int sync_ep_set_params(struct snd_usb_endpoint *ep,
struct audioformat *fmt)
{
int i;
ep->syncbuf = usb_alloc_coherent(ep->chip->dev, SYNC_URBS * 4,
GFP_KERNEL, &ep->sync_dma);
if (!ep->syncbuf)
return -ENOMEM;
for (i = 0; i < SYNC_URBS; i++) {
struct snd_urb_ctx *u = &ep->urb[i];
u->index = i;
u->ep = ep;
u->packets = 1;
u->urb = usb_alloc_urb(1, GFP_KERNEL);
if (!u->urb)
goto out_of_memory;
u->urb->transfer_buffer = ep->syncbuf + i * 4;
u->urb->transfer_dma = ep->sync_dma + i * 4;
u->urb->transfer_buffer_length = 4;
u->urb->pipe = ep->pipe;
u->urb->transfer_flags = URB_NO_TRANSFER_DMA_MAP;
u->urb->number_of_packets = 1;
u->urb->interval = 1 << ep->syncinterval;
u->urb->context = u;
u->urb->complete = snd_complete_urb;
}
ep->nurbs = SYNC_URBS;
return 0;
out_of_memory:
release_urbs(ep, 0);
return -ENOMEM;
}
/**
* snd_usb_endpoint_set_params: configure an snd_usb_endpoint
*
* @ep: the snd_usb_endpoint to configure
* @pcm_format: the audio fomat.
* @channels: the number of audio channels.
* @period_bytes: the number of bytes in one alsa period.
* @rate: the frame rate.
* @fmt: the USB audio format information
* @sync_ep: the sync endpoint to use, if any
*
* Determine the number of URBs to be used on this endpoint.
* An endpoint must be configured before it can be started.
* An endpoint that is already running can not be reconfigured.
*/
int snd_usb_endpoint_set_params(struct snd_usb_endpoint *ep,
snd_pcm_format_t pcm_format,
unsigned int channels,
unsigned int period_bytes,
unsigned int rate,
struct audioformat *fmt,
struct snd_usb_endpoint *sync_ep)
{
int err;
if (ep->use_count != 0) {
snd_printk(KERN_WARNING "Unable to change format on ep #%x: already in use\n",
ep->ep_num);
return -EBUSY;
}
/* release old buffers, if any */
release_urbs(ep, 0);
ep->datainterval = fmt->datainterval;
ep->maxpacksize = fmt->maxpacksize;
ep->fill_max = !!(fmt->attributes & UAC_EP_CS_ATTR_FILL_MAX);
if (snd_usb_get_speed(ep->chip->dev) == USB_SPEED_FULL)
ep->freqn = get_usb_full_speed_rate(rate);
else
ep->freqn = get_usb_high_speed_rate(rate);
/* calculate the frequency in 16.16 format */
ep->freqm = ep->freqn;
ep->freqshift = INT_MIN;
ep->phase = 0;
switch (ep->type) {
case SND_USB_ENDPOINT_TYPE_DATA:
err = data_ep_set_params(ep, pcm_format, channels,
period_bytes, fmt, sync_ep);
break;
case SND_USB_ENDPOINT_TYPE_SYNC:
err = sync_ep_set_params(ep, fmt);
break;
default:
err = -EINVAL;
}
snd_printdd(KERN_DEBUG "Setting params for ep #%x (type %d, %d urbs), ret=%d\n",
ep->ep_num, ep->type, ep->nurbs, err);
return err;
}
/**
* snd_usb_endpoint_start: start an snd_usb_endpoint
*
* @ep: the endpoint to start
* @can_sleep: flag indicating whether the operation is executed in
* non-atomic context
*
* A call to this function will increment the use count of the endpoint.
* In case it is not already running, the URBs for this endpoint will be
* submitted. Otherwise, this function does nothing.
*
* Must be balanced to calls of snd_usb_endpoint_stop().
*
* Returns an error if the URB submission failed, 0 in all other cases.
*/
int snd_usb_endpoint_start(struct snd_usb_endpoint *ep, bool can_sleep)
{
int err;
unsigned int i;
if (ep->chip->shutdown)
return -EBADFD;
/* already running? */
if (++ep->use_count != 1)
return 0;
/* just to be sure */
deactivate_urbs(ep, false);
if (can_sleep)
wait_clear_urbs(ep);
ep->active_mask = 0;
ep->unlink_mask = 0;
ep->phase = 0;
snd_usb_endpoint_start_quirk(ep);
/*
* If this endpoint has a data endpoint as implicit feedback source,
* don't start the urbs here. Instead, mark them all as available,
* wait for the record urbs to return and queue the playback urbs
* from that context.
*/
set_bit(EP_FLAG_RUNNING, &ep->flags);
if (snd_usb_endpoint_implicit_feedback_sink(ep)) {
for (i = 0; i < ep->nurbs; i++) {
struct snd_urb_ctx *ctx = ep->urb + i;
list_add_tail(&ctx->ready_list, &ep->ready_playback_urbs);
}
return 0;
}
for (i = 0; i < ep->nurbs; i++) {
struct urb *urb = ep->urb[i].urb;
if (snd_BUG_ON(!urb))
goto __error;
if (usb_pipeout(ep->pipe)) {
prepare_outbound_urb(ep, urb->context);
} else {
prepare_inbound_urb(ep, urb->context);
}
err = usb_submit_urb(urb, GFP_ATOMIC);
if (err < 0) {
snd_printk(KERN_ERR "cannot submit urb %d, error %d: %s\n",
i, err, usb_error_string(err));
goto __error;
}
set_bit(i, &ep->active_mask);
}
return 0;
__error:
clear_bit(EP_FLAG_RUNNING, &ep->flags);
ep->use_count--;
deactivate_urbs(ep, false);
return -EPIPE;
}
/**
* snd_usb_endpoint_stop: stop an snd_usb_endpoint
*
* @ep: the endpoint to stop (may be NULL)
*
* A call to this function will decrement the use count of the endpoint.
* In case the last user has requested the endpoint stop, the URBs will
* actually be deactivated.
*
* Must be balanced to calls of snd_usb_endpoint_start().
*
* The caller needs to synchronize the pending stop operation via
* snd_usb_endpoint_sync_pending_stop().
*/
void snd_usb_endpoint_stop(struct snd_usb_endpoint *ep)
{
if (!ep)
return;
if (snd_BUG_ON(ep->use_count == 0))
return;
if (--ep->use_count == 0) {
deactivate_urbs(ep, false);
ep->data_subs = NULL;
ep->sync_slave = NULL;
ep->retire_data_urb = NULL;
ep->prepare_data_urb = NULL;
set_bit(EP_FLAG_STOPPING, &ep->flags);
}
}
/**
* snd_usb_endpoint_deactivate: deactivate an snd_usb_endpoint
*
* @ep: the endpoint to deactivate
*
* If the endpoint is not currently in use, this functions will select the
* alternate interface setting 0 for the interface of this endpoint.
*
* In case of any active users, this functions does nothing.
*
* Returns an error if usb_set_interface() failed, 0 in all other
* cases.
*/
int snd_usb_endpoint_deactivate(struct snd_usb_endpoint *ep)
{
if (!ep)
return -EINVAL;
deactivate_urbs(ep, true);
wait_clear_urbs(ep);
if (ep->use_count != 0)
return 0;
clear_bit(EP_FLAG_ACTIVATED, &ep->flags);
return 0;
}
/**
* snd_usb_endpoint_free: Free the resources of an snd_usb_endpoint
*
* @ep: the list header of the endpoint to free
*
* This function does not care for the endpoint's use count but will tear
* down all the streaming URBs immediately and free all resources.
*/
void snd_usb_endpoint_free(struct list_head *head)
{
struct snd_usb_endpoint *ep;
ep = list_entry(head, struct snd_usb_endpoint, list);
release_urbs(ep, 1);
kfree(ep);
}
/**
* snd_usb_handle_sync_urb: parse an USB sync packet
*
* @ep: the endpoint to handle the packet
* @sender: the sending endpoint
* @urb: the received packet
*
* This function is called from the context of an endpoint that received
* the packet and is used to let another endpoint object handle the payload.
*/
void snd_usb_handle_sync_urb(struct snd_usb_endpoint *ep,
struct snd_usb_endpoint *sender,
const struct urb *urb)
{
int shift;
unsigned int f;
unsigned long flags;
snd_BUG_ON(ep == sender);
/*
* In case the endpoint is operating in implicit feedback mode, prepare
* a new outbound URB that has the same layout as the received packet
* and add it to the list of pending urbs. queue_pending_output_urbs()
* will take care of them later.
*/
if (snd_usb_endpoint_implicit_feedback_sink(ep) &&
ep->use_count != 0) {
/* implicit feedback case */
int i, bytes = 0;
struct snd_urb_ctx *in_ctx;
struct snd_usb_packet_info *out_packet;
in_ctx = urb->context;
/* Count overall packet size */
for (i = 0; i < in_ctx->packets; i++)
if (urb->iso_frame_desc[i].status == 0)
bytes += urb->iso_frame_desc[i].actual_length;
/*
* skip empty packets. At least M-Audio's Fast Track Ultra stops
* streaming once it received a 0-byte OUT URB
*/
if (bytes == 0)
return;
spin_lock_irqsave(&ep->lock, flags);
out_packet = ep->next_packet + ep->next_packet_write_pos;
/*
* Iterate through the inbound packet and prepare the lengths
* for the output packet. The OUT packet we are about to send
* will have the same amount of payload bytes per stride as the
* IN packet we just received. Since the actual size is scaled
* by the stride, use the sender stride to calculate the length
* in case the number of channels differ between the implicitly
* fed-back endpoint and the synchronizing endpoint.
*/
out_packet->packets = in_ctx->packets;
for (i = 0; i < in_ctx->packets; i++) {
if (urb->iso_frame_desc[i].status == 0)
out_packet->packet_size[i] =
urb->iso_frame_desc[i].actual_length / sender->stride;
else
out_packet->packet_size[i] = 0;
}
ep->next_packet_write_pos++;
ep->next_packet_write_pos %= MAX_URBS;
spin_unlock_irqrestore(&ep->lock, flags);
queue_pending_output_urbs(ep);
return;
}
/*
* process after playback sync complete
*
* Full speed devices report feedback values in 10.14 format as samples
* per frame, high speed devices in 16.16 format as samples per
* microframe.
*
* Because the Audio Class 1 spec was written before USB 2.0, many high
* speed devices use a wrong interpretation, some others use an
* entirely different format.
*
* Therefore, we cannot predict what format any particular device uses
* and must detect it automatically.
*/
if (urb->iso_frame_desc[0].status != 0 ||
urb->iso_frame_desc[0].actual_length < 3)
return;
f = le32_to_cpup(urb->transfer_buffer);
if (urb->iso_frame_desc[0].actual_length == 3)
f &= 0x00ffffff;
else
f &= 0x0fffffff;
if (f == 0)
return;
if (unlikely(ep->freqshift == INT_MIN)) {
/*
* The first time we see a feedback value, determine its format
* by shifting it left or right until it matches the nominal
* frequency value. This assumes that the feedback does not
* differ from the nominal value more than +50% or -25%.
*/
shift = 0;
while (f < ep->freqn - ep->freqn / 4) {
f <<= 1;
shift++;
}
while (f > ep->freqn + ep->freqn / 2) {
f >>= 1;
shift--;
}
ep->freqshift = shift;
} else if (ep->freqshift >= 0)
f <<= ep->freqshift;
else
f >>= -ep->freqshift;
if (likely(f >= ep->freqn - ep->freqn / 8 && f <= ep->freqmax)) {
/*
* If the frequency looks valid, set it.
* This value is referred to in prepare_playback_urb().
*/
spin_lock_irqsave(&ep->lock, flags);
ep->freqm = f;
spin_unlock_irqrestore(&ep->lock, flags);
} else {
/*
* Out of range; maybe the shift value is wrong.
* Reset it so that we autodetect again the next time.
*/
ep->freqshift = INT_MIN;
}
}
| gpl-2.0 |
jakwu/linux-imx | drivers/crypto/ux500/cryp/cryp_core.c | 1207 | 45155 | /**
* Copyright (C) ST-Ericsson SA 2010
* Author: Shujuan Chen <shujuan.chen@stericsson.com> for ST-Ericsson.
* Author: Joakim Bech <joakim.xx.bech@stericsson.com> for ST-Ericsson.
* Author: Berne Hebark <berne.herbark@stericsson.com> for ST-Ericsson.
* Author: Niklas Hernaeus <niklas.hernaeus@stericsson.com> for ST-Ericsson.
* Author: Jonas Linde <jonas.linde@stericsson.com> for ST-Ericsson.
* Author: Andreas Westin <andreas.westin@stericsson.com> for ST-Ericsson.
* License terms: GNU General Public License (GPL) version 2
*/
#include <linux/clk.h>
#include <linux/completion.h>
#include <linux/crypto.h>
#include <linux/dmaengine.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/irqreturn.h>
#include <linux/klist.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/regulator/consumer.h>
#include <linux/semaphore.h>
#include <linux/platform_data/dma-ste-dma40.h>
#include <crypto/aes.h>
#include <crypto/algapi.h>
#include <crypto/ctr.h>
#include <crypto/des.h>
#include <crypto/scatterwalk.h>
#include <linux/platform_data/crypto-ux500.h>
#include "cryp_p.h"
#include "cryp.h"
#define CRYP_MAX_KEY_SIZE 32
#define BYTES_PER_WORD 4
static int cryp_mode;
static atomic_t session_id;
static struct stedma40_chan_cfg *mem_to_engine;
static struct stedma40_chan_cfg *engine_to_mem;
/**
* struct cryp_driver_data - data specific to the driver.
*
* @device_list: A list of registered devices to choose from.
* @device_allocation: A semaphore initialized with number of devices.
*/
struct cryp_driver_data {
struct klist device_list;
struct semaphore device_allocation;
};
/**
* struct cryp_ctx - Crypto context
* @config: Crypto mode.
* @key[CRYP_MAX_KEY_SIZE]: Key.
* @keylen: Length of key.
* @iv: Pointer to initialization vector.
* @indata: Pointer to indata.
* @outdata: Pointer to outdata.
* @datalen: Length of indata.
* @outlen: Length of outdata.
* @blocksize: Size of blocks.
* @updated: Updated flag.
* @dev_ctx: Device dependent context.
* @device: Pointer to the device.
*/
struct cryp_ctx {
struct cryp_config config;
u8 key[CRYP_MAX_KEY_SIZE];
u32 keylen;
u8 *iv;
const u8 *indata;
u8 *outdata;
u32 datalen;
u32 outlen;
u32 blocksize;
u8 updated;
struct cryp_device_context dev_ctx;
struct cryp_device_data *device;
u32 session_id;
};
static struct cryp_driver_data driver_data;
/**
* uint8p_to_uint32_be - 4*uint8 to uint32 big endian
* @in: Data to convert.
*/
static inline u32 uint8p_to_uint32_be(u8 *in)
{
u32 *data = (u32 *)in;
return cpu_to_be32p(data);
}
/**
* swap_bits_in_byte - mirror the bits in a byte
* @b: the byte to be mirrored
*
* The bits are swapped the following way:
* Byte b include bits 0-7, nibble 1 (n1) include bits 0-3 and
* nibble 2 (n2) bits 4-7.
*
* Nibble 1 (n1):
* (The "old" (moved) bit is replaced with a zero)
* 1. Move bit 6 and 7, 4 positions to the left.
* 2. Move bit 3 and 5, 2 positions to the left.
* 3. Move bit 1-4, 1 position to the left.
*
* Nibble 2 (n2):
* 1. Move bit 0 and 1, 4 positions to the right.
* 2. Move bit 2 and 4, 2 positions to the right.
* 3. Move bit 3-6, 1 position to the right.
*
* Combine the two nibbles to a complete and swapped byte.
*/
static inline u8 swap_bits_in_byte(u8 b)
{
#define R_SHIFT_4_MASK 0xc0 /* Bits 6 and 7, right shift 4 */
#define R_SHIFT_2_MASK 0x28 /* (After right shift 4) Bits 3 and 5,
right shift 2 */
#define R_SHIFT_1_MASK 0x1e /* (After right shift 2) Bits 1-4,
right shift 1 */
#define L_SHIFT_4_MASK 0x03 /* Bits 0 and 1, left shift 4 */
#define L_SHIFT_2_MASK 0x14 /* (After left shift 4) Bits 2 and 4,
left shift 2 */
#define L_SHIFT_1_MASK 0x78 /* (After left shift 1) Bits 3-6,
left shift 1 */
u8 n1;
u8 n2;
/* Swap most significant nibble */
/* Right shift 4, bits 6 and 7 */
n1 = ((b & R_SHIFT_4_MASK) >> 4) | (b & ~(R_SHIFT_4_MASK >> 4));
/* Right shift 2, bits 3 and 5 */
n1 = ((n1 & R_SHIFT_2_MASK) >> 2) | (n1 & ~(R_SHIFT_2_MASK >> 2));
/* Right shift 1, bits 1-4 */
n1 = (n1 & R_SHIFT_1_MASK) >> 1;
/* Swap least significant nibble */
/* Left shift 4, bits 0 and 1 */
n2 = ((b & L_SHIFT_4_MASK) << 4) | (b & ~(L_SHIFT_4_MASK << 4));
/* Left shift 2, bits 2 and 4 */
n2 = ((n2 & L_SHIFT_2_MASK) << 2) | (n2 & ~(L_SHIFT_2_MASK << 2));
/* Left shift 1, bits 3-6 */
n2 = (n2 & L_SHIFT_1_MASK) << 1;
return n1 | n2;
}
static inline void swap_words_in_key_and_bits_in_byte(const u8 *in,
u8 *out, u32 len)
{
unsigned int i = 0;
int j;
int index = 0;
j = len - BYTES_PER_WORD;
while (j >= 0) {
for (i = 0; i < BYTES_PER_WORD; i++) {
index = len - j - BYTES_PER_WORD + i;
out[j + i] =
swap_bits_in_byte(in[index]);
}
j -= BYTES_PER_WORD;
}
}
static void add_session_id(struct cryp_ctx *ctx)
{
/*
* We never want 0 to be a valid value, since this is the default value
* for the software context.
*/
if (unlikely(atomic_inc_and_test(&session_id)))
atomic_inc(&session_id);
ctx->session_id = atomic_read(&session_id);
}
static irqreturn_t cryp_interrupt_handler(int irq, void *param)
{
struct cryp_ctx *ctx;
int i;
struct cryp_device_data *device_data;
if (param == NULL) {
BUG_ON(!param);
return IRQ_HANDLED;
}
/* The device is coming from the one found in hw_crypt_noxts. */
device_data = (struct cryp_device_data *)param;
ctx = device_data->current_ctx;
if (ctx == NULL) {
BUG_ON(!ctx);
return IRQ_HANDLED;
}
dev_dbg(ctx->device->dev, "[%s] (len: %d) %s, ", __func__, ctx->outlen,
cryp_pending_irq_src(device_data, CRYP_IRQ_SRC_OUTPUT_FIFO) ?
"out" : "in");
if (cryp_pending_irq_src(device_data,
CRYP_IRQ_SRC_OUTPUT_FIFO)) {
if (ctx->outlen / ctx->blocksize > 0) {
for (i = 0; i < ctx->blocksize / 4; i++) {
*(ctx->outdata) = readl_relaxed(
&device_data->base->dout);
ctx->outdata += 4;
ctx->outlen -= 4;
}
if (ctx->outlen == 0) {
cryp_disable_irq_src(device_data,
CRYP_IRQ_SRC_OUTPUT_FIFO);
}
}
} else if (cryp_pending_irq_src(device_data,
CRYP_IRQ_SRC_INPUT_FIFO)) {
if (ctx->datalen / ctx->blocksize > 0) {
for (i = 0 ; i < ctx->blocksize / 4; i++) {
writel_relaxed(ctx->indata,
&device_data->base->din);
ctx->indata += 4;
ctx->datalen -= 4;
}
if (ctx->datalen == 0)
cryp_disable_irq_src(device_data,
CRYP_IRQ_SRC_INPUT_FIFO);
if (ctx->config.algomode == CRYP_ALGO_AES_XTS) {
CRYP_PUT_BITS(&device_data->base->cr,
CRYP_START_ENABLE,
CRYP_CR_START_POS,
CRYP_CR_START_MASK);
cryp_wait_until_done(device_data);
}
}
}
return IRQ_HANDLED;
}
static int mode_is_aes(enum cryp_algo_mode mode)
{
return CRYP_ALGO_AES_ECB == mode ||
CRYP_ALGO_AES_CBC == mode ||
CRYP_ALGO_AES_CTR == mode ||
CRYP_ALGO_AES_XTS == mode;
}
static int cfg_iv(struct cryp_device_data *device_data, u32 left, u32 right,
enum cryp_init_vector_index index)
{
struct cryp_init_vector_value vector_value;
dev_dbg(device_data->dev, "[%s]", __func__);
vector_value.init_value_left = left;
vector_value.init_value_right = right;
return cryp_configure_init_vector(device_data,
index,
vector_value);
}
static int cfg_ivs(struct cryp_device_data *device_data, struct cryp_ctx *ctx)
{
int i;
int status = 0;
int num_of_regs = ctx->blocksize / 8;
u32 iv[AES_BLOCK_SIZE / 4];
dev_dbg(device_data->dev, "[%s]", __func__);
/*
* Since we loop on num_of_regs we need to have a check in case
* someone provides an incorrect blocksize which would force calling
* cfg_iv with i greater than 2 which is an error.
*/
if (num_of_regs > 2) {
dev_err(device_data->dev, "[%s] Incorrect blocksize %d",
__func__, ctx->blocksize);
return -EINVAL;
}
for (i = 0; i < ctx->blocksize / 4; i++)
iv[i] = uint8p_to_uint32_be(ctx->iv + i*4);
for (i = 0; i < num_of_regs; i++) {
status = cfg_iv(device_data, iv[i*2], iv[i*2+1],
(enum cryp_init_vector_index) i);
if (status != 0)
return status;
}
return status;
}
static int set_key(struct cryp_device_data *device_data,
u32 left_key,
u32 right_key,
enum cryp_key_reg_index index)
{
struct cryp_key_value key_value;
int cryp_error;
dev_dbg(device_data->dev, "[%s]", __func__);
key_value.key_value_left = left_key;
key_value.key_value_right = right_key;
cryp_error = cryp_configure_key_values(device_data,
index,
key_value);
if (cryp_error != 0)
dev_err(device_data->dev, "[%s]: "
"cryp_configure_key_values() failed!", __func__);
return cryp_error;
}
static int cfg_keys(struct cryp_ctx *ctx)
{
int i;
int num_of_regs = ctx->keylen / 8;
u32 swapped_key[CRYP_MAX_KEY_SIZE / 4];
int cryp_error = 0;
dev_dbg(ctx->device->dev, "[%s]", __func__);
if (mode_is_aes(ctx->config.algomode)) {
swap_words_in_key_and_bits_in_byte((u8 *)ctx->key,
(u8 *)swapped_key,
ctx->keylen);
} else {
for (i = 0; i < ctx->keylen / 4; i++)
swapped_key[i] = uint8p_to_uint32_be(ctx->key + i*4);
}
for (i = 0; i < num_of_regs; i++) {
cryp_error = set_key(ctx->device,
*(((u32 *)swapped_key)+i*2),
*(((u32 *)swapped_key)+i*2+1),
(enum cryp_key_reg_index) i);
if (cryp_error != 0) {
dev_err(ctx->device->dev, "[%s]: set_key() failed!",
__func__);
return cryp_error;
}
}
return cryp_error;
}
static int cryp_setup_context(struct cryp_ctx *ctx,
struct cryp_device_data *device_data)
{
u32 control_register = CRYP_CR_DEFAULT;
switch (cryp_mode) {
case CRYP_MODE_INTERRUPT:
writel_relaxed(CRYP_IMSC_DEFAULT, &device_data->base->imsc);
break;
case CRYP_MODE_DMA:
writel_relaxed(CRYP_DMACR_DEFAULT, &device_data->base->dmacr);
break;
default:
break;
}
if (ctx->updated == 0) {
cryp_flush_inoutfifo(device_data);
if (cfg_keys(ctx) != 0) {
dev_err(ctx->device->dev, "[%s]: cfg_keys failed!",
__func__);
return -EINVAL;
}
if (ctx->iv &&
CRYP_ALGO_AES_ECB != ctx->config.algomode &&
CRYP_ALGO_DES_ECB != ctx->config.algomode &&
CRYP_ALGO_TDES_ECB != ctx->config.algomode) {
if (cfg_ivs(device_data, ctx) != 0)
return -EPERM;
}
cryp_set_configuration(device_data, &ctx->config,
&control_register);
add_session_id(ctx);
} else if (ctx->updated == 1 &&
ctx->session_id != atomic_read(&session_id)) {
cryp_flush_inoutfifo(device_data);
cryp_restore_device_context(device_data, &ctx->dev_ctx);
add_session_id(ctx);
control_register = ctx->dev_ctx.cr;
} else
control_register = ctx->dev_ctx.cr;
writel(control_register |
(CRYP_CRYPEN_ENABLE << CRYP_CR_CRYPEN_POS),
&device_data->base->cr);
return 0;
}
static int cryp_get_device_data(struct cryp_ctx *ctx,
struct cryp_device_data **device_data)
{
int ret;
struct klist_iter device_iterator;
struct klist_node *device_node;
struct cryp_device_data *local_device_data = NULL;
pr_debug(DEV_DBG_NAME " [%s]", __func__);
/* Wait until a device is available */
ret = down_interruptible(&driver_data.device_allocation);
if (ret)
return ret; /* Interrupted */
/* Select a device */
klist_iter_init(&driver_data.device_list, &device_iterator);
device_node = klist_next(&device_iterator);
while (device_node) {
local_device_data = container_of(device_node,
struct cryp_device_data, list_node);
spin_lock(&local_device_data->ctx_lock);
/* current_ctx allocates a device, NULL = unallocated */
if (local_device_data->current_ctx) {
device_node = klist_next(&device_iterator);
} else {
local_device_data->current_ctx = ctx;
ctx->device = local_device_data;
spin_unlock(&local_device_data->ctx_lock);
break;
}
spin_unlock(&local_device_data->ctx_lock);
}
klist_iter_exit(&device_iterator);
if (!device_node) {
/**
* No free device found.
* Since we allocated a device with down_interruptible, this
* should not be able to happen.
* Number of available devices, which are contained in
* device_allocation, is therefore decremented by not doing
* an up(device_allocation).
*/
return -EBUSY;
}
*device_data = local_device_data;
return 0;
}
static void cryp_dma_setup_channel(struct cryp_device_data *device_data,
struct device *dev)
{
dma_cap_zero(device_data->dma.mask);
dma_cap_set(DMA_SLAVE, device_data->dma.mask);
device_data->dma.cfg_mem2cryp = mem_to_engine;
device_data->dma.chan_mem2cryp =
dma_request_channel(device_data->dma.mask,
stedma40_filter,
device_data->dma.cfg_mem2cryp);
device_data->dma.cfg_cryp2mem = engine_to_mem;
device_data->dma.chan_cryp2mem =
dma_request_channel(device_data->dma.mask,
stedma40_filter,
device_data->dma.cfg_cryp2mem);
init_completion(&device_data->dma.cryp_dma_complete);
}
static void cryp_dma_out_callback(void *data)
{
struct cryp_ctx *ctx = (struct cryp_ctx *) data;
dev_dbg(ctx->device->dev, "[%s]: ", __func__);
complete(&ctx->device->dma.cryp_dma_complete);
}
static int cryp_set_dma_transfer(struct cryp_ctx *ctx,
struct scatterlist *sg,
int len,
enum dma_data_direction direction)
{
struct dma_async_tx_descriptor *desc;
struct dma_chan *channel = NULL;
dma_cookie_t cookie;
dev_dbg(ctx->device->dev, "[%s]: ", __func__);
if (unlikely(!IS_ALIGNED((u32)sg, 4))) {
dev_err(ctx->device->dev, "[%s]: Data in sg list isn't "
"aligned! Addr: 0x%08x", __func__, (u32)sg);
return -EFAULT;
}
switch (direction) {
case DMA_TO_DEVICE:
channel = ctx->device->dma.chan_mem2cryp;
ctx->device->dma.sg_src = sg;
ctx->device->dma.sg_src_len = dma_map_sg(channel->device->dev,
ctx->device->dma.sg_src,
ctx->device->dma.nents_src,
direction);
if (!ctx->device->dma.sg_src_len) {
dev_dbg(ctx->device->dev,
"[%s]: Could not map the sg list (TO_DEVICE)",
__func__);
return -EFAULT;
}
dev_dbg(ctx->device->dev, "[%s]: Setting up DMA for buffer "
"(TO_DEVICE)", __func__);
desc = channel->device->device_prep_slave_sg(channel,
ctx->device->dma.sg_src,
ctx->device->dma.sg_src_len,
direction, DMA_CTRL_ACK, NULL);
break;
case DMA_FROM_DEVICE:
channel = ctx->device->dma.chan_cryp2mem;
ctx->device->dma.sg_dst = sg;
ctx->device->dma.sg_dst_len = dma_map_sg(channel->device->dev,
ctx->device->dma.sg_dst,
ctx->device->dma.nents_dst,
direction);
if (!ctx->device->dma.sg_dst_len) {
dev_dbg(ctx->device->dev,
"[%s]: Could not map the sg list (FROM_DEVICE)",
__func__);
return -EFAULT;
}
dev_dbg(ctx->device->dev, "[%s]: Setting up DMA for buffer "
"(FROM_DEVICE)", __func__);
desc = channel->device->device_prep_slave_sg(channel,
ctx->device->dma.sg_dst,
ctx->device->dma.sg_dst_len,
direction,
DMA_CTRL_ACK |
DMA_PREP_INTERRUPT, NULL);
desc->callback = cryp_dma_out_callback;
desc->callback_param = ctx;
break;
default:
dev_dbg(ctx->device->dev, "[%s]: Invalid DMA direction",
__func__);
return -EFAULT;
}
cookie = desc->tx_submit(desc);
dma_async_issue_pending(channel);
return 0;
}
static void cryp_dma_done(struct cryp_ctx *ctx)
{
struct dma_chan *chan;
dev_dbg(ctx->device->dev, "[%s]: ", __func__);
chan = ctx->device->dma.chan_mem2cryp;
chan->device->device_control(chan, DMA_TERMINATE_ALL, 0);
dma_unmap_sg(chan->device->dev, ctx->device->dma.sg_src,
ctx->device->dma.sg_src_len, DMA_TO_DEVICE);
chan = ctx->device->dma.chan_cryp2mem;
chan->device->device_control(chan, DMA_TERMINATE_ALL, 0);
dma_unmap_sg(chan->device->dev, ctx->device->dma.sg_dst,
ctx->device->dma.sg_dst_len, DMA_FROM_DEVICE);
}
static int cryp_dma_write(struct cryp_ctx *ctx, struct scatterlist *sg,
int len)
{
int error = cryp_set_dma_transfer(ctx, sg, len, DMA_TO_DEVICE);
dev_dbg(ctx->device->dev, "[%s]: ", __func__);
if (error) {
dev_dbg(ctx->device->dev, "[%s]: cryp_set_dma_transfer() "
"failed", __func__);
return error;
}
return len;
}
static int cryp_dma_read(struct cryp_ctx *ctx, struct scatterlist *sg, int len)
{
int error = cryp_set_dma_transfer(ctx, sg, len, DMA_FROM_DEVICE);
if (error) {
dev_dbg(ctx->device->dev, "[%s]: cryp_set_dma_transfer() "
"failed", __func__);
return error;
}
return len;
}
static void cryp_polling_mode(struct cryp_ctx *ctx,
struct cryp_device_data *device_data)
{
int len = ctx->blocksize / BYTES_PER_WORD;
int remaining_length = ctx->datalen;
u32 *indata = (u32 *)ctx->indata;
u32 *outdata = (u32 *)ctx->outdata;
while (remaining_length > 0) {
writesl(&device_data->base->din, indata, len);
indata += len;
remaining_length -= (len * BYTES_PER_WORD);
cryp_wait_until_done(device_data);
readsl(&device_data->base->dout, outdata, len);
outdata += len;
cryp_wait_until_done(device_data);
}
}
static int cryp_disable_power(struct device *dev,
struct cryp_device_data *device_data,
bool save_device_context)
{
int ret = 0;
dev_dbg(dev, "[%s]", __func__);
spin_lock(&device_data->power_state_spinlock);
if (!device_data->power_state)
goto out;
spin_lock(&device_data->ctx_lock);
if (save_device_context && device_data->current_ctx) {
cryp_save_device_context(device_data,
&device_data->current_ctx->dev_ctx,
cryp_mode);
device_data->restore_dev_ctx = true;
}
spin_unlock(&device_data->ctx_lock);
clk_disable(device_data->clk);
ret = regulator_disable(device_data->pwr_regulator);
if (ret)
dev_err(dev, "[%s]: "
"regulator_disable() failed!",
__func__);
device_data->power_state = false;
out:
spin_unlock(&device_data->power_state_spinlock);
return ret;
}
static int cryp_enable_power(
struct device *dev,
struct cryp_device_data *device_data,
bool restore_device_context)
{
int ret = 0;
dev_dbg(dev, "[%s]", __func__);
spin_lock(&device_data->power_state_spinlock);
if (!device_data->power_state) {
ret = regulator_enable(device_data->pwr_regulator);
if (ret) {
dev_err(dev, "[%s]: regulator_enable() failed!",
__func__);
goto out;
}
ret = clk_enable(device_data->clk);
if (ret) {
dev_err(dev, "[%s]: clk_enable() failed!",
__func__);
regulator_disable(device_data->pwr_regulator);
goto out;
}
device_data->power_state = true;
}
if (device_data->restore_dev_ctx) {
spin_lock(&device_data->ctx_lock);
if (restore_device_context && device_data->current_ctx) {
device_data->restore_dev_ctx = false;
cryp_restore_device_context(device_data,
&device_data->current_ctx->dev_ctx);
}
spin_unlock(&device_data->ctx_lock);
}
out:
spin_unlock(&device_data->power_state_spinlock);
return ret;
}
static int hw_crypt_noxts(struct cryp_ctx *ctx,
struct cryp_device_data *device_data)
{
int ret = 0;
const u8 *indata = ctx->indata;
u8 *outdata = ctx->outdata;
u32 datalen = ctx->datalen;
u32 outlen = datalen;
pr_debug(DEV_DBG_NAME " [%s]", __func__);
ctx->outlen = ctx->datalen;
if (unlikely(!IS_ALIGNED((u32)indata, 4))) {
pr_debug(DEV_DBG_NAME " [%s]: Data isn't aligned! Addr: "
"0x%08x", __func__, (u32)indata);
return -EINVAL;
}
ret = cryp_setup_context(ctx, device_data);
if (ret)
goto out;
if (cryp_mode == CRYP_MODE_INTERRUPT) {
cryp_enable_irq_src(device_data, CRYP_IRQ_SRC_INPUT_FIFO |
CRYP_IRQ_SRC_OUTPUT_FIFO);
/*
* ctx->outlen is decremented in the cryp_interrupt_handler
* function. We had to add cpu_relax() (barrier) to make sure
* that gcc didn't optimze away this variable.
*/
while (ctx->outlen > 0)
cpu_relax();
} else if (cryp_mode == CRYP_MODE_POLLING ||
cryp_mode == CRYP_MODE_DMA) {
/*
* The reason for having DMA in this if case is that if we are
* running cryp_mode = 2, then we separate DMA routines for
* handling cipher/plaintext > blocksize, except when
* running the normal CRYPTO_ALG_TYPE_CIPHER, then we still use
* the polling mode. Overhead of doing DMA setup eats up the
* benefits using it.
*/
cryp_polling_mode(ctx, device_data);
} else {
dev_err(ctx->device->dev, "[%s]: Invalid operation mode!",
__func__);
ret = -EPERM;
goto out;
}
cryp_save_device_context(device_data, &ctx->dev_ctx, cryp_mode);
ctx->updated = 1;
out:
ctx->indata = indata;
ctx->outdata = outdata;
ctx->datalen = datalen;
ctx->outlen = outlen;
return ret;
}
static int get_nents(struct scatterlist *sg, int nbytes)
{
int nents = 0;
while (nbytes > 0) {
nbytes -= sg->length;
sg = scatterwalk_sg_next(sg);
nents++;
}
return nents;
}
static int ablk_dma_crypt(struct ablkcipher_request *areq)
{
struct crypto_ablkcipher *cipher = crypto_ablkcipher_reqtfm(areq);
struct cryp_ctx *ctx = crypto_ablkcipher_ctx(cipher);
struct cryp_device_data *device_data;
int bytes_written = 0;
int bytes_read = 0;
int ret;
pr_debug(DEV_DBG_NAME " [%s]", __func__);
ctx->datalen = areq->nbytes;
ctx->outlen = areq->nbytes;
ret = cryp_get_device_data(ctx, &device_data);
if (ret)
return ret;
ret = cryp_setup_context(ctx, device_data);
if (ret)
goto out;
/* We have the device now, so store the nents in the dma struct. */
ctx->device->dma.nents_src = get_nents(areq->src, ctx->datalen);
ctx->device->dma.nents_dst = get_nents(areq->dst, ctx->outlen);
/* Enable DMA in- and output. */
cryp_configure_for_dma(device_data, CRYP_DMA_ENABLE_BOTH_DIRECTIONS);
bytes_written = cryp_dma_write(ctx, areq->src, ctx->datalen);
bytes_read = cryp_dma_read(ctx, areq->dst, bytes_written);
wait_for_completion(&ctx->device->dma.cryp_dma_complete);
cryp_dma_done(ctx);
cryp_save_device_context(device_data, &ctx->dev_ctx, cryp_mode);
ctx->updated = 1;
out:
spin_lock(&device_data->ctx_lock);
device_data->current_ctx = NULL;
ctx->device = NULL;
spin_unlock(&device_data->ctx_lock);
/*
* The down_interruptible part for this semaphore is called in
* cryp_get_device_data.
*/
up(&driver_data.device_allocation);
if (unlikely(bytes_written != bytes_read))
return -EPERM;
return 0;
}
static int ablk_crypt(struct ablkcipher_request *areq)
{
struct ablkcipher_walk walk;
struct crypto_ablkcipher *cipher = crypto_ablkcipher_reqtfm(areq);
struct cryp_ctx *ctx = crypto_ablkcipher_ctx(cipher);
struct cryp_device_data *device_data;
unsigned long src_paddr;
unsigned long dst_paddr;
int ret;
int nbytes;
pr_debug(DEV_DBG_NAME " [%s]", __func__);
ret = cryp_get_device_data(ctx, &device_data);
if (ret)
goto out;
ablkcipher_walk_init(&walk, areq->dst, areq->src, areq->nbytes);
ret = ablkcipher_walk_phys(areq, &walk);
if (ret) {
pr_err(DEV_DBG_NAME "[%s]: ablkcipher_walk_phys() failed!",
__func__);
goto out;
}
while ((nbytes = walk.nbytes) > 0) {
ctx->iv = walk.iv;
src_paddr = (page_to_phys(walk.src.page) + walk.src.offset);
ctx->indata = phys_to_virt(src_paddr);
dst_paddr = (page_to_phys(walk.dst.page) + walk.dst.offset);
ctx->outdata = phys_to_virt(dst_paddr);
ctx->datalen = nbytes - (nbytes % ctx->blocksize);
ret = hw_crypt_noxts(ctx, device_data);
if (ret)
goto out;
nbytes -= ctx->datalen;
ret = ablkcipher_walk_done(areq, &walk, nbytes);
if (ret)
goto out;
}
ablkcipher_walk_complete(&walk);
out:
/* Release the device */
spin_lock(&device_data->ctx_lock);
device_data->current_ctx = NULL;
ctx->device = NULL;
spin_unlock(&device_data->ctx_lock);
/*
* The down_interruptible part for this semaphore is called in
* cryp_get_device_data.
*/
up(&driver_data.device_allocation);
return ret;
}
static int aes_ablkcipher_setkey(struct crypto_ablkcipher *cipher,
const u8 *key, unsigned int keylen)
{
struct cryp_ctx *ctx = crypto_ablkcipher_ctx(cipher);
u32 *flags = &cipher->base.crt_flags;
pr_debug(DEV_DBG_NAME " [%s]", __func__);
switch (keylen) {
case AES_KEYSIZE_128:
ctx->config.keysize = CRYP_KEY_SIZE_128;
break;
case AES_KEYSIZE_192:
ctx->config.keysize = CRYP_KEY_SIZE_192;
break;
case AES_KEYSIZE_256:
ctx->config.keysize = CRYP_KEY_SIZE_256;
break;
default:
pr_err(DEV_DBG_NAME "[%s]: Unknown keylen!", __func__);
*flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
return -EINVAL;
}
memcpy(ctx->key, key, keylen);
ctx->keylen = keylen;
ctx->updated = 0;
return 0;
}
static int des_ablkcipher_setkey(struct crypto_ablkcipher *cipher,
const u8 *key, unsigned int keylen)
{
struct cryp_ctx *ctx = crypto_ablkcipher_ctx(cipher);
u32 *flags = &cipher->base.crt_flags;
u32 tmp[DES_EXPKEY_WORDS];
int ret;
pr_debug(DEV_DBG_NAME " [%s]", __func__);
if (keylen != DES_KEY_SIZE) {
*flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
pr_debug(DEV_DBG_NAME " [%s]: CRYPTO_TFM_RES_BAD_KEY_LEN",
__func__);
return -EINVAL;
}
ret = des_ekey(tmp, key);
if (unlikely(ret == 0) && (*flags & CRYPTO_TFM_REQ_WEAK_KEY)) {
*flags |= CRYPTO_TFM_RES_WEAK_KEY;
pr_debug(DEV_DBG_NAME " [%s]: CRYPTO_TFM_REQ_WEAK_KEY",
__func__);
return -EINVAL;
}
memcpy(ctx->key, key, keylen);
ctx->keylen = keylen;
ctx->updated = 0;
return 0;
}
static int des3_ablkcipher_setkey(struct crypto_ablkcipher *cipher,
const u8 *key, unsigned int keylen)
{
struct cryp_ctx *ctx = crypto_ablkcipher_ctx(cipher);
u32 *flags = &cipher->base.crt_flags;
const u32 *K = (const u32 *)key;
u32 tmp[DES3_EDE_EXPKEY_WORDS];
int i, ret;
pr_debug(DEV_DBG_NAME " [%s]", __func__);
if (keylen != DES3_EDE_KEY_SIZE) {
*flags |= CRYPTO_TFM_RES_BAD_KEY_LEN;
pr_debug(DEV_DBG_NAME " [%s]: CRYPTO_TFM_RES_BAD_KEY_LEN",
__func__);
return -EINVAL;
}
/* Checking key interdependency for weak key detection. */
if (unlikely(!((K[0] ^ K[2]) | (K[1] ^ K[3])) ||
!((K[2] ^ K[4]) | (K[3] ^ K[5]))) &&
(*flags & CRYPTO_TFM_REQ_WEAK_KEY)) {
*flags |= CRYPTO_TFM_RES_WEAK_KEY;
pr_debug(DEV_DBG_NAME " [%s]: CRYPTO_TFM_REQ_WEAK_KEY",
__func__);
return -EINVAL;
}
for (i = 0; i < 3; i++) {
ret = des_ekey(tmp, key + i*DES_KEY_SIZE);
if (unlikely(ret == 0) && (*flags & CRYPTO_TFM_REQ_WEAK_KEY)) {
*flags |= CRYPTO_TFM_RES_WEAK_KEY;
pr_debug(DEV_DBG_NAME " [%s]: "
"CRYPTO_TFM_REQ_WEAK_KEY", __func__);
return -EINVAL;
}
}
memcpy(ctx->key, key, keylen);
ctx->keylen = keylen;
ctx->updated = 0;
return 0;
}
static int cryp_blk_encrypt(struct ablkcipher_request *areq)
{
struct crypto_ablkcipher *cipher = crypto_ablkcipher_reqtfm(areq);
struct cryp_ctx *ctx = crypto_ablkcipher_ctx(cipher);
pr_debug(DEV_DBG_NAME " [%s]", __func__);
ctx->config.algodir = CRYP_ALGORITHM_ENCRYPT;
/*
* DMA does not work for DES due to a hw bug */
if (cryp_mode == CRYP_MODE_DMA && mode_is_aes(ctx->config.algomode))
return ablk_dma_crypt(areq);
/* For everything except DMA, we run the non DMA version. */
return ablk_crypt(areq);
}
static int cryp_blk_decrypt(struct ablkcipher_request *areq)
{
struct crypto_ablkcipher *cipher = crypto_ablkcipher_reqtfm(areq);
struct cryp_ctx *ctx = crypto_ablkcipher_ctx(cipher);
pr_debug(DEV_DBG_NAME " [%s]", __func__);
ctx->config.algodir = CRYP_ALGORITHM_DECRYPT;
/* DMA does not work for DES due to a hw bug */
if (cryp_mode == CRYP_MODE_DMA && mode_is_aes(ctx->config.algomode))
return ablk_dma_crypt(areq);
/* For everything except DMA, we run the non DMA version. */
return ablk_crypt(areq);
}
struct cryp_algo_template {
enum cryp_algo_mode algomode;
struct crypto_alg crypto;
};
static int cryp_cra_init(struct crypto_tfm *tfm)
{
struct cryp_ctx *ctx = crypto_tfm_ctx(tfm);
struct crypto_alg *alg = tfm->__crt_alg;
struct cryp_algo_template *cryp_alg = container_of(alg,
struct cryp_algo_template,
crypto);
ctx->config.algomode = cryp_alg->algomode;
ctx->blocksize = crypto_tfm_alg_blocksize(tfm);
return 0;
}
static struct cryp_algo_template cryp_algs[] = {
{
.algomode = CRYP_ALGO_AES_ECB,
.crypto = {
.cra_name = "aes",
.cra_driver_name = "aes-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = aes_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt
}
}
}
},
{
.algomode = CRYP_ALGO_AES_ECB,
.crypto = {
.cra_name = "ecb(aes)",
.cra_driver_name = "ecb-aes-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = aes_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt,
}
}
}
},
{
.algomode = CRYP_ALGO_AES_CBC,
.crypto = {
.cra_name = "cbc(aes)",
.cra_driver_name = "cbc-aes-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = aes_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt,
.ivsize = AES_BLOCK_SIZE,
}
}
}
},
{
.algomode = CRYP_ALGO_AES_CTR,
.crypto = {
.cra_name = "ctr(aes)",
.cra_driver_name = "ctr-aes-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.setkey = aes_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt,
.ivsize = AES_BLOCK_SIZE,
}
}
}
},
{
.algomode = CRYP_ALGO_DES_ECB,
.crypto = {
.cra_name = "des",
.cra_driver_name = "des-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = DES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = DES_KEY_SIZE,
.max_keysize = DES_KEY_SIZE,
.setkey = des_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt
}
}
}
},
{
.algomode = CRYP_ALGO_TDES_ECB,
.crypto = {
.cra_name = "des3_ede",
.cra_driver_name = "des3_ede-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = DES3_EDE_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = DES3_EDE_KEY_SIZE,
.max_keysize = DES3_EDE_KEY_SIZE,
.setkey = des_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt
}
}
}
},
{
.algomode = CRYP_ALGO_DES_ECB,
.crypto = {
.cra_name = "ecb(des)",
.cra_driver_name = "ecb-des-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = DES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = DES_KEY_SIZE,
.max_keysize = DES_KEY_SIZE,
.setkey = des_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt,
}
}
}
},
{
.algomode = CRYP_ALGO_TDES_ECB,
.crypto = {
.cra_name = "ecb(des3_ede)",
.cra_driver_name = "ecb-des3_ede-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = DES3_EDE_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = DES3_EDE_KEY_SIZE,
.max_keysize = DES3_EDE_KEY_SIZE,
.setkey = des3_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt,
}
}
}
},
{
.algomode = CRYP_ALGO_DES_CBC,
.crypto = {
.cra_name = "cbc(des)",
.cra_driver_name = "cbc-des-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = DES_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = DES_KEY_SIZE,
.max_keysize = DES_KEY_SIZE,
.setkey = des_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt,
}
}
}
},
{
.algomode = CRYP_ALGO_TDES_CBC,
.crypto = {
.cra_name = "cbc(des3_ede)",
.cra_driver_name = "cbc-des3_ede-ux500",
.cra_priority = 300,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER |
CRYPTO_ALG_ASYNC,
.cra_blocksize = DES3_EDE_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct cryp_ctx),
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = cryp_cra_init,
.cra_module = THIS_MODULE,
.cra_u = {
.ablkcipher = {
.min_keysize = DES3_EDE_KEY_SIZE,
.max_keysize = DES3_EDE_KEY_SIZE,
.setkey = des3_ablkcipher_setkey,
.encrypt = cryp_blk_encrypt,
.decrypt = cryp_blk_decrypt,
.ivsize = DES3_EDE_BLOCK_SIZE,
}
}
}
}
};
/**
* cryp_algs_register_all -
*/
static int cryp_algs_register_all(void)
{
int ret;
int i;
int count;
pr_debug("[%s]", __func__);
for (i = 0; i < ARRAY_SIZE(cryp_algs); i++) {
ret = crypto_register_alg(&cryp_algs[i].crypto);
if (ret) {
count = i;
pr_err("[%s] alg registration failed",
cryp_algs[i].crypto.cra_driver_name);
goto unreg;
}
}
return 0;
unreg:
for (i = 0; i < count; i++)
crypto_unregister_alg(&cryp_algs[i].crypto);
return ret;
}
/**
* cryp_algs_unregister_all -
*/
static void cryp_algs_unregister_all(void)
{
int i;
pr_debug(DEV_DBG_NAME " [%s]", __func__);
for (i = 0; i < ARRAY_SIZE(cryp_algs); i++)
crypto_unregister_alg(&cryp_algs[i].crypto);
}
static int ux500_cryp_probe(struct platform_device *pdev)
{
int ret;
int cryp_error = 0;
struct resource *res = NULL;
struct resource *res_irq = NULL;
struct cryp_device_data *device_data;
struct cryp_protection_config prot = {
.privilege_access = CRYP_STATE_ENABLE
};
struct device *dev = &pdev->dev;
dev_dbg(dev, "[%s]", __func__);
device_data = kzalloc(sizeof(struct cryp_device_data), GFP_ATOMIC);
if (!device_data) {
dev_err(dev, "[%s]: kzalloc() failed!", __func__);
ret = -ENOMEM;
goto out;
}
device_data->dev = dev;
device_data->current_ctx = NULL;
/* Grab the DMA configuration from platform data. */
mem_to_engine = &((struct cryp_platform_data *)
dev->platform_data)->mem_to_engine;
engine_to_mem = &((struct cryp_platform_data *)
dev->platform_data)->engine_to_mem;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(dev, "[%s]: platform_get_resource() failed",
__func__);
ret = -ENODEV;
goto out_kfree;
}
res = request_mem_region(res->start, resource_size(res), pdev->name);
if (res == NULL) {
dev_err(dev, "[%s]: request_mem_region() failed",
__func__);
ret = -EBUSY;
goto out_kfree;
}
device_data->base = ioremap(res->start, resource_size(res));
if (!device_data->base) {
dev_err(dev, "[%s]: ioremap failed!", __func__);
ret = -ENOMEM;
goto out_free_mem;
}
spin_lock_init(&device_data->ctx_lock);
spin_lock_init(&device_data->power_state_spinlock);
/* Enable power for CRYP hardware block */
device_data->pwr_regulator = regulator_get(&pdev->dev, "v-ape");
if (IS_ERR(device_data->pwr_regulator)) {
dev_err(dev, "[%s]: could not get cryp regulator", __func__);
ret = PTR_ERR(device_data->pwr_regulator);
device_data->pwr_regulator = NULL;
goto out_unmap;
}
/* Enable the clk for CRYP hardware block */
device_data->clk = clk_get(&pdev->dev, NULL);
if (IS_ERR(device_data->clk)) {
dev_err(dev, "[%s]: clk_get() failed!", __func__);
ret = PTR_ERR(device_data->clk);
goto out_regulator;
}
/* Enable device power (and clock) */
ret = cryp_enable_power(device_data->dev, device_data, false);
if (ret) {
dev_err(dev, "[%s]: cryp_enable_power() failed!", __func__);
goto out_clk;
}
cryp_error = cryp_check(device_data);
if (cryp_error != 0) {
dev_err(dev, "[%s]: cryp_init() failed!", __func__);
ret = -EINVAL;
goto out_power;
}
cryp_error = cryp_configure_protection(device_data, &prot);
if (cryp_error != 0) {
dev_err(dev, "[%s]: cryp_configure_protection() failed!",
__func__);
ret = -EINVAL;
goto out_power;
}
res_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res_irq) {
dev_err(dev, "[%s]: IORESOURCE_IRQ unavailable",
__func__);
ret = -ENODEV;
goto out_power;
}
ret = request_irq(res_irq->start,
cryp_interrupt_handler,
0,
"cryp1",
device_data);
if (ret) {
dev_err(dev, "[%s]: Unable to request IRQ", __func__);
goto out_power;
}
if (cryp_mode == CRYP_MODE_DMA)
cryp_dma_setup_channel(device_data, dev);
platform_set_drvdata(pdev, device_data);
/* Put the new device into the device list... */
klist_add_tail(&device_data->list_node, &driver_data.device_list);
/* ... and signal that a new device is available. */
up(&driver_data.device_allocation);
atomic_set(&session_id, 1);
ret = cryp_algs_register_all();
if (ret) {
dev_err(dev, "[%s]: cryp_algs_register_all() failed!",
__func__);
goto out_power;
}
return 0;
out_power:
cryp_disable_power(device_data->dev, device_data, false);
out_clk:
clk_put(device_data->clk);
out_regulator:
regulator_put(device_data->pwr_regulator);
out_unmap:
iounmap(device_data->base);
out_free_mem:
release_mem_region(res->start, resource_size(res));
out_kfree:
kfree(device_data);
out:
return ret;
}
static int ux500_cryp_remove(struct platform_device *pdev)
{
struct resource *res = NULL;
struct resource *res_irq = NULL;
struct cryp_device_data *device_data;
dev_dbg(&pdev->dev, "[%s]", __func__);
device_data = platform_get_drvdata(pdev);
if (!device_data) {
dev_err(&pdev->dev, "[%s]: platform_get_drvdata() failed!",
__func__);
return -ENOMEM;
}
/* Try to decrease the number of available devices. */
if (down_trylock(&driver_data.device_allocation))
return -EBUSY;
/* Check that the device is free */
spin_lock(&device_data->ctx_lock);
/* current_ctx allocates a device, NULL = unallocated */
if (device_data->current_ctx) {
/* The device is busy */
spin_unlock(&device_data->ctx_lock);
/* Return the device to the pool. */
up(&driver_data.device_allocation);
return -EBUSY;
}
spin_unlock(&device_data->ctx_lock);
/* Remove the device from the list */
if (klist_node_attached(&device_data->list_node))
klist_remove(&device_data->list_node);
/* If this was the last device, remove the services */
if (list_empty(&driver_data.device_list.k_list))
cryp_algs_unregister_all();
res_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res_irq)
dev_err(&pdev->dev, "[%s]: IORESOURCE_IRQ, unavailable",
__func__);
else {
disable_irq(res_irq->start);
free_irq(res_irq->start, device_data);
}
if (cryp_disable_power(&pdev->dev, device_data, false))
dev_err(&pdev->dev, "[%s]: cryp_disable_power() failed",
__func__);
clk_put(device_data->clk);
regulator_put(device_data->pwr_regulator);
iounmap(device_data->base);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res)
release_mem_region(res->start, res->end - res->start + 1);
kfree(device_data);
return 0;
}
static void ux500_cryp_shutdown(struct platform_device *pdev)
{
struct resource *res_irq = NULL;
struct cryp_device_data *device_data;
dev_dbg(&pdev->dev, "[%s]", __func__);
device_data = platform_get_drvdata(pdev);
if (!device_data) {
dev_err(&pdev->dev, "[%s]: platform_get_drvdata() failed!",
__func__);
return;
}
/* Check that the device is free */
spin_lock(&device_data->ctx_lock);
/* current_ctx allocates a device, NULL = unallocated */
if (!device_data->current_ctx) {
if (down_trylock(&driver_data.device_allocation))
dev_dbg(&pdev->dev, "[%s]: Cryp still in use!"
"Shutting down anyway...", __func__);
/**
* (Allocate the device)
* Need to set this to non-null (dummy) value,
* to avoid usage if context switching.
*/
device_data->current_ctx++;
}
spin_unlock(&device_data->ctx_lock);
/* Remove the device from the list */
if (klist_node_attached(&device_data->list_node))
klist_remove(&device_data->list_node);
/* If this was the last device, remove the services */
if (list_empty(&driver_data.device_list.k_list))
cryp_algs_unregister_all();
res_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res_irq)
dev_err(&pdev->dev, "[%s]: IORESOURCE_IRQ, unavailable",
__func__);
else {
disable_irq(res_irq->start);
free_irq(res_irq->start, device_data);
}
if (cryp_disable_power(&pdev->dev, device_data, false))
dev_err(&pdev->dev, "[%s]: cryp_disable_power() failed",
__func__);
}
static int ux500_cryp_suspend(struct device *dev)
{
int ret;
struct platform_device *pdev = to_platform_device(dev);
struct cryp_device_data *device_data;
struct resource *res_irq;
struct cryp_ctx *temp_ctx = NULL;
dev_dbg(dev, "[%s]", __func__);
/* Handle state? */
device_data = platform_get_drvdata(pdev);
if (!device_data) {
dev_err(dev, "[%s]: platform_get_drvdata() failed!", __func__);
return -ENOMEM;
}
res_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res_irq)
dev_err(dev, "[%s]: IORESOURCE_IRQ, unavailable", __func__);
else
disable_irq(res_irq->start);
spin_lock(&device_data->ctx_lock);
if (!device_data->current_ctx)
device_data->current_ctx++;
spin_unlock(&device_data->ctx_lock);
if (device_data->current_ctx == ++temp_ctx) {
if (down_interruptible(&driver_data.device_allocation))
dev_dbg(dev, "[%s]: down_interruptible() failed",
__func__);
ret = cryp_disable_power(dev, device_data, false);
} else
ret = cryp_disable_power(dev, device_data, true);
if (ret)
dev_err(dev, "[%s]: cryp_disable_power()", __func__);
return ret;
}
static int ux500_cryp_resume(struct device *dev)
{
int ret = 0;
struct platform_device *pdev = to_platform_device(dev);
struct cryp_device_data *device_data;
struct resource *res_irq;
struct cryp_ctx *temp_ctx = NULL;
dev_dbg(dev, "[%s]", __func__);
device_data = platform_get_drvdata(pdev);
if (!device_data) {
dev_err(dev, "[%s]: platform_get_drvdata() failed!", __func__);
return -ENOMEM;
}
spin_lock(&device_data->ctx_lock);
if (device_data->current_ctx == ++temp_ctx)
device_data->current_ctx = NULL;
spin_unlock(&device_data->ctx_lock);
if (!device_data->current_ctx)
up(&driver_data.device_allocation);
else
ret = cryp_enable_power(dev, device_data, true);
if (ret)
dev_err(dev, "[%s]: cryp_enable_power() failed!", __func__);
else {
res_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (res_irq)
enable_irq(res_irq->start);
}
return ret;
}
static SIMPLE_DEV_PM_OPS(ux500_cryp_pm, ux500_cryp_suspend, ux500_cryp_resume);
static struct platform_driver cryp_driver = {
.probe = ux500_cryp_probe,
.remove = ux500_cryp_remove,
.shutdown = ux500_cryp_shutdown,
.driver = {
.owner = THIS_MODULE,
.name = "cryp1",
.pm = &ux500_cryp_pm,
}
};
static int __init ux500_cryp_mod_init(void)
{
pr_debug("[%s] is called!", __func__);
klist_init(&driver_data.device_list, NULL, NULL);
/* Initialize the semaphore to 0 devices (locked state) */
sema_init(&driver_data.device_allocation, 0);
return platform_driver_register(&cryp_driver);
}
static void __exit ux500_cryp_mod_fini(void)
{
pr_debug("[%s] is called!", __func__);
platform_driver_unregister(&cryp_driver);
return;
}
module_init(ux500_cryp_mod_init);
module_exit(ux500_cryp_mod_fini);
module_param(cryp_mode, int, 0);
MODULE_DESCRIPTION("Driver for ST-Ericsson UX500 CRYP crypto engine.");
MODULE_ALIAS("aes-all");
MODULE_ALIAS("des-all");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Angor00/linux-aura-hd-android-2.6.35.3 | drivers/media/video/gspca/stv06xx/stv06xx_hdcs.c | 1463 | 13989 | /*
* Copyright (c) 2001 Jean-Fredric Clere, Nikolas Zimmermann, Georg Acher
* Mark Cave-Ayland, Carlo E Prelz, Dick Streefland
* Copyright (c) 2002, 2003 Tuukka Toivonen
* Copyright (c) 2008 Erik Andrén
* Copyright (c) 2008 Chia-I Wu
*
* 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
*
* P/N 861037: Sensor HDCS1000 ASIC STV0600
* P/N 861050-0010: Sensor HDCS1000 ASIC STV0600
* P/N 861050-0020: Sensor Photobit PB100 ASIC STV0600-1 - QuickCam Express
* P/N 861055: Sensor ST VV6410 ASIC STV0610 - LEGO cam
* P/N 861075-0040: Sensor HDCS1000 ASIC
* P/N 961179-0700: Sensor ST VV6410 ASIC STV0602 - Dexxa WebCam USB
* P/N 861040-0000: Sensor ST VV6410 ASIC STV0610 - QuickCam Web
*/
#include "stv06xx_hdcs.h"
static const struct ctrl hdcs1x00_ctrl[] = {
{
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "exposure",
.minimum = 0x00,
.maximum = 0xff,
.step = 0x1,
.default_value = HDCS_DEFAULT_EXPOSURE,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = hdcs_set_exposure,
.get = hdcs_get_exposure
}, {
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "gain",
.minimum = 0x00,
.maximum = 0xff,
.step = 0x1,
.default_value = HDCS_DEFAULT_GAIN,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = hdcs_set_gain,
.get = hdcs_get_gain
}
};
static struct v4l2_pix_format hdcs1x00_mode[] = {
{
HDCS_1X00_DEF_WIDTH,
HDCS_1X00_DEF_HEIGHT,
V4L2_PIX_FMT_SGRBG8,
V4L2_FIELD_NONE,
.sizeimage =
HDCS_1X00_DEF_WIDTH * HDCS_1X00_DEF_HEIGHT,
.bytesperline = HDCS_1X00_DEF_WIDTH,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 1
}
};
static const struct ctrl hdcs1020_ctrl[] = {
{
{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "exposure",
.minimum = 0x00,
.maximum = 0xffff,
.step = 0x1,
.default_value = HDCS_DEFAULT_EXPOSURE,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = hdcs_set_exposure,
.get = hdcs_get_exposure
}, {
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "gain",
.minimum = 0x00,
.maximum = 0xff,
.step = 0x1,
.default_value = HDCS_DEFAULT_GAIN,
.flags = V4L2_CTRL_FLAG_SLIDER
},
.set = hdcs_set_gain,
.get = hdcs_get_gain
}
};
static struct v4l2_pix_format hdcs1020_mode[] = {
{
HDCS_1020_DEF_WIDTH,
HDCS_1020_DEF_HEIGHT,
V4L2_PIX_FMT_SGRBG8,
V4L2_FIELD_NONE,
.sizeimage =
HDCS_1020_DEF_WIDTH * HDCS_1020_DEF_HEIGHT,
.bytesperline = HDCS_1020_DEF_WIDTH,
.colorspace = V4L2_COLORSPACE_SRGB,
.priv = 1
}
};
enum hdcs_power_state {
HDCS_STATE_SLEEP,
HDCS_STATE_IDLE,
HDCS_STATE_RUN
};
/* no lock? */
struct hdcs {
enum hdcs_power_state state;
int w, h;
/* visible area of the sensor array */
struct {
int left, top;
int width, height;
int border;
} array;
struct {
/* Column timing overhead */
u8 cto;
/* Column processing overhead */
u8 cpo;
/* Row sample period constant */
u16 rs;
/* Exposure reset duration */
u16 er;
} exp;
int psmp;
u8 exp_cache, gain_cache;
};
static int hdcs_reg_write_seq(struct sd *sd, u8 reg, u8 *vals, u8 len)
{
u8 regs[I2C_MAX_BYTES * 2];
int i;
if (unlikely((len <= 0) || (len >= I2C_MAX_BYTES) ||
(reg + len > 0xff)))
return -EINVAL;
for (i = 0; i < len; i++) {
regs[2 * i] = reg;
regs[2 * i + 1] = vals[i];
/* All addresses are shifted left one bit as bit 0 toggles r/w */
reg += 2;
}
return stv06xx_write_sensor_bytes(sd, regs, len);
}
static int hdcs_set_state(struct sd *sd, enum hdcs_power_state state)
{
struct hdcs *hdcs = sd->sensor_priv;
u8 val;
int ret;
if (hdcs->state == state)
return 0;
/* we need to go idle before running or sleeping */
if (hdcs->state != HDCS_STATE_IDLE) {
ret = stv06xx_write_sensor(sd, HDCS_REG_CONTROL(sd), 0);
if (ret)
return ret;
}
hdcs->state = HDCS_STATE_IDLE;
if (state == HDCS_STATE_IDLE)
return 0;
switch (state) {
case HDCS_STATE_SLEEP:
val = HDCS_SLEEP_MODE;
break;
case HDCS_STATE_RUN:
val = HDCS_RUN_ENABLE;
break;
default:
return -EINVAL;
}
ret = stv06xx_write_sensor(sd, HDCS_REG_CONTROL(sd), val);
/* Update the state if the write succeeded */
if (!ret)
hdcs->state = state;
return ret;
}
static int hdcs_reset(struct sd *sd)
{
struct hdcs *hdcs = sd->sensor_priv;
int err;
err = stv06xx_write_sensor(sd, HDCS_REG_CONTROL(sd), 1);
if (err < 0)
return err;
err = stv06xx_write_sensor(sd, HDCS_REG_CONTROL(sd), 0);
if (err < 0)
hdcs->state = HDCS_STATE_IDLE;
return err;
}
static int hdcs_get_exposure(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
struct hdcs *hdcs = sd->sensor_priv;
*val = hdcs->exp_cache;
return 0;
}
static int hdcs_set_exposure(struct gspca_dev *gspca_dev, __s32 val)
{
struct sd *sd = (struct sd *) gspca_dev;
struct hdcs *hdcs = sd->sensor_priv;
int rowexp, srowexp;
int max_srowexp;
/* Column time period */
int ct;
/* Column processing period */
int cp;
/* Row processing period */
int rp;
/* Minimum number of column timing periods
within the column processing period */
int mnct;
int cycles, err;
u8 exp[14];
val &= 0xff;
hdcs->exp_cache = val;
cycles = val * HDCS_CLK_FREQ_MHZ * 257;
ct = hdcs->exp.cto + hdcs->psmp + (HDCS_ADC_START_SIG_DUR + 2);
cp = hdcs->exp.cto + (hdcs->w * ct / 2);
/* the cycles one row takes */
rp = hdcs->exp.rs + cp;
rowexp = cycles / rp;
/* the remaining cycles */
cycles -= rowexp * rp;
/* calculate sub-row exposure */
if (IS_1020(sd)) {
/* see HDCS-1020 datasheet 3.5.6.4, p. 63 */
srowexp = hdcs->w - (cycles + hdcs->exp.er + 13) / ct;
mnct = (hdcs->exp.er + 12 + ct - 1) / ct;
max_srowexp = hdcs->w - mnct;
} else {
/* see HDCS-1000 datasheet 3.4.5.5, p. 61 */
srowexp = cp - hdcs->exp.er - 6 - cycles;
mnct = (hdcs->exp.er + 5 + ct - 1) / ct;
max_srowexp = cp - mnct * ct - 1;
}
if (srowexp < 0)
srowexp = 0;
else if (srowexp > max_srowexp)
srowexp = max_srowexp;
if (IS_1020(sd)) {
exp[0] = HDCS20_CONTROL;
exp[1] = 0x00; /* Stop streaming */
exp[2] = HDCS_ROWEXPL;
exp[3] = rowexp & 0xff;
exp[4] = HDCS_ROWEXPH;
exp[5] = rowexp >> 8;
exp[6] = HDCS20_SROWEXP;
exp[7] = (srowexp >> 2) & 0xff;
exp[8] = HDCS20_ERROR;
exp[9] = 0x10; /* Clear exposure error flag*/
exp[10] = HDCS20_CONTROL;
exp[11] = 0x04; /* Restart streaming */
err = stv06xx_write_sensor_bytes(sd, exp, 6);
} else {
exp[0] = HDCS00_CONTROL;
exp[1] = 0x00; /* Stop streaming */
exp[2] = HDCS_ROWEXPL;
exp[3] = rowexp & 0xff;
exp[4] = HDCS_ROWEXPH;
exp[5] = rowexp >> 8;
exp[6] = HDCS00_SROWEXPL;
exp[7] = srowexp & 0xff;
exp[8] = HDCS00_SROWEXPH;
exp[9] = srowexp >> 8;
exp[10] = HDCS_STATUS;
exp[11] = 0x10; /* Clear exposure error flag*/
exp[12] = HDCS00_CONTROL;
exp[13] = 0x04; /* Restart streaming */
err = stv06xx_write_sensor_bytes(sd, exp, 7);
if (err < 0)
return err;
}
PDEBUG(D_V4L2, "Writing exposure %d, rowexp %d, srowexp %d",
val, rowexp, srowexp);
return err;
}
static int hdcs_set_gains(struct sd *sd, u8 g)
{
struct hdcs *hdcs = sd->sensor_priv;
int err;
u8 gains[4];
hdcs->gain_cache = g;
/* the voltage gain Av = (1 + 19 * val / 127) * (1 + bit7) */
if (g > 127)
g = 0x80 | (g / 2);
gains[0] = g;
gains[1] = g;
gains[2] = g;
gains[3] = g;
err = hdcs_reg_write_seq(sd, HDCS_ERECPGA, gains, 4);
return err;
}
static int hdcs_get_gain(struct gspca_dev *gspca_dev, __s32 *val)
{
struct sd *sd = (struct sd *) gspca_dev;
struct hdcs *hdcs = sd->sensor_priv;
*val = hdcs->gain_cache;
return 0;
}
static int hdcs_set_gain(struct gspca_dev *gspca_dev, __s32 val)
{
PDEBUG(D_V4L2, "Writing gain %d", val);
return hdcs_set_gains((struct sd *) gspca_dev,
val & 0xff);
}
static int hdcs_set_size(struct sd *sd,
unsigned int width, unsigned int height)
{
struct hdcs *hdcs = sd->sensor_priv;
u8 win[4];
unsigned int x, y;
int err;
/* must be multiple of 4 */
width = (width + 3) & ~0x3;
height = (height + 3) & ~0x3;
if (width > hdcs->array.width)
width = hdcs->array.width;
if (IS_1020(sd)) {
/* the borders are also invalid */
if (height + 2 * hdcs->array.border + HDCS_1020_BOTTOM_Y_SKIP
> hdcs->array.height)
height = hdcs->array.height - 2 * hdcs->array.border -
HDCS_1020_BOTTOM_Y_SKIP;
y = (hdcs->array.height - HDCS_1020_BOTTOM_Y_SKIP - height) / 2
+ hdcs->array.top;
} else {
if (height > hdcs->array.height)
height = hdcs->array.height;
y = hdcs->array.top + (hdcs->array.height - height) / 2;
}
x = hdcs->array.left + (hdcs->array.width - width) / 2;
win[0] = y / 4;
win[1] = x / 4;
win[2] = (y + height) / 4 - 1;
win[3] = (x + width) / 4 - 1;
err = hdcs_reg_write_seq(sd, HDCS_FWROW, win, 4);
if (err < 0)
return err;
/* Update the current width and height */
hdcs->w = width;
hdcs->h = height;
return err;
}
static int hdcs_probe_1x00(struct sd *sd)
{
struct hdcs *hdcs;
u16 sensor;
int ret;
ret = stv06xx_read_sensor(sd, HDCS_IDENT, &sensor);
if (ret < 0 || sensor != 0x08)
return -ENODEV;
info("HDCS-1000/1100 sensor detected");
sd->gspca_dev.cam.cam_mode = hdcs1x00_mode;
sd->gspca_dev.cam.nmodes = ARRAY_SIZE(hdcs1x00_mode);
sd->desc.ctrls = hdcs1x00_ctrl;
sd->desc.nctrls = ARRAY_SIZE(hdcs1x00_ctrl);
hdcs = kmalloc(sizeof(struct hdcs), GFP_KERNEL);
if (!hdcs)
return -ENOMEM;
hdcs->array.left = 8;
hdcs->array.top = 8;
hdcs->array.width = HDCS_1X00_DEF_WIDTH;
hdcs->array.height = HDCS_1X00_DEF_HEIGHT;
hdcs->array.border = 4;
hdcs->exp.cto = 4;
hdcs->exp.cpo = 2;
hdcs->exp.rs = 186;
hdcs->exp.er = 100;
/*
* Frame rate on HDCS-1000 with STV600 depends on PSMP:
* 4 = doesn't work at all
* 5 = 7.8 fps,
* 6 = 6.9 fps,
* 8 = 6.3 fps,
* 10 = 5.5 fps,
* 15 = 4.4 fps,
* 31 = 2.8 fps
*
* Frame rate on HDCS-1000 with STV602 depends on PSMP:
* 15 = doesn't work at all
* 18 = doesn't work at all
* 19 = 7.3 fps
* 20 = 7.4 fps
* 21 = 7.4 fps
* 22 = 7.4 fps
* 24 = 6.3 fps
* 30 = 5.4 fps
*/
hdcs->psmp = (sd->bridge == BRIDGE_STV602) ? 20 : 5;
sd->sensor_priv = hdcs;
return 0;
}
static int hdcs_probe_1020(struct sd *sd)
{
struct hdcs *hdcs;
u16 sensor;
int ret;
ret = stv06xx_read_sensor(sd, HDCS_IDENT, &sensor);
if (ret < 0 || sensor != 0x10)
return -ENODEV;
info("HDCS-1020 sensor detected");
sd->gspca_dev.cam.cam_mode = hdcs1020_mode;
sd->gspca_dev.cam.nmodes = ARRAY_SIZE(hdcs1020_mode);
sd->desc.ctrls = hdcs1020_ctrl;
sd->desc.nctrls = ARRAY_SIZE(hdcs1020_ctrl);
hdcs = kmalloc(sizeof(struct hdcs), GFP_KERNEL);
if (!hdcs)
return -ENOMEM;
/*
* From Andrey's test image: looks like HDCS-1020 upper-left
* visible pixel is at 24,8 (y maybe even smaller?) and lower-right
* visible pixel at 375,299 (x maybe even larger?)
*/
hdcs->array.left = 24;
hdcs->array.top = 4;
hdcs->array.width = HDCS_1020_DEF_WIDTH;
hdcs->array.height = 304;
hdcs->array.border = 4;
hdcs->psmp = 6;
hdcs->exp.cto = 3;
hdcs->exp.cpo = 3;
hdcs->exp.rs = 155;
hdcs->exp.er = 96;
sd->sensor_priv = hdcs;
return 0;
}
static int hdcs_start(struct sd *sd)
{
PDEBUG(D_STREAM, "Starting stream");
return hdcs_set_state(sd, HDCS_STATE_RUN);
}
static int hdcs_stop(struct sd *sd)
{
PDEBUG(D_STREAM, "Halting stream");
return hdcs_set_state(sd, HDCS_STATE_SLEEP);
}
static void hdcs_disconnect(struct sd *sd)
{
PDEBUG(D_PROBE, "Disconnecting the sensor");
kfree(sd->sensor_priv);
}
static int hdcs_init(struct sd *sd)
{
struct hdcs *hdcs = sd->sensor_priv;
int i, err = 0;
/* Set the STV0602AA in STV0600 emulation mode */
if (sd->bridge == BRIDGE_STV602)
stv06xx_write_bridge(sd, STV_STV0600_EMULATION, 1);
/* Execute the bridge init */
for (i = 0; i < ARRAY_SIZE(stv_bridge_init) && !err; i++) {
err = stv06xx_write_bridge(sd, stv_bridge_init[i][0],
stv_bridge_init[i][1]);
}
if (err < 0)
return err;
/* sensor soft reset */
hdcs_reset(sd);
/* Execute the sensor init */
for (i = 0; i < ARRAY_SIZE(stv_sensor_init) && !err; i++) {
err = stv06xx_write_sensor(sd, stv_sensor_init[i][0],
stv_sensor_init[i][1]);
}
if (err < 0)
return err;
/* Enable continous frame capture, bit 2: stop when frame complete */
err = stv06xx_write_sensor(sd, HDCS_REG_CONFIG(sd), BIT(3));
if (err < 0)
return err;
/* Set PGA sample duration
(was 0x7E for the STV602, but caused slow framerate with HDCS-1020) */
if (IS_1020(sd))
err = stv06xx_write_sensor(sd, HDCS_TCTRL,
(HDCS_ADC_START_SIG_DUR << 6) | hdcs->psmp);
else
err = stv06xx_write_sensor(sd, HDCS_TCTRL,
(HDCS_ADC_START_SIG_DUR << 5) | hdcs->psmp);
if (err < 0)
return err;
err = hdcs_set_gains(sd, HDCS_DEFAULT_GAIN);
if (err < 0)
return err;
err = hdcs_set_size(sd, hdcs->array.width, hdcs->array.height);
if (err < 0)
return err;
err = hdcs_set_exposure(&sd->gspca_dev, HDCS_DEFAULT_EXPOSURE);
return err;
}
static int hdcs_dump(struct sd *sd)
{
u16 reg, val;
info("Dumping sensor registers:");
for (reg = HDCS_IDENT; reg <= HDCS_ROWEXPH; reg++) {
stv06xx_read_sensor(sd, reg, &val);
info("reg 0x%02x = 0x%02x", reg, val);
}
return 0;
}
| gpl-2.0 |
surkovalex/linux | drivers/usb/serial/kl5kusb105.c | 2231 | 17900 | /*
* KLSI KL5KUSB105 chip RS232 converter driver
*
* Copyright (C) 2010 Johan Hovold <jhovold@gmail.com>
* Copyright (C) 2001 Utz-Uwe Haus <haus@uuhaus.de>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* All information about the device was acquired using SniffUSB ans snoopUSB
* on Windows98.
* It was written out of frustration with the PalmConnect USB Serial adapter
* sold by Palm Inc.
* Neither Palm, nor their contractor (MCCI) or their supplier (KLSI) provided
* information that was not already available.
*
* It seems that KLSI bought some silicon-design information from ScanLogic,
* whose SL11R processor is at the core of the KL5KUSB chipset from KLSI.
* KLSI has firmware available for their devices; it is probable that the
* firmware differs from that used by KLSI in their products. If you have an
* original KLSI device and can provide some information on it, I would be
* most interested in adding support for it here. If you have any information
* on the protocol used (or find errors in my reverse-engineered stuff), please
* let me know.
*
* The code was only tested with a PalmConnect USB adapter; if you
* are adventurous, try it with any KLSI-based device and let me know how it
* breaks so that I can fix it!
*/
/* TODO:
* check modem line signals
* implement handshaking or decide that we do not support it
*/
#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/uaccess.h>
#include <asm/unaligned.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include "kl5kusb105.h"
#define DRIVER_AUTHOR "Utz-Uwe Haus <haus@uuhaus.de>, Johan Hovold <jhovold@gmail.com>"
#define DRIVER_DESC "KLSI KL5KUSB105 chipset USB->Serial Converter driver"
/*
* Function prototypes
*/
static int klsi_105_port_probe(struct usb_serial_port *port);
static int klsi_105_port_remove(struct usb_serial_port *port);
static int klsi_105_open(struct tty_struct *tty, struct usb_serial_port *port);
static void klsi_105_close(struct usb_serial_port *port);
static void klsi_105_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old);
static int klsi_105_tiocmget(struct tty_struct *tty);
static int klsi_105_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear);
static void klsi_105_process_read_urb(struct urb *urb);
static int klsi_105_prepare_write_buffer(struct usb_serial_port *port,
void *dest, size_t size);
/*
* All of the device info needed for the KLSI converters.
*/
static const struct usb_device_id id_table[] = {
{ USB_DEVICE(PALMCONNECT_VID, PALMCONNECT_PID) },
{ USB_DEVICE(KLSI_VID, KLSI_KL5KUSB105D_PID) },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table);
static struct usb_serial_driver kl5kusb105d_device = {
.driver = {
.owner = THIS_MODULE,
.name = "kl5kusb105d",
},
.description = "KL5KUSB105D / PalmConnect",
.id_table = id_table,
.num_ports = 1,
.bulk_out_size = 64,
.open = klsi_105_open,
.close = klsi_105_close,
.set_termios = klsi_105_set_termios,
/*.break_ctl = klsi_105_break_ctl,*/
.tiocmget = klsi_105_tiocmget,
.tiocmset = klsi_105_tiocmset,
.port_probe = klsi_105_port_probe,
.port_remove = klsi_105_port_remove,
.throttle = usb_serial_generic_throttle,
.unthrottle = usb_serial_generic_unthrottle,
.process_read_urb = klsi_105_process_read_urb,
.prepare_write_buffer = klsi_105_prepare_write_buffer,
};
static struct usb_serial_driver * const serial_drivers[] = {
&kl5kusb105d_device, NULL
};
struct klsi_105_port_settings {
__u8 pktlen; /* always 5, it seems */
__u8 baudrate;
__u8 databits;
__u8 unknown1;
__u8 unknown2;
} __attribute__ ((packed));
struct klsi_105_private {
struct klsi_105_port_settings cfg;
struct ktermios termios;
unsigned long line_state; /* modem line settings */
spinlock_t lock;
};
/*
* Handle vendor specific USB requests
*/
#define KLSI_TIMEOUT 5000 /* default urb timeout */
static int klsi_105_chg_port_settings(struct usb_serial_port *port,
struct klsi_105_port_settings *settings)
{
int rc;
rc = usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
KL5KUSB105A_SIO_SET_DATA,
USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_INTERFACE,
0, /* value */
0, /* index */
settings,
sizeof(struct klsi_105_port_settings),
KLSI_TIMEOUT);
if (rc < 0)
dev_err(&port->dev,
"Change port settings failed (error = %d)\n", rc);
dev_info(&port->serial->dev->dev,
"%d byte block, baudrate %x, databits %d, u1 %d, u2 %d\n",
settings->pktlen, settings->baudrate, settings->databits,
settings->unknown1, settings->unknown2);
return rc;
}
/* translate a 16-bit status value from the device to linux's TIO bits */
static unsigned long klsi_105_status2linestate(const __u16 status)
{
unsigned long res = 0;
res = ((status & KL5KUSB105A_DSR) ? TIOCM_DSR : 0)
| ((status & KL5KUSB105A_CTS) ? TIOCM_CTS : 0)
;
return res;
}
/*
* Read line control via vendor command and return result through
* *line_state_p
*/
/* It seems that the status buffer has always only 2 bytes length */
#define KLSI_STATUSBUF_LEN 2
static int klsi_105_get_line_state(struct usb_serial_port *port,
unsigned long *line_state_p)
{
int rc;
u8 *status_buf;
__u16 status;
dev_info(&port->serial->dev->dev, "sending SIO Poll request\n");
status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL);
if (!status_buf) {
dev_err(&port->dev, "%s - out of memory for status buffer.\n",
__func__);
return -ENOMEM;
}
status_buf[0] = 0xff;
status_buf[1] = 0xff;
rc = usb_control_msg(port->serial->dev,
usb_rcvctrlpipe(port->serial->dev, 0),
KL5KUSB105A_SIO_POLL,
USB_TYPE_VENDOR | USB_DIR_IN,
0, /* value */
0, /* index */
status_buf, KLSI_STATUSBUF_LEN,
10000
);
if (rc < 0)
dev_err(&port->dev, "Reading line status failed (error = %d)\n",
rc);
else {
status = get_unaligned_le16(status_buf);
dev_info(&port->serial->dev->dev, "read status %x %x",
status_buf[0], status_buf[1]);
*line_state_p = klsi_105_status2linestate(status);
}
kfree(status_buf);
return rc;
}
/*
* Driver's tty interface functions
*/
static int klsi_105_port_probe(struct usb_serial_port *port)
{
struct klsi_105_private *priv;
priv = kmalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
/* set initial values for control structures */
priv->cfg.pktlen = 5;
priv->cfg.baudrate = kl5kusb105a_sio_b9600;
priv->cfg.databits = kl5kusb105a_dtb_8;
priv->cfg.unknown1 = 0;
priv->cfg.unknown2 = 1;
priv->line_state = 0;
spin_lock_init(&priv->lock);
/* priv->termios is left uninitialized until port opening */
usb_set_serial_port_data(port, priv);
return 0;
}
static int klsi_105_port_remove(struct usb_serial_port *port)
{
struct klsi_105_private *priv;
priv = usb_get_serial_port_data(port);
kfree(priv);
return 0;
}
static int klsi_105_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct klsi_105_private *priv = usb_get_serial_port_data(port);
int retval = 0;
int rc;
int i;
unsigned long line_state;
struct klsi_105_port_settings *cfg;
unsigned long flags;
/* Do a defined restart:
* Set up sane default baud rate and send the 'READ_ON'
* vendor command.
* FIXME: set modem line control (how?)
* Then read the modem line control and store values in
* priv->line_state.
*/
cfg = kmalloc(sizeof(*cfg), GFP_KERNEL);
if (!cfg) {
dev_err(&port->dev, "%s - out of memory for config buffer.\n",
__func__);
return -ENOMEM;
}
cfg->pktlen = 5;
cfg->baudrate = kl5kusb105a_sio_b9600;
cfg->databits = kl5kusb105a_dtb_8;
cfg->unknown1 = 0;
cfg->unknown2 = 1;
klsi_105_chg_port_settings(port, cfg);
/* set up termios structure */
spin_lock_irqsave(&priv->lock, flags);
priv->termios.c_iflag = tty->termios.c_iflag;
priv->termios.c_oflag = tty->termios.c_oflag;
priv->termios.c_cflag = tty->termios.c_cflag;
priv->termios.c_lflag = tty->termios.c_lflag;
for (i = 0; i < NCCS; i++)
priv->termios.c_cc[i] = tty->termios.c_cc[i];
priv->cfg.pktlen = cfg->pktlen;
priv->cfg.baudrate = cfg->baudrate;
priv->cfg.databits = cfg->databits;
priv->cfg.unknown1 = cfg->unknown1;
priv->cfg.unknown2 = cfg->unknown2;
spin_unlock_irqrestore(&priv->lock, flags);
/* READ_ON and urb submission */
rc = usb_serial_generic_open(tty, port);
if (rc) {
retval = rc;
goto exit;
}
rc = usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
KL5KUSB105A_SIO_CONFIGURE,
USB_TYPE_VENDOR|USB_DIR_OUT|USB_RECIP_INTERFACE,
KL5KUSB105A_SIO_CONFIGURE_READ_ON,
0, /* index */
NULL,
0,
KLSI_TIMEOUT);
if (rc < 0) {
dev_err(&port->dev, "Enabling read failed (error = %d)\n", rc);
retval = rc;
} else
dev_dbg(&port->dev, "%s - enabled reading\n", __func__);
rc = klsi_105_get_line_state(port, &line_state);
if (rc >= 0) {
spin_lock_irqsave(&priv->lock, flags);
priv->line_state = line_state;
spin_unlock_irqrestore(&priv->lock, flags);
dev_dbg(&port->dev, "%s - read line state 0x%lx\n", __func__, line_state);
retval = 0;
} else
retval = rc;
exit:
kfree(cfg);
return retval;
}
static void klsi_105_close(struct usb_serial_port *port)
{
int rc;
/* send READ_OFF */
rc = usb_control_msg(port->serial->dev,
usb_sndctrlpipe(port->serial->dev, 0),
KL5KUSB105A_SIO_CONFIGURE,
USB_TYPE_VENDOR | USB_DIR_OUT,
KL5KUSB105A_SIO_CONFIGURE_READ_OFF,
0, /* index */
NULL, 0,
KLSI_TIMEOUT);
if (rc < 0)
dev_err(&port->dev, "failed to disable read: %d\n", rc);
/* shutdown our bulk reads and writes */
usb_serial_generic_close(port);
}
/* We need to write a complete 64-byte data block and encode the
* number actually sent in the first double-byte, LSB-order. That
* leaves at most 62 bytes of payload.
*/
#define KLSI_HDR_LEN 2
static int klsi_105_prepare_write_buffer(struct usb_serial_port *port,
void *dest, size_t size)
{
unsigned char *buf = dest;
int count;
count = kfifo_out_locked(&port->write_fifo, buf + KLSI_HDR_LEN, size,
&port->lock);
put_unaligned_le16(count, buf);
return count + KLSI_HDR_LEN;
}
/* The data received is preceded by a length double-byte in LSB-first order.
*/
static void klsi_105_process_read_urb(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
unsigned char *data = urb->transfer_buffer;
unsigned len;
/* empty urbs seem to happen, we ignore them */
if (!urb->actual_length)
return;
if (urb->actual_length <= KLSI_HDR_LEN) {
dev_dbg(&port->dev, "%s - malformed packet\n", __func__);
return;
}
len = get_unaligned_le16(data);
if (len > urb->actual_length - KLSI_HDR_LEN) {
dev_dbg(&port->dev, "%s - packet length mismatch\n", __func__);
len = urb->actual_length - KLSI_HDR_LEN;
}
tty_insert_flip_string(&port->port, data + KLSI_HDR_LEN, len);
tty_flip_buffer_push(&port->port);
}
static void klsi_105_set_termios(struct tty_struct *tty,
struct usb_serial_port *port,
struct ktermios *old_termios)
{
struct klsi_105_private *priv = usb_get_serial_port_data(port);
struct device *dev = &port->dev;
unsigned int iflag = tty->termios.c_iflag;
unsigned int old_iflag = old_termios->c_iflag;
unsigned int cflag = tty->termios.c_cflag;
unsigned int old_cflag = old_termios->c_cflag;
struct klsi_105_port_settings *cfg;
unsigned long flags;
speed_t baud;
cfg = kmalloc(sizeof(*cfg), GFP_KERNEL);
if (!cfg) {
dev_err(dev, "%s - out of memory for config buffer.\n", __func__);
return;
}
/* lock while we are modifying the settings */
spin_lock_irqsave(&priv->lock, flags);
/*
* Update baud rate
*/
baud = tty_get_baud_rate(tty);
if ((cflag & CBAUD) != (old_cflag & CBAUD)) {
/* reassert DTR and (maybe) RTS on transition from B0 */
if ((old_cflag & CBAUD) == B0) {
dev_dbg(dev, "%s: baud was B0\n", __func__);
#if 0
priv->control_state |= TIOCM_DTR;
/* don't set RTS if using hardware flow control */
if (!(old_cflag & CRTSCTS))
priv->control_state |= TIOCM_RTS;
mct_u232_set_modem_ctrl(serial, priv->control_state);
#endif
}
}
switch (baud) {
case 0: /* handled below */
break;
case 1200:
priv->cfg.baudrate = kl5kusb105a_sio_b1200;
break;
case 2400:
priv->cfg.baudrate = kl5kusb105a_sio_b2400;
break;
case 4800:
priv->cfg.baudrate = kl5kusb105a_sio_b4800;
break;
case 9600:
priv->cfg.baudrate = kl5kusb105a_sio_b9600;
break;
case 19200:
priv->cfg.baudrate = kl5kusb105a_sio_b19200;
break;
case 38400:
priv->cfg.baudrate = kl5kusb105a_sio_b38400;
break;
case 57600:
priv->cfg.baudrate = kl5kusb105a_sio_b57600;
break;
case 115200:
priv->cfg.baudrate = kl5kusb105a_sio_b115200;
break;
default:
dev_dbg(dev, "KLSI USB->Serial converter: unsupported baudrate request, using default of 9600");
priv->cfg.baudrate = kl5kusb105a_sio_b9600;
baud = 9600;
break;
}
if ((cflag & CBAUD) == B0) {
dev_dbg(dev, "%s: baud is B0\n", __func__);
/* Drop RTS and DTR */
/* maybe this should be simulated by sending read
* disable and read enable messages?
*/
;
#if 0
priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS);
mct_u232_set_modem_ctrl(serial, priv->control_state);
#endif
}
tty_encode_baud_rate(tty, baud, baud);
if ((cflag & CSIZE) != (old_cflag & CSIZE)) {
/* set the number of data bits */
switch (cflag & CSIZE) {
case CS5:
dev_dbg(dev, "%s - 5 bits/byte not supported\n", __func__);
spin_unlock_irqrestore(&priv->lock, flags);
goto err;
case CS6:
dev_dbg(dev, "%s - 6 bits/byte not supported\n", __func__);
spin_unlock_irqrestore(&priv->lock, flags);
goto err;
case CS7:
priv->cfg.databits = kl5kusb105a_dtb_7;
break;
case CS8:
priv->cfg.databits = kl5kusb105a_dtb_8;
break;
default:
dev_err(dev, "CSIZE was not CS5-CS8, using default of 8\n");
priv->cfg.databits = kl5kusb105a_dtb_8;
break;
}
}
/*
* Update line control register (LCR)
*/
if ((cflag & (PARENB|PARODD)) != (old_cflag & (PARENB|PARODD))
|| (cflag & CSTOPB) != (old_cflag & CSTOPB)) {
/* Not currently supported */
tty->termios.c_cflag &= ~(PARENB|PARODD|CSTOPB);
#if 0
priv->last_lcr = 0;
/* set the parity */
if (cflag & PARENB)
priv->last_lcr |= (cflag & PARODD) ?
MCT_U232_PARITY_ODD : MCT_U232_PARITY_EVEN;
else
priv->last_lcr |= MCT_U232_PARITY_NONE;
/* set the number of stop bits */
priv->last_lcr |= (cflag & CSTOPB) ?
MCT_U232_STOP_BITS_2 : MCT_U232_STOP_BITS_1;
mct_u232_set_line_ctrl(serial, priv->last_lcr);
#endif
;
}
/*
* Set flow control: well, I do not really now how to handle DTR/RTS.
* Just do what we have seen with SniffUSB on Win98.
*/
if ((iflag & IXOFF) != (old_iflag & IXOFF)
|| (iflag & IXON) != (old_iflag & IXON)
|| (cflag & CRTSCTS) != (old_cflag & CRTSCTS)) {
/* Not currently supported */
tty->termios.c_cflag &= ~CRTSCTS;
/* Drop DTR/RTS if no flow control otherwise assert */
#if 0
if ((iflag & IXOFF) || (iflag & IXON) || (cflag & CRTSCTS))
priv->control_state |= TIOCM_DTR | TIOCM_RTS;
else
priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS);
mct_u232_set_modem_ctrl(serial, priv->control_state);
#endif
;
}
memcpy(cfg, &priv->cfg, sizeof(*cfg));
spin_unlock_irqrestore(&priv->lock, flags);
/* now commit changes to device */
klsi_105_chg_port_settings(port, cfg);
err:
kfree(cfg);
}
#if 0
static void mct_u232_break_ctl(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
struct usb_serial *serial = port->serial;
struct mct_u232_private *priv =
(struct mct_u232_private *)port->private;
unsigned char lcr = priv->last_lcr;
dev_dbg(&port->dev, "%s - state=%d\n", __func__, break_state);
/* LOCKING */
if (break_state)
lcr |= MCT_U232_SET_BREAK;
mct_u232_set_line_ctrl(serial, lcr);
}
#endif
static int klsi_105_tiocmget(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct klsi_105_private *priv = usb_get_serial_port_data(port);
unsigned long flags;
int rc;
unsigned long line_state;
rc = klsi_105_get_line_state(port, &line_state);
if (rc < 0) {
dev_err(&port->dev,
"Reading line control failed (error = %d)\n", rc);
/* better return value? EAGAIN? */
return rc;
}
spin_lock_irqsave(&priv->lock, flags);
priv->line_state = line_state;
spin_unlock_irqrestore(&priv->lock, flags);
dev_dbg(&port->dev, "%s - read line state 0x%lx\n", __func__, line_state);
return (int)line_state;
}
static int klsi_105_tiocmset(struct tty_struct *tty,
unsigned int set, unsigned int clear)
{
int retval = -EINVAL;
/* if this ever gets implemented, it should be done something like this:
struct usb_serial *serial = port->serial;
struct klsi_105_private *priv = usb_get_serial_port_data(port);
unsigned long flags;
int control;
spin_lock_irqsave (&priv->lock, flags);
if (set & TIOCM_RTS)
priv->control_state |= TIOCM_RTS;
if (set & TIOCM_DTR)
priv->control_state |= TIOCM_DTR;
if (clear & TIOCM_RTS)
priv->control_state &= ~TIOCM_RTS;
if (clear & TIOCM_DTR)
priv->control_state &= ~TIOCM_DTR;
control = priv->control_state;
spin_unlock_irqrestore (&priv->lock, flags);
retval = mct_u232_set_modem_ctrl(serial, control);
*/
return retval;
}
module_usb_serial_driver(serial_drivers, id_table);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
KernelWorld/KW-Kenzo | drivers/md/persistent-data/dm-space-map-disk.c | 2231 | 6762 | /*
* Copyright (C) 2011 Red Hat, Inc.
*
* This file is released under the GPL.
*/
#include "dm-space-map-common.h"
#include "dm-space-map-disk.h"
#include "dm-space-map.h"
#include "dm-transaction-manager.h"
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/device-mapper.h>
#define DM_MSG_PREFIX "space map disk"
/*----------------------------------------------------------------*/
/*
* Space map interface.
*/
struct sm_disk {
struct dm_space_map sm;
struct ll_disk ll;
struct ll_disk old_ll;
dm_block_t begin;
dm_block_t nr_allocated_this_transaction;
};
static void sm_disk_destroy(struct dm_space_map *sm)
{
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
kfree(smd);
}
static int sm_disk_extend(struct dm_space_map *sm, dm_block_t extra_blocks)
{
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
return sm_ll_extend(&smd->ll, extra_blocks);
}
static int sm_disk_get_nr_blocks(struct dm_space_map *sm, dm_block_t *count)
{
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
*count = smd->old_ll.nr_blocks;
return 0;
}
static int sm_disk_get_nr_free(struct dm_space_map *sm, dm_block_t *count)
{
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
*count = (smd->old_ll.nr_blocks - smd->old_ll.nr_allocated) - smd->nr_allocated_this_transaction;
return 0;
}
static int sm_disk_get_count(struct dm_space_map *sm, dm_block_t b,
uint32_t *result)
{
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
return sm_ll_lookup(&smd->ll, b, result);
}
static int sm_disk_count_is_more_than_one(struct dm_space_map *sm, dm_block_t b,
int *result)
{
int r;
uint32_t count;
r = sm_disk_get_count(sm, b, &count);
if (r)
return r;
return count > 1;
}
static int sm_disk_set_count(struct dm_space_map *sm, dm_block_t b,
uint32_t count)
{
int r;
uint32_t old_count;
enum allocation_event ev;
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
r = sm_ll_insert(&smd->ll, b, count, &ev);
if (!r) {
switch (ev) {
case SM_NONE:
break;
case SM_ALLOC:
/*
* This _must_ be free in the prior transaction
* otherwise we've lost atomicity.
*/
smd->nr_allocated_this_transaction++;
break;
case SM_FREE:
/*
* It's only free if it's also free in the last
* transaction.
*/
r = sm_ll_lookup(&smd->old_ll, b, &old_count);
if (r)
return r;
if (!old_count)
smd->nr_allocated_this_transaction--;
break;
}
}
return r;
}
static int sm_disk_inc_block(struct dm_space_map *sm, dm_block_t b)
{
int r;
enum allocation_event ev;
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
r = sm_ll_inc(&smd->ll, b, &ev);
if (!r && (ev == SM_ALLOC))
/*
* This _must_ be free in the prior transaction
* otherwise we've lost atomicity.
*/
smd->nr_allocated_this_transaction++;
return r;
}
static int sm_disk_dec_block(struct dm_space_map *sm, dm_block_t b)
{
int r;
uint32_t old_count;
enum allocation_event ev;
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
r = sm_ll_dec(&smd->ll, b, &ev);
if (!r && (ev == SM_FREE)) {
/*
* It's only free if it's also free in the last
* transaction.
*/
r = sm_ll_lookup(&smd->old_ll, b, &old_count);
if (r)
return r;
if (!old_count)
smd->nr_allocated_this_transaction--;
}
return r;
}
static int sm_disk_new_block(struct dm_space_map *sm, dm_block_t *b)
{
int r;
enum allocation_event ev;
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
/* FIXME: we should loop round a couple of times */
r = sm_ll_find_free_block(&smd->old_ll, smd->begin, smd->old_ll.nr_blocks, b);
if (r)
return r;
smd->begin = *b + 1;
r = sm_ll_inc(&smd->ll, *b, &ev);
if (!r) {
BUG_ON(ev != SM_ALLOC);
smd->nr_allocated_this_transaction++;
}
return r;
}
static int sm_disk_commit(struct dm_space_map *sm)
{
int r;
dm_block_t nr_free;
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
r = sm_disk_get_nr_free(sm, &nr_free);
if (r)
return r;
r = sm_ll_commit(&smd->ll);
if (r)
return r;
memcpy(&smd->old_ll, &smd->ll, sizeof(smd->old_ll));
smd->begin = 0;
smd->nr_allocated_this_transaction = 0;
r = sm_disk_get_nr_free(sm, &nr_free);
if (r)
return r;
return 0;
}
static int sm_disk_root_size(struct dm_space_map *sm, size_t *result)
{
*result = sizeof(struct disk_sm_root);
return 0;
}
static int sm_disk_copy_root(struct dm_space_map *sm, void *where_le, size_t max)
{
struct sm_disk *smd = container_of(sm, struct sm_disk, sm);
struct disk_sm_root root_le;
root_le.nr_blocks = cpu_to_le64(smd->ll.nr_blocks);
root_le.nr_allocated = cpu_to_le64(smd->ll.nr_allocated);
root_le.bitmap_root = cpu_to_le64(smd->ll.bitmap_root);
root_le.ref_count_root = cpu_to_le64(smd->ll.ref_count_root);
if (max < sizeof(root_le))
return -ENOSPC;
memcpy(where_le, &root_le, sizeof(root_le));
return 0;
}
/*----------------------------------------------------------------*/
static struct dm_space_map ops = {
.destroy = sm_disk_destroy,
.extend = sm_disk_extend,
.get_nr_blocks = sm_disk_get_nr_blocks,
.get_nr_free = sm_disk_get_nr_free,
.get_count = sm_disk_get_count,
.count_is_more_than_one = sm_disk_count_is_more_than_one,
.set_count = sm_disk_set_count,
.inc_block = sm_disk_inc_block,
.dec_block = sm_disk_dec_block,
.new_block = sm_disk_new_block,
.commit = sm_disk_commit,
.root_size = sm_disk_root_size,
.copy_root = sm_disk_copy_root,
.register_threshold_callback = NULL
};
struct dm_space_map *dm_sm_disk_create(struct dm_transaction_manager *tm,
dm_block_t nr_blocks)
{
int r;
struct sm_disk *smd;
smd = kmalloc(sizeof(*smd), GFP_KERNEL);
if (!smd)
return ERR_PTR(-ENOMEM);
smd->begin = 0;
smd->nr_allocated_this_transaction = 0;
memcpy(&smd->sm, &ops, sizeof(smd->sm));
r = sm_ll_new_disk(&smd->ll, tm);
if (r)
goto bad;
r = sm_ll_extend(&smd->ll, nr_blocks);
if (r)
goto bad;
r = sm_disk_commit(&smd->sm);
if (r)
goto bad;
return &smd->sm;
bad:
kfree(smd);
return ERR_PTR(r);
}
EXPORT_SYMBOL_GPL(dm_sm_disk_create);
struct dm_space_map *dm_sm_disk_open(struct dm_transaction_manager *tm,
void *root_le, size_t len)
{
int r;
struct sm_disk *smd;
smd = kmalloc(sizeof(*smd), GFP_KERNEL);
if (!smd)
return ERR_PTR(-ENOMEM);
smd->begin = 0;
smd->nr_allocated_this_transaction = 0;
memcpy(&smd->sm, &ops, sizeof(smd->sm));
r = sm_ll_open_disk(&smd->ll, tm, root_le, len);
if (r)
goto bad;
r = sm_disk_commit(&smd->sm);
if (r)
goto bad;
return &smd->sm;
bad:
kfree(smd);
return ERR_PTR(r);
}
EXPORT_SYMBOL_GPL(dm_sm_disk_open);
/*----------------------------------------------------------------*/
| gpl-2.0 |
Alberto97/android_kernel_lge_dory | arch/m68k/platform/68000/timers.c | 2231 | 3517 | /***************************************************************************/
/*
* timers.c - Generic hardware timer support.
*
* Copyright (C) 1993 Hamish Macdonald
* Copyright (C) 1999 D. Jeff Dionne
* Copyright (C) 2001 Georges Menie, Ken Desmet
*
* 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/types.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/clocksource.h>
#include <linux/rtc.h>
#include <asm/setup.h>
#include <asm/pgtable.h>
#include <asm/machdep.h>
#include <asm/MC68VZ328.h>
/***************************************************************************/
#if defined(CONFIG_DRAGEN2)
/* with a 33.16 MHz clock, this will give usec resolution to the time functions */
#define CLOCK_SOURCE TCTL_CLKSOURCE_SYSCLK
#define CLOCK_PRE 7
#define TICKS_PER_JIFFY 41450
#elif defined(CONFIG_XCOPILOT_BUGS)
/*
* The only thing I know is that CLK32 is not available on Xcopilot
* I have little idea about what frequency SYSCLK has on Xcopilot.
* The values for prescaler and compare registers were simply
* taken from the original source
*/
#define CLOCK_SOURCE TCTL_CLKSOURCE_SYSCLK
#define CLOCK_PRE 2
#define TICKS_PER_JIFFY 0xd7e4
#else
/* default to using the 32Khz clock */
#define CLOCK_SOURCE TCTL_CLKSOURCE_32KHZ
#define CLOCK_PRE 31
#define TICKS_PER_JIFFY 10
#endif
static u32 m68328_tick_cnt;
static irq_handler_t timer_interrupt;
/***************************************************************************/
static irqreturn_t hw_tick(int irq, void *dummy)
{
/* Reset Timer1 */
TSTAT &= 0;
m68328_tick_cnt += TICKS_PER_JIFFY;
return timer_interrupt(irq, dummy);
}
/***************************************************************************/
static struct irqaction m68328_timer_irq = {
.name = "timer",
.flags = IRQF_DISABLED | IRQF_TIMER,
.handler = hw_tick,
};
/***************************************************************************/
static cycle_t m68328_read_clk(struct clocksource *cs)
{
unsigned long flags;
u32 cycles;
local_irq_save(flags);
cycles = m68328_tick_cnt + TCN;
local_irq_restore(flags);
return cycles;
}
/***************************************************************************/
static struct clocksource m68328_clk = {
.name = "timer",
.rating = 250,
.read = m68328_read_clk,
.mask = CLOCKSOURCE_MASK(32),
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
/***************************************************************************/
void hw_timer_init(irq_handler_t handler)
{
/* disable timer 1 */
TCTL = 0;
/* set ISR */
setup_irq(TMR_IRQ_NUM, &m68328_timer_irq);
/* Restart mode, Enable int, Set clock source */
TCTL = TCTL_OM | TCTL_IRQEN | CLOCK_SOURCE;
TPRER = CLOCK_PRE;
TCMP = TICKS_PER_JIFFY;
/* Enable timer 1 */
TCTL |= TCTL_TEN;
clocksource_register_hz(&m68328_clk, TICKS_PER_JIFFY*HZ);
timer_interrupt = handler;
}
/***************************************************************************/
int m68328_hwclk(int set, struct rtc_time *t)
{
if (!set) {
long now = RTCTIME;
t->tm_year = t->tm_mon = t->tm_mday = 1;
t->tm_hour = (now >> 24) % 24;
t->tm_min = (now >> 16) % 60;
t->tm_sec = now % 60;
}
return 0;
}
/***************************************************************************/
| gpl-2.0 |
TeamExodus/kernel_yu_tomato | drivers/pci/remove.c | 2231 | 3343 | #include <linux/pci.h>
#include <linux/module.h>
#include <linux/pci-aspm.h>
#include "pci.h"
static void pci_free_resources(struct pci_dev *dev)
{
int i;
msi_remove_pci_irq_vectors(dev);
pci_cleanup_rom(dev);
for (i = 0; i < PCI_NUM_RESOURCES; i++) {
struct resource *res = dev->resource + i;
if (res->parent)
release_resource(res);
}
}
static void pci_stop_dev(struct pci_dev *dev)
{
pci_pme_active(dev, false);
if (dev->is_added) {
pci_proc_detach_device(dev);
pci_remove_sysfs_dev_files(dev);
device_del(&dev->dev);
dev->is_added = 0;
}
if (dev->bus->self)
pcie_aspm_exit_link_state(dev);
}
static void pci_destroy_dev(struct pci_dev *dev)
{
down_write(&pci_bus_sem);
list_del(&dev->bus_list);
up_write(&pci_bus_sem);
pci_free_resources(dev);
put_device(&dev->dev);
}
void pci_remove_bus(struct pci_bus *bus)
{
pci_proc_detach_bus(bus);
down_write(&pci_bus_sem);
list_del(&bus->node);
pci_bus_release_busn_res(bus);
up_write(&pci_bus_sem);
pci_remove_legacy_files(bus);
pcibios_remove_bus(bus);
device_unregister(&bus->dev);
}
EXPORT_SYMBOL(pci_remove_bus);
static void pci_stop_bus_device(struct pci_dev *dev)
{
struct pci_bus *bus = dev->subordinate;
struct pci_dev *child, *tmp;
/*
* Stopping an SR-IOV PF device removes all the associated VFs,
* which will update the bus->devices list and confuse the
* iterator. Therefore, iterate in reverse so we remove the VFs
* first, then the PF.
*/
if (bus) {
list_for_each_entry_safe_reverse(child, tmp,
&bus->devices, bus_list)
pci_stop_bus_device(child);
}
pci_stop_dev(dev);
}
static void pci_remove_bus_device(struct pci_dev *dev)
{
struct pci_bus *bus = dev->subordinate;
struct pci_dev *child, *tmp;
if (bus) {
list_for_each_entry_safe(child, tmp,
&bus->devices, bus_list)
pci_remove_bus_device(child);
pci_remove_bus(bus);
dev->subordinate = NULL;
}
pci_destroy_dev(dev);
}
/**
* pci_stop_and_remove_bus_device - remove a PCI device and any children
* @dev: the device to remove
*
* Remove a PCI device from the device lists, informing the drivers
* that the device has been removed. We also remove any subordinate
* buses and children in a depth-first manner.
*
* For each device we remove, delete the device structure from the
* device lists, remove the /proc entry, and notify userspace
* (/sbin/hotplug).
*/
void pci_stop_and_remove_bus_device(struct pci_dev *dev)
{
pci_stop_bus_device(dev);
pci_remove_bus_device(dev);
}
EXPORT_SYMBOL(pci_stop_and_remove_bus_device);
void pci_stop_root_bus(struct pci_bus *bus)
{
struct pci_dev *child, *tmp;
struct pci_host_bridge *host_bridge;
if (!pci_is_root_bus(bus))
return;
host_bridge = to_pci_host_bridge(bus->bridge);
list_for_each_entry_safe_reverse(child, tmp,
&bus->devices, bus_list)
pci_stop_bus_device(child);
/* stop the host bridge */
device_del(&host_bridge->dev);
}
void pci_remove_root_bus(struct pci_bus *bus)
{
struct pci_dev *child, *tmp;
struct pci_host_bridge *host_bridge;
if (!pci_is_root_bus(bus))
return;
host_bridge = to_pci_host_bridge(bus->bridge);
list_for_each_entry_safe(child, tmp,
&bus->devices, bus_list)
pci_remove_bus_device(child);
pci_remove_bus(bus);
host_bridge->bus = NULL;
/* remove the host bridge */
put_device(&host_bridge->dev);
}
| gpl-2.0 |
CryToCry96/android_kernel_huawei_msm7x27a | fs/fat/dir.c | 3255 | 34883 | /*
* linux/fs/fat/dir.c
*
* directory handling functions for fat-based filesystems
*
* Written 1992,1993 by Werner Almesberger
*
* Hidden files 1995 by Albert Cahalan <albert@ccs.neu.edu> <adc@coe.neu.edu>
*
* VFAT extensions by Gordon Chaffee <chaffee@plateau.cs.berkeley.edu>
* Merged with msdos fs by Henrik Storner <storner@osiris.ping.dk>
* Rewritten for constant inumbers. Plugged buffer overrun in readdir(). AV
* Short name translation 1999, 2001 by Wolfram Pienkoss <wp@bszh.de>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/buffer_head.h>
#include <linux/compat.h>
#include <asm/uaccess.h>
#include <linux/kernel.h>
#include "fat.h"
/*
* Maximum buffer size of short name.
* [(MSDOS_NAME + '.') * max one char + nul]
* For msdos style, ['.' (hidden) + MSDOS_NAME + '.' + nul]
*/
#define FAT_MAX_SHORT_SIZE ((MSDOS_NAME + 1) * NLS_MAX_CHARSET_SIZE + 1)
/*
* Maximum buffer size of unicode chars from slots.
* [(max longname slots * 13 (size in a slot) + nul) * sizeof(wchar_t)]
*/
#define FAT_MAX_UNI_CHARS ((MSDOS_SLOTS - 1) * 13 + 1)
#define FAT_MAX_UNI_SIZE (FAT_MAX_UNI_CHARS * sizeof(wchar_t))
static inline loff_t fat_make_i_pos(struct super_block *sb,
struct buffer_head *bh,
struct msdos_dir_entry *de)
{
return ((loff_t)bh->b_blocknr << MSDOS_SB(sb)->dir_per_block_bits)
| (de - (struct msdos_dir_entry *)bh->b_data);
}
static inline void fat_dir_readahead(struct inode *dir, sector_t iblock,
sector_t phys)
{
struct super_block *sb = dir->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
struct buffer_head *bh;
int sec;
/* This is not a first sector of cluster, or sec_per_clus == 1 */
if ((iblock & (sbi->sec_per_clus - 1)) || sbi->sec_per_clus == 1)
return;
/* root dir of FAT12/FAT16 */
if ((sbi->fat_bits != 32) && (dir->i_ino == MSDOS_ROOT_INO))
return;
bh = sb_find_get_block(sb, phys);
if (bh == NULL || !buffer_uptodate(bh)) {
for (sec = 0; sec < sbi->sec_per_clus; sec++)
sb_breadahead(sb, phys + sec);
}
brelse(bh);
}
/* Returns the inode number of the directory entry at offset pos. If bh is
non-NULL, it is brelse'd before. Pos is incremented. The buffer header is
returned in bh.
AV. Most often we do it item-by-item. Makes sense to optimize.
AV. OK, there we go: if both bh and de are non-NULL we assume that we just
AV. want the next entry (took one explicit de=NULL in vfat/namei.c).
AV. It's done in fat_get_entry() (inlined), here the slow case lives.
AV. Additionally, when we return -1 (i.e. reached the end of directory)
AV. we make bh NULL.
*/
static int fat__get_entry(struct inode *dir, loff_t *pos,
struct buffer_head **bh, struct msdos_dir_entry **de)
{
struct super_block *sb = dir->i_sb;
sector_t phys, iblock;
unsigned long mapped_blocks;
int err, offset;
next:
if (*bh)
brelse(*bh);
*bh = NULL;
iblock = *pos >> sb->s_blocksize_bits;
err = fat_bmap(dir, iblock, &phys, &mapped_blocks, 0);
if (err || !phys)
return -1; /* beyond EOF or error */
fat_dir_readahead(dir, iblock, phys);
*bh = sb_bread(sb, phys);
if (*bh == NULL) {
fat_msg(sb, KERN_ERR, "Directory bread(block %llu) failed",
(llu)phys);
/* skip this block */
*pos = (iblock + 1) << sb->s_blocksize_bits;
goto next;
}
offset = *pos & (sb->s_blocksize - 1);
*pos += sizeof(struct msdos_dir_entry);
*de = (struct msdos_dir_entry *)((*bh)->b_data + offset);
return 0;
}
static inline int fat_get_entry(struct inode *dir, loff_t *pos,
struct buffer_head **bh,
struct msdos_dir_entry **de)
{
/* Fast stuff first */
if (*bh && *de &&
(*de - (struct msdos_dir_entry *)(*bh)->b_data) < MSDOS_SB(dir->i_sb)->dir_per_block - 1) {
*pos += sizeof(struct msdos_dir_entry);
(*de)++;
return 0;
}
return fat__get_entry(dir, pos, bh, de);
}
/*
* Convert Unicode 16 to UTF-8, translated Unicode, or ASCII.
* If uni_xlate is enabled and we can't get a 1:1 conversion, use a
* colon as an escape character since it is normally invalid on the vfat
* filesystem. The following four characters are the hexadecimal digits
* of Unicode value. This lets us do a full dump and restore of Unicode
* filenames. We could get into some trouble with long Unicode names,
* but ignore that right now.
* Ahem... Stack smashing in ring 0 isn't fun. Fixed.
*/
static int uni16_to_x8(struct super_block *sb, unsigned char *ascii,
const wchar_t *uni, int len, struct nls_table *nls)
{
int uni_xlate = MSDOS_SB(sb)->options.unicode_xlate;
const wchar_t *ip;
wchar_t ec;
unsigned char *op;
int charlen;
ip = uni;
op = ascii;
while (*ip && ((len - NLS_MAX_CHARSET_SIZE) > 0)) {
ec = *ip++;
if ((charlen = nls->uni2char(ec, op, NLS_MAX_CHARSET_SIZE)) > 0) {
op += charlen;
len -= charlen;
} else {
if (uni_xlate == 1) {
*op++ = ':';
op = hex_byte_pack(op, ec >> 8);
op = hex_byte_pack(op, ec);
len -= 5;
} else {
*op++ = '?';
len--;
}
}
}
if (unlikely(*ip)) {
fat_msg(sb, KERN_WARNING, "filename was truncated while "
"converting.");
}
*op = 0;
return (op - ascii);
}
static inline int fat_uni_to_x8(struct super_block *sb, const wchar_t *uni,
unsigned char *buf, int size)
{
struct msdos_sb_info *sbi = MSDOS_SB(sb);
if (sbi->options.utf8)
return utf16s_to_utf8s(uni, FAT_MAX_UNI_CHARS,
UTF16_HOST_ENDIAN, buf, size);
else
return uni16_to_x8(sb, buf, uni, size, sbi->nls_io);
}
static inline int
fat_short2uni(struct nls_table *t, unsigned char *c, int clen, wchar_t *uni)
{
int charlen;
charlen = t->char2uni(c, clen, uni);
if (charlen < 0) {
*uni = 0x003f; /* a question mark */
charlen = 1;
}
return charlen;
}
static inline int
fat_short2lower_uni(struct nls_table *t, unsigned char *c, int clen, wchar_t *uni)
{
int charlen;
wchar_t wc;
charlen = t->char2uni(c, clen, &wc);
if (charlen < 0) {
*uni = 0x003f; /* a question mark */
charlen = 1;
} else if (charlen <= 1) {
unsigned char nc = t->charset2lower[*c];
if (!nc)
nc = *c;
if ( (charlen = t->char2uni(&nc, 1, uni)) < 0) {
*uni = 0x003f; /* a question mark */
charlen = 1;
}
} else
*uni = wc;
return charlen;
}
static inline int
fat_shortname2uni(struct nls_table *nls, unsigned char *buf, int buf_size,
wchar_t *uni_buf, unsigned short opt, int lower)
{
int len = 0;
if (opt & VFAT_SFN_DISPLAY_LOWER)
len = fat_short2lower_uni(nls, buf, buf_size, uni_buf);
else if (opt & VFAT_SFN_DISPLAY_WIN95)
len = fat_short2uni(nls, buf, buf_size, uni_buf);
else if (opt & VFAT_SFN_DISPLAY_WINNT) {
if (lower)
len = fat_short2lower_uni(nls, buf, buf_size, uni_buf);
else
len = fat_short2uni(nls, buf, buf_size, uni_buf);
} else
len = fat_short2uni(nls, buf, buf_size, uni_buf);
return len;
}
static inline int fat_name_match(struct msdos_sb_info *sbi,
const unsigned char *a, int a_len,
const unsigned char *b, int b_len)
{
if (a_len != b_len)
return 0;
if (sbi->options.name_check != 's')
return !nls_strnicmp(sbi->nls_io, a, b, a_len);
else
return !memcmp(a, b, a_len);
}
enum { PARSE_INVALID = 1, PARSE_NOT_LONGNAME, PARSE_EOF, };
/**
* fat_parse_long - Parse extended directory entry.
*
* This function returns zero on success, negative value on error, or one of
* the following:
*
* %PARSE_INVALID - Directory entry is invalid.
* %PARSE_NOT_LONGNAME - Directory entry does not contain longname.
* %PARSE_EOF - Directory has no more entries.
*/
static int fat_parse_long(struct inode *dir, loff_t *pos,
struct buffer_head **bh, struct msdos_dir_entry **de,
wchar_t **unicode, unsigned char *nr_slots)
{
struct msdos_dir_slot *ds;
unsigned char id, slot, slots, alias_checksum;
if (!*unicode) {
*unicode = __getname();
if (!*unicode) {
brelse(*bh);
return -ENOMEM;
}
}
parse_long:
slots = 0;
ds = (struct msdos_dir_slot *)*de;
id = ds->id;
if (!(id & 0x40))
return PARSE_INVALID;
slots = id & ~0x40;
if (slots > 20 || !slots) /* ceil(256 * 2 / 26) */
return PARSE_INVALID;
*nr_slots = slots;
alias_checksum = ds->alias_checksum;
slot = slots;
while (1) {
int offset;
slot--;
offset = slot * 13;
fat16_towchar(*unicode + offset, ds->name0_4, 5);
fat16_towchar(*unicode + offset + 5, ds->name5_10, 6);
fat16_towchar(*unicode + offset + 11, ds->name11_12, 2);
if (ds->id & 0x40)
(*unicode)[offset + 13] = 0;
if (fat_get_entry(dir, pos, bh, de) < 0)
return PARSE_EOF;
if (slot == 0)
break;
ds = (struct msdos_dir_slot *)*de;
if (ds->attr != ATTR_EXT)
return PARSE_NOT_LONGNAME;
if ((ds->id & ~0x40) != slot)
goto parse_long;
if (ds->alias_checksum != alias_checksum)
goto parse_long;
}
if ((*de)->name[0] == DELETED_FLAG)
return PARSE_INVALID;
if ((*de)->attr == ATTR_EXT)
goto parse_long;
if (IS_FREE((*de)->name) || ((*de)->attr & ATTR_VOLUME))
return PARSE_INVALID;
if (fat_checksum((*de)->name) != alias_checksum)
*nr_slots = 0;
return 0;
}
/*
* Return values: negative -> error, 0 -> not found, positive -> found,
* value is the total amount of slots, including the shortname entry.
*/
int fat_search_long(struct inode *inode, const unsigned char *name,
int name_len, struct fat_slot_info *sinfo)
{
struct super_block *sb = inode->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
struct buffer_head *bh = NULL;
struct msdos_dir_entry *de;
struct nls_table *nls_disk = sbi->nls_disk;
unsigned char nr_slots;
wchar_t bufuname[14];
wchar_t *unicode = NULL;
unsigned char work[MSDOS_NAME];
unsigned char bufname[FAT_MAX_SHORT_SIZE];
unsigned short opt_shortname = sbi->options.shortname;
loff_t cpos = 0;
int chl, i, j, last_u, err, len;
err = -ENOENT;
while (1) {
if (fat_get_entry(inode, &cpos, &bh, &de) == -1)
goto end_of_dir;
parse_record:
nr_slots = 0;
if (de->name[0] == DELETED_FLAG)
continue;
if (de->attr != ATTR_EXT && (de->attr & ATTR_VOLUME))
continue;
if (de->attr != ATTR_EXT && IS_FREE(de->name))
continue;
if (de->attr == ATTR_EXT) {
int status = fat_parse_long(inode, &cpos, &bh, &de,
&unicode, &nr_slots);
if (status < 0) {
err = status;
goto end_of_dir;
} else if (status == PARSE_INVALID)
continue;
else if (status == PARSE_NOT_LONGNAME)
goto parse_record;
else if (status == PARSE_EOF)
goto end_of_dir;
}
memcpy(work, de->name, sizeof(de->name));
/* see namei.c, msdos_format_name */
if (work[0] == 0x05)
work[0] = 0xE5;
for (i = 0, j = 0, last_u = 0; i < 8;) {
if (!work[i])
break;
chl = fat_shortname2uni(nls_disk, &work[i], 8 - i,
&bufuname[j++], opt_shortname,
de->lcase & CASE_LOWER_BASE);
if (chl <= 1) {
if (work[i] != ' ')
last_u = j;
} else {
last_u = j;
}
i += chl;
}
j = last_u;
fat_short2uni(nls_disk, ".", 1, &bufuname[j++]);
for (i = 8; i < MSDOS_NAME;) {
if (!work[i])
break;
chl = fat_shortname2uni(nls_disk, &work[i],
MSDOS_NAME - i,
&bufuname[j++], opt_shortname,
de->lcase & CASE_LOWER_EXT);
if (chl <= 1) {
if (work[i] != ' ')
last_u = j;
} else {
last_u = j;
}
i += chl;
}
if (!last_u)
continue;
/* Compare shortname */
bufuname[last_u] = 0x0000;
len = fat_uni_to_x8(sb, bufuname, bufname, sizeof(bufname));
if (fat_name_match(sbi, name, name_len, bufname, len))
goto found;
if (nr_slots) {
void *longname = unicode + FAT_MAX_UNI_CHARS;
int size = PATH_MAX - FAT_MAX_UNI_SIZE;
/* Compare longname */
len = fat_uni_to_x8(sb, unicode, longname, size);
if (fat_name_match(sbi, name, name_len, longname, len))
goto found;
}
}
found:
nr_slots++; /* include the de */
sinfo->slot_off = cpos - nr_slots * sizeof(*de);
sinfo->nr_slots = nr_slots;
sinfo->de = de;
sinfo->bh = bh;
sinfo->i_pos = fat_make_i_pos(sb, sinfo->bh, sinfo->de);
err = 0;
end_of_dir:
if (unicode)
__putname(unicode);
return err;
}
EXPORT_SYMBOL_GPL(fat_search_long);
struct fat_ioctl_filldir_callback {
void __user *dirent;
int result;
/* for dir ioctl */
const char *longname;
int long_len;
const char *shortname;
int short_len;
};
static int __fat_readdir(struct inode *inode, struct file *filp, void *dirent,
filldir_t filldir, int short_only, int both)
{
struct super_block *sb = inode->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
struct buffer_head *bh;
struct msdos_dir_entry *de;
struct nls_table *nls_disk = sbi->nls_disk;
unsigned char nr_slots;
wchar_t bufuname[14];
wchar_t *unicode = NULL;
unsigned char c, work[MSDOS_NAME];
unsigned char bufname[FAT_MAX_SHORT_SIZE], *ptname = bufname;
unsigned short opt_shortname = sbi->options.shortname;
int isvfat = sbi->options.isvfat;
int nocase = sbi->options.nocase;
const char *fill_name = NULL;
unsigned long inum;
unsigned long lpos, dummy, *furrfu = &lpos;
loff_t cpos;
int chi, chl, i, i2, j, last, last_u, dotoffset = 0, fill_len = 0;
int ret = 0;
lock_super(sb);
cpos = filp->f_pos;
/* Fake . and .. for the root directory. */
if (inode->i_ino == MSDOS_ROOT_INO) {
while (cpos < 2) {
if (filldir(dirent, "..", cpos+1, cpos, MSDOS_ROOT_INO, DT_DIR) < 0)
goto out;
cpos++;
filp->f_pos++;
}
if (cpos == 2) {
dummy = 2;
furrfu = &dummy;
cpos = 0;
}
}
if (cpos & (sizeof(struct msdos_dir_entry) - 1)) {
ret = -ENOENT;
goto out;
}
bh = NULL;
get_new:
if (fat_get_entry(inode, &cpos, &bh, &de) == -1)
goto end_of_dir;
parse_record:
nr_slots = 0;
/*
* Check for long filename entry, but if short_only, we don't
* need to parse long filename.
*/
if (isvfat && !short_only) {
if (de->name[0] == DELETED_FLAG)
goto record_end;
if (de->attr != ATTR_EXT && (de->attr & ATTR_VOLUME))
goto record_end;
if (de->attr != ATTR_EXT && IS_FREE(de->name))
goto record_end;
} else {
if ((de->attr & ATTR_VOLUME) || IS_FREE(de->name))
goto record_end;
}
if (isvfat && de->attr == ATTR_EXT) {
int status = fat_parse_long(inode, &cpos, &bh, &de,
&unicode, &nr_slots);
if (status < 0) {
filp->f_pos = cpos;
ret = status;
goto out;
} else if (status == PARSE_INVALID)
goto record_end;
else if (status == PARSE_NOT_LONGNAME)
goto parse_record;
else if (status == PARSE_EOF)
goto end_of_dir;
if (nr_slots) {
void *longname = unicode + FAT_MAX_UNI_CHARS;
int size = PATH_MAX - FAT_MAX_UNI_SIZE;
int len = fat_uni_to_x8(sb, unicode, longname, size);
fill_name = longname;
fill_len = len;
/* !both && !short_only, so we don't need shortname. */
if (!both)
goto start_filldir;
}
}
if (sbi->options.dotsOK) {
ptname = bufname;
dotoffset = 0;
if (de->attr & ATTR_HIDDEN) {
*ptname++ = '.';
dotoffset = 1;
}
}
memcpy(work, de->name, sizeof(de->name));
/* see namei.c, msdos_format_name */
if (work[0] == 0x05)
work[0] = 0xE5;
for (i = 0, j = 0, last = 0, last_u = 0; i < 8;) {
if (!(c = work[i]))
break;
chl = fat_shortname2uni(nls_disk, &work[i], 8 - i,
&bufuname[j++], opt_shortname,
de->lcase & CASE_LOWER_BASE);
if (chl <= 1) {
ptname[i++] = (!nocase && c>='A' && c<='Z') ? c+32 : c;
if (c != ' ') {
last = i;
last_u = j;
}
} else {
last_u = j;
for (chi = 0; chi < chl && i < 8; chi++) {
ptname[i] = work[i];
i++; last = i;
}
}
}
i = last;
j = last_u;
fat_short2uni(nls_disk, ".", 1, &bufuname[j++]);
ptname[i++] = '.';
for (i2 = 8; i2 < MSDOS_NAME;) {
if (!(c = work[i2]))
break;
chl = fat_shortname2uni(nls_disk, &work[i2], MSDOS_NAME - i2,
&bufuname[j++], opt_shortname,
de->lcase & CASE_LOWER_EXT);
if (chl <= 1) {
i2++;
ptname[i++] = (!nocase && c>='A' && c<='Z') ? c+32 : c;
if (c != ' ') {
last = i;
last_u = j;
}
} else {
last_u = j;
for (chi = 0; chi < chl && i2 < MSDOS_NAME; chi++) {
ptname[i++] = work[i2++];
last = i;
}
}
}
if (!last)
goto record_end;
i = last + dotoffset;
j = last_u;
if (isvfat) {
bufuname[j] = 0x0000;
i = fat_uni_to_x8(sb, bufuname, bufname, sizeof(bufname));
}
if (nr_slots) {
/* hack for fat_ioctl_filldir() */
struct fat_ioctl_filldir_callback *p = dirent;
p->longname = fill_name;
p->long_len = fill_len;
p->shortname = bufname;
p->short_len = i;
fill_name = NULL;
fill_len = 0;
} else {
fill_name = bufname;
fill_len = i;
}
start_filldir:
lpos = cpos - (nr_slots + 1) * sizeof(struct msdos_dir_entry);
if (!memcmp(de->name, MSDOS_DOT, MSDOS_NAME))
inum = inode->i_ino;
else if (!memcmp(de->name, MSDOS_DOTDOT, MSDOS_NAME)) {
inum = parent_ino(filp->f_path.dentry);
} else {
loff_t i_pos = fat_make_i_pos(sb, bh, de);
struct inode *tmp = fat_iget(sb, i_pos);
if (tmp) {
inum = tmp->i_ino;
iput(tmp);
} else
inum = iunique(sb, MSDOS_ROOT_INO);
}
if (filldir(dirent, fill_name, fill_len, *furrfu, inum,
(de->attr & ATTR_DIR) ? DT_DIR : DT_REG) < 0)
goto fill_failed;
record_end:
furrfu = &lpos;
filp->f_pos = cpos;
goto get_new;
end_of_dir:
filp->f_pos = cpos;
fill_failed:
brelse(bh);
if (unicode)
__putname(unicode);
out:
unlock_super(sb);
return ret;
}
static int fat_readdir(struct file *filp, void *dirent, filldir_t filldir)
{
struct inode *inode = filp->f_path.dentry->d_inode;
return __fat_readdir(inode, filp, dirent, filldir, 0, 0);
}
#define FAT_IOCTL_FILLDIR_FUNC(func, dirent_type) \
static int func(void *__buf, const char *name, int name_len, \
loff_t offset, u64 ino, unsigned int d_type) \
{ \
struct fat_ioctl_filldir_callback *buf = __buf; \
struct dirent_type __user *d1 = buf->dirent; \
struct dirent_type __user *d2 = d1 + 1; \
\
if (buf->result) \
return -EINVAL; \
buf->result++; \
\
if (name != NULL) { \
/* dirent has only short name */ \
if (name_len >= sizeof(d1->d_name)) \
name_len = sizeof(d1->d_name) - 1; \
\
if (put_user(0, d2->d_name) || \
put_user(0, &d2->d_reclen) || \
copy_to_user(d1->d_name, name, name_len) || \
put_user(0, d1->d_name + name_len) || \
put_user(name_len, &d1->d_reclen)) \
goto efault; \
} else { \
/* dirent has short and long name */ \
const char *longname = buf->longname; \
int long_len = buf->long_len; \
const char *shortname = buf->shortname; \
int short_len = buf->short_len; \
\
if (long_len >= sizeof(d1->d_name)) \
long_len = sizeof(d1->d_name) - 1; \
if (short_len >= sizeof(d1->d_name)) \
short_len = sizeof(d1->d_name) - 1; \
\
if (copy_to_user(d2->d_name, longname, long_len) || \
put_user(0, d2->d_name + long_len) || \
put_user(long_len, &d2->d_reclen) || \
put_user(ino, &d2->d_ino) || \
put_user(offset, &d2->d_off) || \
copy_to_user(d1->d_name, shortname, short_len) || \
put_user(0, d1->d_name + short_len) || \
put_user(short_len, &d1->d_reclen)) \
goto efault; \
} \
return 0; \
efault: \
buf->result = -EFAULT; \
return -EFAULT; \
}
FAT_IOCTL_FILLDIR_FUNC(fat_ioctl_filldir, __fat_dirent)
static int fat_ioctl_readdir(struct inode *inode, struct file *filp,
void __user *dirent, filldir_t filldir,
int short_only, int both)
{
struct fat_ioctl_filldir_callback buf;
int ret;
buf.dirent = dirent;
buf.result = 0;
mutex_lock(&inode->i_mutex);
ret = -ENOENT;
if (!IS_DEADDIR(inode)) {
ret = __fat_readdir(inode, filp, &buf, filldir,
short_only, both);
}
mutex_unlock(&inode->i_mutex);
if (ret >= 0)
ret = buf.result;
return ret;
}
static int fat_ioctl_volume_id(struct inode *dir)
{
struct super_block *sb = dir->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
return sbi->vol_id;
}
static long fat_dir_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct __fat_dirent __user *d1 = (struct __fat_dirent __user *)arg;
int short_only, both;
switch (cmd) {
case VFAT_IOCTL_READDIR_SHORT:
short_only = 1;
both = 0;
break;
case VFAT_IOCTL_READDIR_BOTH:
short_only = 0;
both = 1;
break;
case VFAT_IOCTL_GET_VOLUME_ID:
return fat_ioctl_volume_id(inode);
default:
return fat_generic_ioctl(filp, cmd, arg);
}
if (!access_ok(VERIFY_WRITE, d1, sizeof(struct __fat_dirent[2])))
return -EFAULT;
/*
* Yes, we don't need this put_user() absolutely. However old
* code didn't return the right value. So, app use this value,
* in order to check whether it is EOF.
*/
if (put_user(0, &d1->d_reclen))
return -EFAULT;
return fat_ioctl_readdir(inode, filp, d1, fat_ioctl_filldir,
short_only, both);
}
#ifdef CONFIG_COMPAT
#define VFAT_IOCTL_READDIR_BOTH32 _IOR('r', 1, struct compat_dirent[2])
#define VFAT_IOCTL_READDIR_SHORT32 _IOR('r', 2, struct compat_dirent[2])
FAT_IOCTL_FILLDIR_FUNC(fat_compat_ioctl_filldir, compat_dirent)
static long fat_compat_dir_ioctl(struct file *filp, unsigned cmd,
unsigned long arg)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct compat_dirent __user *d1 = compat_ptr(arg);
int short_only, both;
switch (cmd) {
case VFAT_IOCTL_READDIR_SHORT32:
short_only = 1;
both = 0;
break;
case VFAT_IOCTL_READDIR_BOTH32:
short_only = 0;
both = 1;
break;
default:
return fat_generic_ioctl(filp, cmd, (unsigned long)arg);
}
if (!access_ok(VERIFY_WRITE, d1, sizeof(struct compat_dirent[2])))
return -EFAULT;
/*
* Yes, we don't need this put_user() absolutely. However old
* code didn't return the right value. So, app use this value,
* in order to check whether it is EOF.
*/
if (put_user(0, &d1->d_reclen))
return -EFAULT;
return fat_ioctl_readdir(inode, filp, d1, fat_compat_ioctl_filldir,
short_only, both);
}
#endif /* CONFIG_COMPAT */
const struct file_operations fat_dir_operations = {
.llseek = generic_file_llseek,
.read = generic_read_dir,
.readdir = fat_readdir,
.unlocked_ioctl = fat_dir_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = fat_compat_dir_ioctl,
#endif
.fsync = fat_file_fsync,
};
static int fat_get_short_entry(struct inode *dir, loff_t *pos,
struct buffer_head **bh,
struct msdos_dir_entry **de)
{
while (fat_get_entry(dir, pos, bh, de) >= 0) {
/* free entry or long name entry or volume label */
if (!IS_FREE((*de)->name) && !((*de)->attr & ATTR_VOLUME))
return 0;
}
return -ENOENT;
}
/*
* The ".." entry can not provide the "struct fat_slot_info" informations
* for inode. So, this function provide the some informations only.
*/
int fat_get_dotdot_entry(struct inode *dir, struct buffer_head **bh,
struct msdos_dir_entry **de, loff_t *i_pos)
{
loff_t offset;
offset = 0;
*bh = NULL;
while (fat_get_short_entry(dir, &offset, bh, de) >= 0) {
if (!strncmp((*de)->name, MSDOS_DOTDOT, MSDOS_NAME)) {
*i_pos = fat_make_i_pos(dir->i_sb, *bh, *de);
return 0;
}
}
return -ENOENT;
}
EXPORT_SYMBOL_GPL(fat_get_dotdot_entry);
/* See if directory is empty */
int fat_dir_empty(struct inode *dir)
{
struct buffer_head *bh;
struct msdos_dir_entry *de;
loff_t cpos;
int result = 0;
bh = NULL;
cpos = 0;
while (fat_get_short_entry(dir, &cpos, &bh, &de) >= 0) {
if (strncmp(de->name, MSDOS_DOT , MSDOS_NAME) &&
strncmp(de->name, MSDOS_DOTDOT, MSDOS_NAME)) {
result = -ENOTEMPTY;
break;
}
}
brelse(bh);
return result;
}
EXPORT_SYMBOL_GPL(fat_dir_empty);
/*
* fat_subdirs counts the number of sub-directories of dir. It can be run
* on directories being created.
*/
int fat_subdirs(struct inode *dir)
{
struct buffer_head *bh;
struct msdos_dir_entry *de;
loff_t cpos;
int count = 0;
bh = NULL;
cpos = 0;
while (fat_get_short_entry(dir, &cpos, &bh, &de) >= 0) {
if (de->attr & ATTR_DIR)
count++;
}
brelse(bh);
return count;
}
/*
* Scans a directory for a given file (name points to its formatted name).
* Returns an error code or zero.
*/
int fat_scan(struct inode *dir, const unsigned char *name,
struct fat_slot_info *sinfo)
{
struct super_block *sb = dir->i_sb;
sinfo->slot_off = 0;
sinfo->bh = NULL;
while (fat_get_short_entry(dir, &sinfo->slot_off, &sinfo->bh,
&sinfo->de) >= 0) {
if (!strncmp(sinfo->de->name, name, MSDOS_NAME)) {
sinfo->slot_off -= sizeof(*sinfo->de);
sinfo->nr_slots = 1;
sinfo->i_pos = fat_make_i_pos(sb, sinfo->bh, sinfo->de);
return 0;
}
}
return -ENOENT;
}
EXPORT_SYMBOL_GPL(fat_scan);
static int __fat_remove_entries(struct inode *dir, loff_t pos, int nr_slots)
{
struct super_block *sb = dir->i_sb;
struct buffer_head *bh;
struct msdos_dir_entry *de, *endp;
int err = 0, orig_slots;
while (nr_slots) {
bh = NULL;
if (fat_get_entry(dir, &pos, &bh, &de) < 0) {
err = -EIO;
break;
}
orig_slots = nr_slots;
endp = (struct msdos_dir_entry *)(bh->b_data + sb->s_blocksize);
while (nr_slots && de < endp) {
de->name[0] = DELETED_FLAG;
de++;
nr_slots--;
}
mark_buffer_dirty_inode(bh, dir);
if (IS_DIRSYNC(dir))
err = sync_dirty_buffer(bh);
brelse(bh);
if (err)
break;
/* pos is *next* de's position, so this does `- sizeof(de)' */
pos += ((orig_slots - nr_slots) * sizeof(*de)) - sizeof(*de);
}
return err;
}
int fat_remove_entries(struct inode *dir, struct fat_slot_info *sinfo)
{
struct super_block *sb = dir->i_sb;
struct msdos_dir_entry *de;
struct buffer_head *bh;
int err = 0, nr_slots;
/*
* First stage: Remove the shortname. By this, the directory
* entry is removed.
*/
nr_slots = sinfo->nr_slots;
de = sinfo->de;
sinfo->de = NULL;
bh = sinfo->bh;
sinfo->bh = NULL;
while (nr_slots && de >= (struct msdos_dir_entry *)bh->b_data) {
de->name[0] = DELETED_FLAG;
de--;
nr_slots--;
}
mark_buffer_dirty_inode(bh, dir);
if (IS_DIRSYNC(dir))
err = sync_dirty_buffer(bh);
brelse(bh);
if (err)
return err;
dir->i_version++;
if (nr_slots) {
/*
* Second stage: remove the remaining longname slots.
* (This directory entry is already removed, and so return
* the success)
*/
err = __fat_remove_entries(dir, sinfo->slot_off, nr_slots);
if (err) {
fat_msg(sb, KERN_WARNING,
"Couldn't remove the long name slots");
}
}
dir->i_mtime = dir->i_atime = CURRENT_TIME_SEC;
if (IS_DIRSYNC(dir))
(void)fat_sync_inode(dir);
else
mark_inode_dirty(dir);
return 0;
}
EXPORT_SYMBOL_GPL(fat_remove_entries);
static int fat_zeroed_cluster(struct inode *dir, sector_t blknr, int nr_used,
struct buffer_head **bhs, int nr_bhs)
{
struct super_block *sb = dir->i_sb;
sector_t last_blknr = blknr + MSDOS_SB(sb)->sec_per_clus;
int err, i, n;
/* Zeroing the unused blocks on this cluster */
blknr += nr_used;
n = nr_used;
while (blknr < last_blknr) {
bhs[n] = sb_getblk(sb, blknr);
if (!bhs[n]) {
err = -ENOMEM;
goto error;
}
memset(bhs[n]->b_data, 0, sb->s_blocksize);
set_buffer_uptodate(bhs[n]);
mark_buffer_dirty_inode(bhs[n], dir);
n++;
blknr++;
if (n == nr_bhs) {
if (IS_DIRSYNC(dir)) {
err = fat_sync_bhs(bhs, n);
if (err)
goto error;
}
for (i = 0; i < n; i++)
brelse(bhs[i]);
n = 0;
}
}
if (IS_DIRSYNC(dir)) {
err = fat_sync_bhs(bhs, n);
if (err)
goto error;
}
for (i = 0; i < n; i++)
brelse(bhs[i]);
return 0;
error:
for (i = 0; i < n; i++)
bforget(bhs[i]);
return err;
}
int fat_alloc_new_dir(struct inode *dir, struct timespec *ts)
{
struct super_block *sb = dir->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
struct buffer_head *bhs[MAX_BUF_PER_PAGE];
struct msdos_dir_entry *de;
sector_t blknr;
__le16 date, time;
u8 time_cs;
int err, cluster;
err = fat_alloc_clusters(dir, &cluster, 1);
if (err)
goto error;
blknr = fat_clus_to_blknr(sbi, cluster);
bhs[0] = sb_getblk(sb, blknr);
if (!bhs[0]) {
err = -ENOMEM;
goto error_free;
}
fat_time_unix2fat(sbi, ts, &time, &date, &time_cs);
de = (struct msdos_dir_entry *)bhs[0]->b_data;
/* filling the new directory slots ("." and ".." entries) */
memcpy(de[0].name, MSDOS_DOT, MSDOS_NAME);
memcpy(de[1].name, MSDOS_DOTDOT, MSDOS_NAME);
de->attr = de[1].attr = ATTR_DIR;
de[0].lcase = de[1].lcase = 0;
de[0].time = de[1].time = time;
de[0].date = de[1].date = date;
if (sbi->options.isvfat) {
/* extra timestamps */
de[0].ctime = de[1].ctime = time;
de[0].ctime_cs = de[1].ctime_cs = time_cs;
de[0].adate = de[0].cdate = de[1].adate = de[1].cdate = date;
} else {
de[0].ctime = de[1].ctime = 0;
de[0].ctime_cs = de[1].ctime_cs = 0;
de[0].adate = de[0].cdate = de[1].adate = de[1].cdate = 0;
}
de[0].start = cpu_to_le16(cluster);
de[0].starthi = cpu_to_le16(cluster >> 16);
de[1].start = cpu_to_le16(MSDOS_I(dir)->i_logstart);
de[1].starthi = cpu_to_le16(MSDOS_I(dir)->i_logstart >> 16);
de[0].size = de[1].size = 0;
memset(de + 2, 0, sb->s_blocksize - 2 * sizeof(*de));
set_buffer_uptodate(bhs[0]);
mark_buffer_dirty_inode(bhs[0], dir);
err = fat_zeroed_cluster(dir, blknr, 1, bhs, MAX_BUF_PER_PAGE);
if (err)
goto error_free;
return cluster;
error_free:
fat_free_clusters(dir, cluster);
error:
return err;
}
EXPORT_SYMBOL_GPL(fat_alloc_new_dir);
static int fat_add_new_entries(struct inode *dir, void *slots, int nr_slots,
int *nr_cluster, struct msdos_dir_entry **de,
struct buffer_head **bh, loff_t *i_pos)
{
struct super_block *sb = dir->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
struct buffer_head *bhs[MAX_BUF_PER_PAGE];
sector_t blknr, start_blknr, last_blknr;
unsigned long size, copy;
int err, i, n, offset, cluster[2];
/*
* The minimum cluster size is 512bytes, and maximum entry
* size is 32*slots (672bytes). So, iff the cluster size is
* 512bytes, we may need two clusters.
*/
size = nr_slots * sizeof(struct msdos_dir_entry);
*nr_cluster = (size + (sbi->cluster_size - 1)) >> sbi->cluster_bits;
BUG_ON(*nr_cluster > 2);
err = fat_alloc_clusters(dir, cluster, *nr_cluster);
if (err)
goto error;
/*
* First stage: Fill the directory entry. NOTE: This cluster
* is not referenced from any inode yet, so updates order is
* not important.
*/
i = n = copy = 0;
do {
start_blknr = blknr = fat_clus_to_blknr(sbi, cluster[i]);
last_blknr = start_blknr + sbi->sec_per_clus;
while (blknr < last_blknr) {
bhs[n] = sb_getblk(sb, blknr);
if (!bhs[n]) {
err = -ENOMEM;
goto error_nomem;
}
/* fill the directory entry */
copy = min(size, sb->s_blocksize);
memcpy(bhs[n]->b_data, slots, copy);
slots += copy;
size -= copy;
set_buffer_uptodate(bhs[n]);
mark_buffer_dirty_inode(bhs[n], dir);
if (!size)
break;
n++;
blknr++;
}
} while (++i < *nr_cluster);
memset(bhs[n]->b_data + copy, 0, sb->s_blocksize - copy);
offset = copy - sizeof(struct msdos_dir_entry);
get_bh(bhs[n]);
*bh = bhs[n];
*de = (struct msdos_dir_entry *)((*bh)->b_data + offset);
*i_pos = fat_make_i_pos(sb, *bh, *de);
/* Second stage: clear the rest of cluster, and write outs */
err = fat_zeroed_cluster(dir, start_blknr, ++n, bhs, MAX_BUF_PER_PAGE);
if (err)
goto error_free;
return cluster[0];
error_free:
brelse(*bh);
*bh = NULL;
n = 0;
error_nomem:
for (i = 0; i < n; i++)
bforget(bhs[i]);
fat_free_clusters(dir, cluster[0]);
error:
return err;
}
int fat_add_entries(struct inode *dir, void *slots, int nr_slots,
struct fat_slot_info *sinfo)
{
struct super_block *sb = dir->i_sb;
struct msdos_sb_info *sbi = MSDOS_SB(sb);
struct buffer_head *bh, *prev, *bhs[3]; /* 32*slots (672bytes) */
struct msdos_dir_entry *uninitialized_var(de);
int err, free_slots, i, nr_bhs;
loff_t pos, i_pos;
sinfo->nr_slots = nr_slots;
/* First stage: search free direcotry entries */
free_slots = nr_bhs = 0;
bh = prev = NULL;
pos = 0;
err = -ENOSPC;
while (fat_get_entry(dir, &pos, &bh, &de) > -1) {
/* check the maximum size of directory */
if (pos >= FAT_MAX_DIR_SIZE)
goto error;
if (IS_FREE(de->name)) {
if (prev != bh) {
get_bh(bh);
bhs[nr_bhs] = prev = bh;
nr_bhs++;
}
free_slots++;
if (free_slots == nr_slots)
goto found;
} else {
for (i = 0; i < nr_bhs; i++)
brelse(bhs[i]);
prev = NULL;
free_slots = nr_bhs = 0;
}
}
if (dir->i_ino == MSDOS_ROOT_INO) {
if (sbi->fat_bits != 32)
goto error;
} else if (MSDOS_I(dir)->i_start == 0) {
fat_msg(sb, KERN_ERR, "Corrupted directory (i_pos %lld)",
MSDOS_I(dir)->i_pos);
err = -EIO;
goto error;
}
found:
err = 0;
pos -= free_slots * sizeof(*de);
nr_slots -= free_slots;
if (free_slots) {
/*
* Second stage: filling the free entries with new entries.
* NOTE: If this slots has shortname, first, we write
* the long name slots, then write the short name.
*/
int size = free_slots * sizeof(*de);
int offset = pos & (sb->s_blocksize - 1);
int long_bhs = nr_bhs - (nr_slots == 0);
/* Fill the long name slots. */
for (i = 0; i < long_bhs; i++) {
int copy = min_t(int, sb->s_blocksize - offset, size);
memcpy(bhs[i]->b_data + offset, slots, copy);
mark_buffer_dirty_inode(bhs[i], dir);
offset = 0;
slots += copy;
size -= copy;
}
if (long_bhs && IS_DIRSYNC(dir))
err = fat_sync_bhs(bhs, long_bhs);
if (!err && i < nr_bhs) {
/* Fill the short name slot. */
int copy = min_t(int, sb->s_blocksize - offset, size);
memcpy(bhs[i]->b_data + offset, slots, copy);
mark_buffer_dirty_inode(bhs[i], dir);
if (IS_DIRSYNC(dir))
err = sync_dirty_buffer(bhs[i]);
}
for (i = 0; i < nr_bhs; i++)
brelse(bhs[i]);
if (err)
goto error_remove;
}
if (nr_slots) {
int cluster, nr_cluster;
/*
* Third stage: allocate the cluster for new entries.
* And initialize the cluster with new entries, then
* add the cluster to dir.
*/
cluster = fat_add_new_entries(dir, slots, nr_slots, &nr_cluster,
&de, &bh, &i_pos);
if (cluster < 0) {
err = cluster;
goto error_remove;
}
err = fat_chain_add(dir, cluster, nr_cluster);
if (err) {
fat_free_clusters(dir, cluster);
goto error_remove;
}
if (dir->i_size & (sbi->cluster_size - 1)) {
fat_fs_error(sb, "Odd directory size");
dir->i_size = (dir->i_size + sbi->cluster_size - 1)
& ~((loff_t)sbi->cluster_size - 1);
}
dir->i_size += nr_cluster << sbi->cluster_bits;
MSDOS_I(dir)->mmu_private += nr_cluster << sbi->cluster_bits;
}
sinfo->slot_off = pos;
sinfo->de = de;
sinfo->bh = bh;
sinfo->i_pos = fat_make_i_pos(sb, sinfo->bh, sinfo->de);
return 0;
error:
brelse(bh);
for (i = 0; i < nr_bhs; i++)
brelse(bhs[i]);
return err;
error_remove:
brelse(bh);
if (free_slots)
__fat_remove_entries(dir, pos, free_slots);
return err;
}
EXPORT_SYMBOL_GPL(fat_add_entries);
| gpl-2.0 |
laufersteppenwolf/android_kernel_htc_memul | sound/core/vmaster.c | 3511 | 12431 | /*
* Virtual master and slave controls
*
* Copyright (c) 2008 by Takashi Iwai <tiwai@suse.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*
*/
#include <linux/slab.h>
#include <linux/export.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/tlv.h>
/*
* a subset of information returned via ctl info callback
*/
struct link_ctl_info {
snd_ctl_elem_type_t type; /* value type */
int count; /* item count */
int min_val, max_val; /* min, max values */
};
/*
* link master - this contains a list of slave controls that are
* identical types, i.e. info returns the same value type and value
* ranges, but may have different number of counts.
*
* The master control is so far only mono volume/switch for simplicity.
* The same value will be applied to all slaves.
*/
struct link_master {
struct list_head slaves;
struct link_ctl_info info;
int val; /* the master value */
unsigned int tlv[4];
void (*hook)(void *private_data, int);
void *hook_private_data;
};
/*
* link slave - this contains a slave control element
*
* It fakes the control callbacsk with additional attenuation by the
* master control. A slave may have either one or two channels.
*/
struct link_slave {
struct list_head list;
struct link_master *master;
struct link_ctl_info info;
int vals[2]; /* current values */
unsigned int flags;
struct snd_kcontrol *kctl; /* original kcontrol pointer */
struct snd_kcontrol slave; /* the copy of original control entry */
};
static int slave_update(struct link_slave *slave)
{
struct snd_ctl_elem_value *uctl;
int err, ch;
uctl = kmalloc(sizeof(*uctl), GFP_KERNEL);
if (!uctl)
return -ENOMEM;
uctl->id = slave->slave.id;
err = slave->slave.get(&slave->slave, uctl);
for (ch = 0; ch < slave->info.count; ch++)
slave->vals[ch] = uctl->value.integer.value[ch];
kfree(uctl);
return 0;
}
/* get the slave ctl info and save the initial values */
static int slave_init(struct link_slave *slave)
{
struct snd_ctl_elem_info *uinfo;
int err;
if (slave->info.count) {
/* already initialized */
if (slave->flags & SND_CTL_SLAVE_NEED_UPDATE)
return slave_update(slave);
return 0;
}
uinfo = kmalloc(sizeof(*uinfo), GFP_KERNEL);
if (!uinfo)
return -ENOMEM;
uinfo->id = slave->slave.id;
err = slave->slave.info(&slave->slave, uinfo);
if (err < 0) {
kfree(uinfo);
return err;
}
slave->info.type = uinfo->type;
slave->info.count = uinfo->count;
if (slave->info.count > 2 ||
(slave->info.type != SNDRV_CTL_ELEM_TYPE_INTEGER &&
slave->info.type != SNDRV_CTL_ELEM_TYPE_BOOLEAN)) {
snd_printk(KERN_ERR "invalid slave element\n");
kfree(uinfo);
return -EINVAL;
}
slave->info.min_val = uinfo->value.integer.min;
slave->info.max_val = uinfo->value.integer.max;
kfree(uinfo);
return slave_update(slave);
}
/* initialize master volume */
static int master_init(struct link_master *master)
{
struct link_slave *slave;
if (master->info.count)
return 0; /* already initialized */
list_for_each_entry(slave, &master->slaves, list) {
int err = slave_init(slave);
if (err < 0)
return err;
master->info = slave->info;
master->info.count = 1; /* always mono */
/* set full volume as default (= no attenuation) */
master->val = master->info.max_val;
if (master->hook)
master->hook(master->hook_private_data, master->val);
return 1;
}
return -ENOENT;
}
static int slave_get_val(struct link_slave *slave,
struct snd_ctl_elem_value *ucontrol)
{
int err, ch;
err = slave_init(slave);
if (err < 0)
return err;
for (ch = 0; ch < slave->info.count; ch++)
ucontrol->value.integer.value[ch] = slave->vals[ch];
return 0;
}
static int slave_put_val(struct link_slave *slave,
struct snd_ctl_elem_value *ucontrol)
{
int err, ch, vol;
err = master_init(slave->master);
if (err < 0)
return err;
switch (slave->info.type) {
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
for (ch = 0; ch < slave->info.count; ch++)
ucontrol->value.integer.value[ch] &=
!!slave->master->val;
break;
case SNDRV_CTL_ELEM_TYPE_INTEGER:
for (ch = 0; ch < slave->info.count; ch++) {
/* max master volume is supposed to be 0 dB */
vol = ucontrol->value.integer.value[ch];
vol += slave->master->val - slave->master->info.max_val;
if (vol < slave->info.min_val)
vol = slave->info.min_val;
else if (vol > slave->info.max_val)
vol = slave->info.max_val;
ucontrol->value.integer.value[ch] = vol;
}
break;
}
return slave->slave.put(&slave->slave, ucontrol);
}
/*
* ctl callbacks for slaves
*/
static int slave_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
return slave->slave.info(&slave->slave, uinfo);
}
static int slave_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
return slave_get_val(slave, ucontrol);
}
static int slave_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
int err, ch, changed = 0;
err = slave_init(slave);
if (err < 0)
return err;
for (ch = 0; ch < slave->info.count; ch++) {
if (slave->vals[ch] != ucontrol->value.integer.value[ch]) {
changed = 1;
slave->vals[ch] = ucontrol->value.integer.value[ch];
}
}
if (!changed)
return 0;
return slave_put_val(slave, ucontrol);
}
static int slave_tlv_cmd(struct snd_kcontrol *kcontrol,
int op_flag, unsigned int size,
unsigned int __user *tlv)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
/* FIXME: this assumes that the max volume is 0 dB */
return slave->slave.tlv.c(&slave->slave, op_flag, size, tlv);
}
static void slave_free(struct snd_kcontrol *kcontrol)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
if (slave->slave.private_free)
slave->slave.private_free(&slave->slave);
if (slave->master)
list_del(&slave->list);
kfree(slave);
}
/*
* Add a slave control to the group with the given master control
*
* All slaves must be the same type (returning the same information
* via info callback). The function doesn't check it, so it's your
* responsibility.
*
* Also, some additional limitations:
* - at most two channels
* - logarithmic volume control (dB level), no linear volume
* - master can only attenuate the volume, no gain
*/
int _snd_ctl_add_slave(struct snd_kcontrol *master, struct snd_kcontrol *slave,
unsigned int flags)
{
struct link_master *master_link = snd_kcontrol_chip(master);
struct link_slave *srec;
srec = kzalloc(sizeof(*srec) +
slave->count * sizeof(*slave->vd), GFP_KERNEL);
if (!srec)
return -ENOMEM;
srec->kctl = slave;
srec->slave = *slave;
memcpy(srec->slave.vd, slave->vd, slave->count * sizeof(*slave->vd));
srec->master = master_link;
srec->flags = flags;
/* override callbacks */
slave->info = slave_info;
slave->get = slave_get;
slave->put = slave_put;
if (slave->vd[0].access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK)
slave->tlv.c = slave_tlv_cmd;
slave->private_data = srec;
slave->private_free = slave_free;
list_add_tail(&srec->list, &master_link->slaves);
return 0;
}
EXPORT_SYMBOL(_snd_ctl_add_slave);
/*
* ctl callbacks for master controls
*/
static int master_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
int ret;
ret = master_init(master);
if (ret < 0)
return ret;
uinfo->type = master->info.type;
uinfo->count = master->info.count;
uinfo->value.integer.min = master->info.min_val;
uinfo->value.integer.max = master->info.max_val;
return 0;
}
static int master_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
int err = master_init(master);
if (err < 0)
return err;
ucontrol->value.integer.value[0] = master->val;
return 0;
}
static int master_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
struct link_slave *slave;
struct snd_ctl_elem_value *uval;
int err, old_val;
err = master_init(master);
if (err < 0)
return err;
old_val = master->val;
if (ucontrol->value.integer.value[0] == old_val)
return 0;
uval = kmalloc(sizeof(*uval), GFP_KERNEL);
if (!uval)
return -ENOMEM;
list_for_each_entry(slave, &master->slaves, list) {
master->val = old_val;
uval->id = slave->slave.id;
slave_get_val(slave, uval);
master->val = ucontrol->value.integer.value[0];
slave_put_val(slave, uval);
}
kfree(uval);
if (master->hook && !err)
master->hook(master->hook_private_data, master->val);
return 1;
}
static void master_free(struct snd_kcontrol *kcontrol)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
struct link_slave *slave, *n;
/* free all slave links and retore the original slave kctls */
list_for_each_entry_safe(slave, n, &master->slaves, list) {
struct snd_kcontrol *sctl = slave->kctl;
struct list_head olist = sctl->list;
memcpy(sctl, &slave->slave, sizeof(*sctl));
memcpy(sctl->vd, slave->slave.vd,
sctl->count * sizeof(*sctl->vd));
sctl->list = olist; /* keep the current linked-list */
kfree(slave);
}
kfree(master);
}
/**
* snd_ctl_make_virtual_master - Create a virtual master control
* @name: name string of the control element to create
* @tlv: optional TLV int array for dB information
*
* Creates a virtual matster control with the given name string.
* Returns the created control element, or NULL for errors (ENOMEM).
*
* After creating a vmaster element, you can add the slave controls
* via snd_ctl_add_slave() or snd_ctl_add_slave_uncached().
*
* The optional argument @tlv can be used to specify the TLV information
* for dB scale of the master control. It should be a single element
* with #SNDRV_CTL_TLVT_DB_SCALE, #SNDRV_CTL_TLV_DB_MINMAX or
* #SNDRV_CTL_TLVT_DB_MINMAX_MUTE type, and should be the max 0dB.
*/
struct snd_kcontrol *snd_ctl_make_virtual_master(char *name,
const unsigned int *tlv)
{
struct link_master *master;
struct snd_kcontrol *kctl;
struct snd_kcontrol_new knew;
memset(&knew, 0, sizeof(knew));
knew.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
knew.name = name;
knew.info = master_info;
master = kzalloc(sizeof(*master), GFP_KERNEL);
if (!master)
return NULL;
INIT_LIST_HEAD(&master->slaves);
kctl = snd_ctl_new1(&knew, master);
if (!kctl) {
kfree(master);
return NULL;
}
/* override some callbacks */
kctl->info = master_info;
kctl->get = master_get;
kctl->put = master_put;
kctl->private_free = master_free;
/* additional (constant) TLV read */
if (tlv &&
(tlv[0] == SNDRV_CTL_TLVT_DB_SCALE ||
tlv[0] == SNDRV_CTL_TLVT_DB_MINMAX ||
tlv[0] == SNDRV_CTL_TLVT_DB_MINMAX_MUTE)) {
kctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ;
memcpy(master->tlv, tlv, sizeof(master->tlv));
kctl->tlv.p = master->tlv;
}
return kctl;
}
EXPORT_SYMBOL(snd_ctl_make_virtual_master);
/**
* snd_ctl_add_vmaster_hook - Add a hook to a vmaster control
* @kcontrol: vmaster kctl element
* @hook: the hook function
* @private_data: the private_data pointer to be saved
*
* Adds the given hook to the vmaster control element so that it's called
* at each time when the value is changed.
*/
int snd_ctl_add_vmaster_hook(struct snd_kcontrol *kcontrol,
void (*hook)(void *private_data, int),
void *private_data)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
master->hook = hook;
master->hook_private_data = private_data;
return 0;
}
EXPORT_SYMBOL_GPL(snd_ctl_add_vmaster_hook);
/**
* snd_ctl_sync_vmaster_hook - Sync the vmaster hook
* @kcontrol: vmaster kctl element
*
* Call the hook function to synchronize with the current value of the given
* vmaster element. NOP when NULL is passed to @kcontrol or the hook doesn't
* exist.
*/
void snd_ctl_sync_vmaster_hook(struct snd_kcontrol *kcontrol)
{
struct link_master *master;
if (!kcontrol)
return;
master = snd_kcontrol_chip(kcontrol);
if (master->hook)
master->hook(master->hook_private_data, master->val);
}
EXPORT_SYMBOL_GPL(snd_ctl_sync_vmaster_hook);
| gpl-2.0 |
SaatvikShukla/android_kernel_sony_msm8974 | sound/core/vmaster.c | 3511 | 12431 | /*
* Virtual master and slave controls
*
* Copyright (c) 2008 by Takashi Iwai <tiwai@suse.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2.
*
*/
#include <linux/slab.h>
#include <linux/export.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/tlv.h>
/*
* a subset of information returned via ctl info callback
*/
struct link_ctl_info {
snd_ctl_elem_type_t type; /* value type */
int count; /* item count */
int min_val, max_val; /* min, max values */
};
/*
* link master - this contains a list of slave controls that are
* identical types, i.e. info returns the same value type and value
* ranges, but may have different number of counts.
*
* The master control is so far only mono volume/switch for simplicity.
* The same value will be applied to all slaves.
*/
struct link_master {
struct list_head slaves;
struct link_ctl_info info;
int val; /* the master value */
unsigned int tlv[4];
void (*hook)(void *private_data, int);
void *hook_private_data;
};
/*
* link slave - this contains a slave control element
*
* It fakes the control callbacsk with additional attenuation by the
* master control. A slave may have either one or two channels.
*/
struct link_slave {
struct list_head list;
struct link_master *master;
struct link_ctl_info info;
int vals[2]; /* current values */
unsigned int flags;
struct snd_kcontrol *kctl; /* original kcontrol pointer */
struct snd_kcontrol slave; /* the copy of original control entry */
};
static int slave_update(struct link_slave *slave)
{
struct snd_ctl_elem_value *uctl;
int err, ch;
uctl = kmalloc(sizeof(*uctl), GFP_KERNEL);
if (!uctl)
return -ENOMEM;
uctl->id = slave->slave.id;
err = slave->slave.get(&slave->slave, uctl);
for (ch = 0; ch < slave->info.count; ch++)
slave->vals[ch] = uctl->value.integer.value[ch];
kfree(uctl);
return 0;
}
/* get the slave ctl info and save the initial values */
static int slave_init(struct link_slave *slave)
{
struct snd_ctl_elem_info *uinfo;
int err;
if (slave->info.count) {
/* already initialized */
if (slave->flags & SND_CTL_SLAVE_NEED_UPDATE)
return slave_update(slave);
return 0;
}
uinfo = kmalloc(sizeof(*uinfo), GFP_KERNEL);
if (!uinfo)
return -ENOMEM;
uinfo->id = slave->slave.id;
err = slave->slave.info(&slave->slave, uinfo);
if (err < 0) {
kfree(uinfo);
return err;
}
slave->info.type = uinfo->type;
slave->info.count = uinfo->count;
if (slave->info.count > 2 ||
(slave->info.type != SNDRV_CTL_ELEM_TYPE_INTEGER &&
slave->info.type != SNDRV_CTL_ELEM_TYPE_BOOLEAN)) {
snd_printk(KERN_ERR "invalid slave element\n");
kfree(uinfo);
return -EINVAL;
}
slave->info.min_val = uinfo->value.integer.min;
slave->info.max_val = uinfo->value.integer.max;
kfree(uinfo);
return slave_update(slave);
}
/* initialize master volume */
static int master_init(struct link_master *master)
{
struct link_slave *slave;
if (master->info.count)
return 0; /* already initialized */
list_for_each_entry(slave, &master->slaves, list) {
int err = slave_init(slave);
if (err < 0)
return err;
master->info = slave->info;
master->info.count = 1; /* always mono */
/* set full volume as default (= no attenuation) */
master->val = master->info.max_val;
if (master->hook)
master->hook(master->hook_private_data, master->val);
return 1;
}
return -ENOENT;
}
static int slave_get_val(struct link_slave *slave,
struct snd_ctl_elem_value *ucontrol)
{
int err, ch;
err = slave_init(slave);
if (err < 0)
return err;
for (ch = 0; ch < slave->info.count; ch++)
ucontrol->value.integer.value[ch] = slave->vals[ch];
return 0;
}
static int slave_put_val(struct link_slave *slave,
struct snd_ctl_elem_value *ucontrol)
{
int err, ch, vol;
err = master_init(slave->master);
if (err < 0)
return err;
switch (slave->info.type) {
case SNDRV_CTL_ELEM_TYPE_BOOLEAN:
for (ch = 0; ch < slave->info.count; ch++)
ucontrol->value.integer.value[ch] &=
!!slave->master->val;
break;
case SNDRV_CTL_ELEM_TYPE_INTEGER:
for (ch = 0; ch < slave->info.count; ch++) {
/* max master volume is supposed to be 0 dB */
vol = ucontrol->value.integer.value[ch];
vol += slave->master->val - slave->master->info.max_val;
if (vol < slave->info.min_val)
vol = slave->info.min_val;
else if (vol > slave->info.max_val)
vol = slave->info.max_val;
ucontrol->value.integer.value[ch] = vol;
}
break;
}
return slave->slave.put(&slave->slave, ucontrol);
}
/*
* ctl callbacks for slaves
*/
static int slave_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
return slave->slave.info(&slave->slave, uinfo);
}
static int slave_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
return slave_get_val(slave, ucontrol);
}
static int slave_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
int err, ch, changed = 0;
err = slave_init(slave);
if (err < 0)
return err;
for (ch = 0; ch < slave->info.count; ch++) {
if (slave->vals[ch] != ucontrol->value.integer.value[ch]) {
changed = 1;
slave->vals[ch] = ucontrol->value.integer.value[ch];
}
}
if (!changed)
return 0;
return slave_put_val(slave, ucontrol);
}
static int slave_tlv_cmd(struct snd_kcontrol *kcontrol,
int op_flag, unsigned int size,
unsigned int __user *tlv)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
/* FIXME: this assumes that the max volume is 0 dB */
return slave->slave.tlv.c(&slave->slave, op_flag, size, tlv);
}
static void slave_free(struct snd_kcontrol *kcontrol)
{
struct link_slave *slave = snd_kcontrol_chip(kcontrol);
if (slave->slave.private_free)
slave->slave.private_free(&slave->slave);
if (slave->master)
list_del(&slave->list);
kfree(slave);
}
/*
* Add a slave control to the group with the given master control
*
* All slaves must be the same type (returning the same information
* via info callback). The function doesn't check it, so it's your
* responsibility.
*
* Also, some additional limitations:
* - at most two channels
* - logarithmic volume control (dB level), no linear volume
* - master can only attenuate the volume, no gain
*/
int _snd_ctl_add_slave(struct snd_kcontrol *master, struct snd_kcontrol *slave,
unsigned int flags)
{
struct link_master *master_link = snd_kcontrol_chip(master);
struct link_slave *srec;
srec = kzalloc(sizeof(*srec) +
slave->count * sizeof(*slave->vd), GFP_KERNEL);
if (!srec)
return -ENOMEM;
srec->kctl = slave;
srec->slave = *slave;
memcpy(srec->slave.vd, slave->vd, slave->count * sizeof(*slave->vd));
srec->master = master_link;
srec->flags = flags;
/* override callbacks */
slave->info = slave_info;
slave->get = slave_get;
slave->put = slave_put;
if (slave->vd[0].access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK)
slave->tlv.c = slave_tlv_cmd;
slave->private_data = srec;
slave->private_free = slave_free;
list_add_tail(&srec->list, &master_link->slaves);
return 0;
}
EXPORT_SYMBOL(_snd_ctl_add_slave);
/*
* ctl callbacks for master controls
*/
static int master_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
int ret;
ret = master_init(master);
if (ret < 0)
return ret;
uinfo->type = master->info.type;
uinfo->count = master->info.count;
uinfo->value.integer.min = master->info.min_val;
uinfo->value.integer.max = master->info.max_val;
return 0;
}
static int master_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
int err = master_init(master);
if (err < 0)
return err;
ucontrol->value.integer.value[0] = master->val;
return 0;
}
static int master_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
struct link_slave *slave;
struct snd_ctl_elem_value *uval;
int err, old_val;
err = master_init(master);
if (err < 0)
return err;
old_val = master->val;
if (ucontrol->value.integer.value[0] == old_val)
return 0;
uval = kmalloc(sizeof(*uval), GFP_KERNEL);
if (!uval)
return -ENOMEM;
list_for_each_entry(slave, &master->slaves, list) {
master->val = old_val;
uval->id = slave->slave.id;
slave_get_val(slave, uval);
master->val = ucontrol->value.integer.value[0];
slave_put_val(slave, uval);
}
kfree(uval);
if (master->hook && !err)
master->hook(master->hook_private_data, master->val);
return 1;
}
static void master_free(struct snd_kcontrol *kcontrol)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
struct link_slave *slave, *n;
/* free all slave links and retore the original slave kctls */
list_for_each_entry_safe(slave, n, &master->slaves, list) {
struct snd_kcontrol *sctl = slave->kctl;
struct list_head olist = sctl->list;
memcpy(sctl, &slave->slave, sizeof(*sctl));
memcpy(sctl->vd, slave->slave.vd,
sctl->count * sizeof(*sctl->vd));
sctl->list = olist; /* keep the current linked-list */
kfree(slave);
}
kfree(master);
}
/**
* snd_ctl_make_virtual_master - Create a virtual master control
* @name: name string of the control element to create
* @tlv: optional TLV int array for dB information
*
* Creates a virtual matster control with the given name string.
* Returns the created control element, or NULL for errors (ENOMEM).
*
* After creating a vmaster element, you can add the slave controls
* via snd_ctl_add_slave() or snd_ctl_add_slave_uncached().
*
* The optional argument @tlv can be used to specify the TLV information
* for dB scale of the master control. It should be a single element
* with #SNDRV_CTL_TLVT_DB_SCALE, #SNDRV_CTL_TLV_DB_MINMAX or
* #SNDRV_CTL_TLVT_DB_MINMAX_MUTE type, and should be the max 0dB.
*/
struct snd_kcontrol *snd_ctl_make_virtual_master(char *name,
const unsigned int *tlv)
{
struct link_master *master;
struct snd_kcontrol *kctl;
struct snd_kcontrol_new knew;
memset(&knew, 0, sizeof(knew));
knew.iface = SNDRV_CTL_ELEM_IFACE_MIXER;
knew.name = name;
knew.info = master_info;
master = kzalloc(sizeof(*master), GFP_KERNEL);
if (!master)
return NULL;
INIT_LIST_HEAD(&master->slaves);
kctl = snd_ctl_new1(&knew, master);
if (!kctl) {
kfree(master);
return NULL;
}
/* override some callbacks */
kctl->info = master_info;
kctl->get = master_get;
kctl->put = master_put;
kctl->private_free = master_free;
/* additional (constant) TLV read */
if (tlv &&
(tlv[0] == SNDRV_CTL_TLVT_DB_SCALE ||
tlv[0] == SNDRV_CTL_TLVT_DB_MINMAX ||
tlv[0] == SNDRV_CTL_TLVT_DB_MINMAX_MUTE)) {
kctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ;
memcpy(master->tlv, tlv, sizeof(master->tlv));
kctl->tlv.p = master->tlv;
}
return kctl;
}
EXPORT_SYMBOL(snd_ctl_make_virtual_master);
/**
* snd_ctl_add_vmaster_hook - Add a hook to a vmaster control
* @kcontrol: vmaster kctl element
* @hook: the hook function
* @private_data: the private_data pointer to be saved
*
* Adds the given hook to the vmaster control element so that it's called
* at each time when the value is changed.
*/
int snd_ctl_add_vmaster_hook(struct snd_kcontrol *kcontrol,
void (*hook)(void *private_data, int),
void *private_data)
{
struct link_master *master = snd_kcontrol_chip(kcontrol);
master->hook = hook;
master->hook_private_data = private_data;
return 0;
}
EXPORT_SYMBOL_GPL(snd_ctl_add_vmaster_hook);
/**
* snd_ctl_sync_vmaster_hook - Sync the vmaster hook
* @kcontrol: vmaster kctl element
*
* Call the hook function to synchronize with the current value of the given
* vmaster element. NOP when NULL is passed to @kcontrol or the hook doesn't
* exist.
*/
void snd_ctl_sync_vmaster_hook(struct snd_kcontrol *kcontrol)
{
struct link_master *master;
if (!kcontrol)
return;
master = snd_kcontrol_chip(kcontrol);
if (master->hook)
master->hook(master->hook_private_data, master->val);
}
EXPORT_SYMBOL_GPL(snd_ctl_sync_vmaster_hook);
| gpl-2.0 |
francpalm72/linux-imx_3.10.17 | drivers/ide/slc90e66.c | 4791 | 4950 | /*
* Copyright (C) 2000-2002 Andre Hedrick <andre@linux-ide.org>
* Copyright (C) 2006-2007 MontaVista Software, Inc. <source@mvista.com>
*
* This is a look-alike variation of the ICH0 PIIX4 Ultra-66,
* but this keeps the ISA-Bridge and slots alive.
*
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/ide.h>
#include <linux/init.h>
#define DRV_NAME "slc90e66"
static DEFINE_SPINLOCK(slc90e66_lock);
static void slc90e66_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
int is_slave = drive->dn & 1;
int master_port = hwif->channel ? 0x42 : 0x40;
int slave_port = 0x44;
unsigned long flags;
u16 master_data;
u8 slave_data;
int control = 0;
const u8 pio = drive->pio_mode - XFER_PIO_0;
/* ISP RTC */
static const u8 timings[][2] = {
{ 0, 0 },
{ 0, 0 },
{ 1, 0 },
{ 2, 1 },
{ 2, 3 }, };
spin_lock_irqsave(&slc90e66_lock, flags);
pci_read_config_word(dev, master_port, &master_data);
if (pio > 1)
control |= 1; /* Programmable timing on */
if (drive->media == ide_disk)
control |= 4; /* Prefetch, post write */
if (ide_pio_need_iordy(drive, pio))
control |= 2; /* IORDY */
if (is_slave) {
master_data |= 0x4000;
master_data &= ~0x0070;
if (pio > 1) {
/* Set PPE, IE and TIME */
master_data |= control << 4;
}
pci_read_config_byte(dev, slave_port, &slave_data);
slave_data &= hwif->channel ? 0x0f : 0xf0;
slave_data |= ((timings[pio][0] << 2) | timings[pio][1]) <<
(hwif->channel ? 4 : 0);
} else {
master_data &= ~0x3307;
if (pio > 1) {
/* enable PPE, IE and TIME */
master_data |= control;
}
master_data |= (timings[pio][0] << 12) | (timings[pio][1] << 8);
}
pci_write_config_word(dev, master_port, master_data);
if (is_slave)
pci_write_config_byte(dev, slave_port, slave_data);
spin_unlock_irqrestore(&slc90e66_lock, flags);
}
static void slc90e66_set_dma_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
u8 maslave = hwif->channel ? 0x42 : 0x40;
int sitre = 0, a_speed = 7 << (drive->dn * 4);
int u_speed = 0, u_flag = 1 << drive->dn;
u16 reg4042, reg44, reg48, reg4a;
const u8 speed = drive->dma_mode;
pci_read_config_word(dev, maslave, ®4042);
sitre = (reg4042 & 0x4000) ? 1 : 0;
pci_read_config_word(dev, 0x44, ®44);
pci_read_config_word(dev, 0x48, ®48);
pci_read_config_word(dev, 0x4a, ®4a);
if (speed >= XFER_UDMA_0) {
u_speed = (speed - XFER_UDMA_0) << (drive->dn * 4);
if (!(reg48 & u_flag))
pci_write_config_word(dev, 0x48, reg48|u_flag);
if ((reg4a & a_speed) != u_speed) {
pci_write_config_word(dev, 0x4a, reg4a & ~a_speed);
pci_read_config_word(dev, 0x4a, ®4a);
pci_write_config_word(dev, 0x4a, reg4a|u_speed);
}
} else {
const u8 mwdma_to_pio[] = { 0, 3, 4 };
if (reg48 & u_flag)
pci_write_config_word(dev, 0x48, reg48 & ~u_flag);
if (reg4a & a_speed)
pci_write_config_word(dev, 0x4a, reg4a & ~a_speed);
if (speed >= XFER_MW_DMA_0)
drive->pio_mode =
mwdma_to_pio[speed - XFER_MW_DMA_0] + XFER_PIO_0;
else
drive->pio_mode = XFER_PIO_2; /* for SWDMA2 */
slc90e66_set_pio_mode(hwif, drive);
}
}
static u8 slc90e66_cable_detect(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
u8 reg47 = 0, mask = hwif->channel ? 0x01 : 0x02;
pci_read_config_byte(dev, 0x47, ®47);
/* bit[0(1)]: 0:80, 1:40 */
return (reg47 & mask) ? ATA_CBL_PATA40 : ATA_CBL_PATA80;
}
static const struct ide_port_ops slc90e66_port_ops = {
.set_pio_mode = slc90e66_set_pio_mode,
.set_dma_mode = slc90e66_set_dma_mode,
.cable_detect = slc90e66_cable_detect,
};
static const struct ide_port_info slc90e66_chipset = {
.name = DRV_NAME,
.enablebits = { {0x41, 0x80, 0x80}, {0x43, 0x80, 0x80} },
.port_ops = &slc90e66_port_ops,
.pio_mask = ATA_PIO4,
.swdma_mask = ATA_SWDMA2_ONLY,
.mwdma_mask = ATA_MWDMA12_ONLY,
.udma_mask = ATA_UDMA4,
};
static int slc90e66_init_one(struct pci_dev *dev,
const struct pci_device_id *id)
{
return ide_pci_init_one(dev, &slc90e66_chipset, NULL);
}
static const struct pci_device_id slc90e66_pci_tbl[] = {
{ PCI_VDEVICE(EFAR, PCI_DEVICE_ID_EFAR_SLC90E66_1), 0 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, slc90e66_pci_tbl);
static struct pci_driver slc90e66_pci_driver = {
.name = "SLC90e66_IDE",
.id_table = slc90e66_pci_tbl,
.probe = slc90e66_init_one,
.remove = ide_pci_remove,
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init slc90e66_ide_init(void)
{
return ide_pci_register_driver(&slc90e66_pci_driver);
}
static void __exit slc90e66_ide_exit(void)
{
pci_unregister_driver(&slc90e66_pci_driver);
}
module_init(slc90e66_ide_init);
module_exit(slc90e66_ide_exit);
MODULE_AUTHOR("Andre Hedrick");
MODULE_DESCRIPTION("PCI driver module for SLC90E66 IDE");
MODULE_LICENSE("GPL");
| gpl-2.0 |
meta-debian/linux-ltsi | drivers/ide/rapide.c | 4791 | 2046 | /*
* Copyright (c) 1996-2002 Russell King.
*/
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/errno.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <asm/ecard.h>
static const struct ide_port_info rapide_port_info = {
.host_flags = IDE_HFLAG_MMIO | IDE_HFLAG_NO_DMA,
.chipset = ide_generic,
};
static void rapide_setup_ports(struct ide_hw *hw, void __iomem *base,
void __iomem *ctrl, unsigned int sz, int irq)
{
unsigned long port = (unsigned long)base;
int i;
for (i = 0; i <= 7; i++) {
hw->io_ports_array[i] = port;
port += sz;
}
hw->io_ports.ctl_addr = (unsigned long)ctrl;
hw->irq = irq;
}
static int rapide_probe(struct expansion_card *ec, const struct ecard_id *id)
{
void __iomem *base;
struct ide_host *host;
int ret;
struct ide_hw hw, *hws[] = { &hw };
ret = ecard_request_resources(ec);
if (ret)
goto out;
base = ecardm_iomap(ec, ECARD_RES_MEMC, 0, 0);
if (!base) {
ret = -ENOMEM;
goto release;
}
memset(&hw, 0, sizeof(hw));
rapide_setup_ports(&hw, base, base + 0x818, 1 << 6, ec->irq);
hw.dev = &ec->dev;
ret = ide_host_add(&rapide_port_info, hws, 1, &host);
if (ret)
goto release;
ecard_set_drvdata(ec, host);
goto out;
release:
ecard_release_resources(ec);
out:
return ret;
}
static void rapide_remove(struct expansion_card *ec)
{
struct ide_host *host = ecard_get_drvdata(ec);
ecard_set_drvdata(ec, NULL);
ide_host_remove(host);
ecard_release_resources(ec);
}
static struct ecard_id rapide_ids[] = {
{ MANU_YELLOWSTONE, PROD_YELLOWSTONE_RAPIDE32 },
{ 0xffff, 0xffff }
};
static struct ecard_driver rapide_driver = {
.probe = rapide_probe,
.remove = rapide_remove,
.id_table = rapide_ids,
.drv = {
.name = "rapide",
},
};
static int __init rapide_init(void)
{
return ecard_register_driver(&rapide_driver);
}
static void __exit rapide_exit(void)
{
ecard_remove_driver(&rapide_driver);
}
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Yellowstone RAPIDE driver");
module_init(rapide_init);
module_exit(rapide_exit);
| gpl-2.0 |
cm-mirror/android_kernel_xiaomi_dior | net/decnet/dn_nsp_out.c | 4791 | 17970 |
/*
* DECnet An implementation of the DECnet protocol suite for the LINUX
* operating system. DECnet is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* DECnet Network Services Protocol (Output)
*
* Author: Eduardo Marcelo Serrat <emserrat@geocities.com>
*
* Changes:
*
* Steve Whitehouse: Split into dn_nsp_in.c and dn_nsp_out.c from
* original dn_nsp.c.
* Steve Whitehouse: Updated to work with my new routing architecture.
* Steve Whitehouse: Added changes from Eduardo Serrat's patches.
* Steve Whitehouse: Now conninits have the "return" bit set.
* Steve Whitehouse: Fixes to check alloc'd skbs are non NULL!
* Moved output state machine into one function
* Steve Whitehouse: New output state machine
* Paul Koning: Connect Confirm message fix.
* Eduardo Serrat: Fix to stop dn_nsp_do_disc() sending malformed packets.
* Steve Whitehouse: dn_nsp_output() and friends needed a spring clean
* Steve Whitehouse: Moved dn_nsp_send() in here from route.h
*/
/******************************************************************************
(c) 1995-1998 E.M. Serrat emserrat@geocities.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.
*******************************************************************************/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/inet.h>
#include <linux/route.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/termios.h>
#include <linux/interrupt.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/if_packet.h>
#include <net/neighbour.h>
#include <net/dst.h>
#include <net/flow.h>
#include <net/dn.h>
#include <net/dn_nsp.h>
#include <net/dn_dev.h>
#include <net/dn_route.h>
static int nsp_backoff[NSP_MAXRXTSHIFT + 1] = { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };
static void dn_nsp_send(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
struct dn_scp *scp = DN_SK(sk);
struct dst_entry *dst;
struct flowidn fld;
skb_reset_transport_header(skb);
scp->stamp = jiffies;
dst = sk_dst_check(sk, 0);
if (dst) {
try_again:
skb_dst_set(skb, dst);
dst_output(skb);
return;
}
memset(&fld, 0, sizeof(fld));
fld.flowidn_oif = sk->sk_bound_dev_if;
fld.saddr = dn_saddr2dn(&scp->addr);
fld.daddr = dn_saddr2dn(&scp->peer);
dn_sk_ports_copy(&fld, scp);
fld.flowidn_proto = DNPROTO_NSP;
if (dn_route_output_sock(&sk->sk_dst_cache, &fld, sk, 0) == 0) {
dst = sk_dst_get(sk);
sk->sk_route_caps = dst->dev->features;
goto try_again;
}
sk->sk_err = EHOSTUNREACH;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_state_change(sk);
}
/*
* If sk == NULL, then we assume that we are supposed to be making
* a routing layer skb. If sk != NULL, then we are supposed to be
* creating an skb for the NSP layer.
*
* The eventual aim is for each socket to have a cached header size
* for its outgoing packets, and to set hdr from this when sk != NULL.
*/
struct sk_buff *dn_alloc_skb(struct sock *sk, int size, gfp_t pri)
{
struct sk_buff *skb;
int hdr = 64;
if ((skb = alloc_skb(size + hdr, pri)) == NULL)
return NULL;
skb->protocol = htons(ETH_P_DNA_RT);
skb->pkt_type = PACKET_OUTGOING;
if (sk)
skb_set_owner_w(skb, sk);
skb_reserve(skb, hdr);
return skb;
}
/*
* Calculate persist timer based upon the smoothed round
* trip time and the variance. Backoff according to the
* nsp_backoff[] array.
*/
unsigned long dn_nsp_persist(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
unsigned long t = ((scp->nsp_srtt >> 2) + scp->nsp_rttvar) >> 1;
t *= nsp_backoff[scp->nsp_rxtshift];
if (t < HZ) t = HZ;
if (t > (600*HZ)) t = (600*HZ);
if (scp->nsp_rxtshift < NSP_MAXRXTSHIFT)
scp->nsp_rxtshift++;
/* printk(KERN_DEBUG "rxtshift %lu, t=%lu\n", scp->nsp_rxtshift, t); */
return t;
}
/*
* This is called each time we get an estimate for the rtt
* on the link.
*/
static void dn_nsp_rtt(struct sock *sk, long rtt)
{
struct dn_scp *scp = DN_SK(sk);
long srtt = (long)scp->nsp_srtt;
long rttvar = (long)scp->nsp_rttvar;
long delta;
/*
* If the jiffies clock flips over in the middle of timestamp
* gathering this value might turn out negative, so we make sure
* that is it always positive here.
*/
if (rtt < 0)
rtt = -rtt;
/*
* Add new rtt to smoothed average
*/
delta = ((rtt << 3) - srtt);
srtt += (delta >> 3);
if (srtt >= 1)
scp->nsp_srtt = (unsigned long)srtt;
else
scp->nsp_srtt = 1;
/*
* Add new rtt varience to smoothed varience
*/
delta >>= 1;
rttvar += ((((delta>0)?(delta):(-delta)) - rttvar) >> 2);
if (rttvar >= 1)
scp->nsp_rttvar = (unsigned long)rttvar;
else
scp->nsp_rttvar = 1;
/* printk(KERN_DEBUG "srtt=%lu rttvar=%lu\n", scp->nsp_srtt, scp->nsp_rttvar); */
}
/**
* dn_nsp_clone_and_send - Send a data packet by cloning it
* @skb: The packet to clone and transmit
* @gfp: memory allocation flag
*
* Clone a queued data or other data packet and transmit it.
*
* Returns: The number of times the packet has been sent previously
*/
static inline unsigned dn_nsp_clone_and_send(struct sk_buff *skb,
gfp_t gfp)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
struct sk_buff *skb2;
int ret = 0;
if ((skb2 = skb_clone(skb, gfp)) != NULL) {
ret = cb->xmit_count;
cb->xmit_count++;
cb->stamp = jiffies;
skb2->sk = skb->sk;
dn_nsp_send(skb2);
}
return ret;
}
/**
* dn_nsp_output - Try and send something from socket queues
* @sk: The socket whose queues are to be investigated
*
* Try and send the packet on the end of the data and other data queues.
* Other data gets priority over data, and if we retransmit a packet we
* reduce the window by dividing it in two.
*
*/
void dn_nsp_output(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb;
unsigned reduce_win = 0;
/*
* First we check for otherdata/linkservice messages
*/
if ((skb = skb_peek(&scp->other_xmit_queue)) != NULL)
reduce_win = dn_nsp_clone_and_send(skb, GFP_ATOMIC);
/*
* If we may not send any data, we don't.
* If we are still trying to get some other data down the
* channel, we don't try and send any data.
*/
if (reduce_win || (scp->flowrem_sw != DN_SEND))
goto recalc_window;
if ((skb = skb_peek(&scp->data_xmit_queue)) != NULL)
reduce_win = dn_nsp_clone_and_send(skb, GFP_ATOMIC);
/*
* If we've sent any frame more than once, we cut the
* send window size in half. There is always a minimum
* window size of one available.
*/
recalc_window:
if (reduce_win) {
scp->snd_window >>= 1;
if (scp->snd_window < NSP_MIN_WINDOW)
scp->snd_window = NSP_MIN_WINDOW;
}
}
int dn_nsp_xmit_timeout(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
dn_nsp_output(sk);
if (!skb_queue_empty(&scp->data_xmit_queue) ||
!skb_queue_empty(&scp->other_xmit_queue))
scp->persist = dn_nsp_persist(sk);
return 0;
}
static inline __le16 *dn_mk_common_header(struct dn_scp *scp, struct sk_buff *skb, unsigned char msgflag, int len)
{
unsigned char *ptr = skb_push(skb, len);
BUG_ON(len < 5);
*ptr++ = msgflag;
*((__le16 *)ptr) = scp->addrrem;
ptr += 2;
*((__le16 *)ptr) = scp->addrloc;
ptr += 2;
return (__le16 __force *)ptr;
}
static __le16 *dn_mk_ack_header(struct sock *sk, struct sk_buff *skb, unsigned char msgflag, int hlen, int other)
{
struct dn_scp *scp = DN_SK(sk);
unsigned short acknum = scp->numdat_rcv & 0x0FFF;
unsigned short ackcrs = scp->numoth_rcv & 0x0FFF;
__le16 *ptr;
BUG_ON(hlen < 9);
scp->ackxmt_dat = acknum;
scp->ackxmt_oth = ackcrs;
acknum |= 0x8000;
ackcrs |= 0x8000;
/* If this is an "other data/ack" message, swap acknum and ackcrs */
if (other) {
unsigned short tmp = acknum;
acknum = ackcrs;
ackcrs = tmp;
}
/* Set "cross subchannel" bit in ackcrs */
ackcrs |= 0x2000;
ptr = (__le16 *)dn_mk_common_header(scp, skb, msgflag, hlen);
*ptr++ = cpu_to_le16(acknum);
*ptr++ = cpu_to_le16(ackcrs);
return ptr;
}
static __le16 *dn_nsp_mk_data_header(struct sock *sk, struct sk_buff *skb, int oth)
{
struct dn_scp *scp = DN_SK(sk);
struct dn_skb_cb *cb = DN_SKB_CB(skb);
__le16 *ptr = dn_mk_ack_header(sk, skb, cb->nsp_flags, 11, oth);
if (unlikely(oth)) {
cb->segnum = scp->numoth;
seq_add(&scp->numoth, 1);
} else {
cb->segnum = scp->numdat;
seq_add(&scp->numdat, 1);
}
*(ptr++) = cpu_to_le16(cb->segnum);
return ptr;
}
void dn_nsp_queue_xmit(struct sock *sk, struct sk_buff *skb,
gfp_t gfp, int oth)
{
struct dn_scp *scp = DN_SK(sk);
struct dn_skb_cb *cb = DN_SKB_CB(skb);
unsigned long t = ((scp->nsp_srtt >> 2) + scp->nsp_rttvar) >> 1;
cb->xmit_count = 0;
dn_nsp_mk_data_header(sk, skb, oth);
/*
* Slow start: If we have been idle for more than
* one RTT, then reset window to min size.
*/
if ((jiffies - scp->stamp) > t)
scp->snd_window = NSP_MIN_WINDOW;
if (oth)
skb_queue_tail(&scp->other_xmit_queue, skb);
else
skb_queue_tail(&scp->data_xmit_queue, skb);
if (scp->flowrem_sw != DN_SEND)
return;
dn_nsp_clone_and_send(skb, gfp);
}
int dn_nsp_check_xmit_queue(struct sock *sk, struct sk_buff *skb, struct sk_buff_head *q, unsigned short acknum)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb2, *n, *ack = NULL;
int wakeup = 0;
int try_retrans = 0;
unsigned long reftime = cb->stamp;
unsigned long pkttime;
unsigned short xmit_count;
unsigned short segnum;
skb_queue_walk_safe(q, skb2, n) {
struct dn_skb_cb *cb2 = DN_SKB_CB(skb2);
if (dn_before_or_equal(cb2->segnum, acknum))
ack = skb2;
/* printk(KERN_DEBUG "ack: %s %04x %04x\n", ack ? "ACK" : "SKIP", (int)cb2->segnum, (int)acknum); */
if (ack == NULL)
continue;
/* printk(KERN_DEBUG "check_xmit_queue: %04x, %d\n", acknum, cb2->xmit_count); */
/* Does _last_ packet acked have xmit_count > 1 */
try_retrans = 0;
/* Remember to wake up the sending process */
wakeup = 1;
/* Keep various statistics */
pkttime = cb2->stamp;
xmit_count = cb2->xmit_count;
segnum = cb2->segnum;
/* Remove and drop ack'ed packet */
skb_unlink(ack, q);
kfree_skb(ack);
ack = NULL;
/*
* We don't expect to see acknowledgements for packets we
* haven't sent yet.
*/
WARN_ON(xmit_count == 0);
/*
* If the packet has only been sent once, we can use it
* to calculate the RTT and also open the window a little
* further.
*/
if (xmit_count == 1) {
if (dn_equal(segnum, acknum))
dn_nsp_rtt(sk, (long)(pkttime - reftime));
if (scp->snd_window < scp->max_window)
scp->snd_window++;
}
/*
* Packet has been sent more than once. If this is the last
* packet to be acknowledged then we want to send the next
* packet in the send queue again (assumes the remote host does
* go-back-N error control).
*/
if (xmit_count > 1)
try_retrans = 1;
}
if (try_retrans)
dn_nsp_output(sk);
return wakeup;
}
void dn_nsp_send_data_ack(struct sock *sk)
{
struct sk_buff *skb = NULL;
if ((skb = dn_alloc_skb(sk, 9, GFP_ATOMIC)) == NULL)
return;
skb_reserve(skb, 9);
dn_mk_ack_header(sk, skb, 0x04, 9, 0);
dn_nsp_send(skb);
}
void dn_nsp_send_oth_ack(struct sock *sk)
{
struct sk_buff *skb = NULL;
if ((skb = dn_alloc_skb(sk, 9, GFP_ATOMIC)) == NULL)
return;
skb_reserve(skb, 9);
dn_mk_ack_header(sk, skb, 0x14, 9, 1);
dn_nsp_send(skb);
}
void dn_send_conn_ack (struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb = NULL;
struct nsp_conn_ack_msg *msg;
if ((skb = dn_alloc_skb(sk, 3, sk->sk_allocation)) == NULL)
return;
msg = (struct nsp_conn_ack_msg *)skb_put(skb, 3);
msg->msgflg = 0x24;
msg->dstaddr = scp->addrrem;
dn_nsp_send(skb);
}
void dn_nsp_delayed_ack(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
if (scp->ackxmt_oth != scp->numoth_rcv)
dn_nsp_send_oth_ack(sk);
if (scp->ackxmt_dat != scp->numdat_rcv)
dn_nsp_send_data_ack(sk);
}
static int dn_nsp_retrans_conn_conf(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
if (scp->state == DN_CC)
dn_send_conn_conf(sk, GFP_ATOMIC);
return 0;
}
void dn_send_conn_conf(struct sock *sk, gfp_t gfp)
{
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb = NULL;
struct nsp_conn_init_msg *msg;
__u8 len = (__u8)le16_to_cpu(scp->conndata_out.opt_optl);
if ((skb = dn_alloc_skb(sk, 50 + len, gfp)) == NULL)
return;
msg = (struct nsp_conn_init_msg *)skb_put(skb, sizeof(*msg));
msg->msgflg = 0x28;
msg->dstaddr = scp->addrrem;
msg->srcaddr = scp->addrloc;
msg->services = scp->services_loc;
msg->info = scp->info_loc;
msg->segsize = cpu_to_le16(scp->segsize_loc);
*skb_put(skb,1) = len;
if (len > 0)
memcpy(skb_put(skb, len), scp->conndata_out.opt_data, len);
dn_nsp_send(skb);
scp->persist = dn_nsp_persist(sk);
scp->persist_fxn = dn_nsp_retrans_conn_conf;
}
static __inline__ void dn_nsp_do_disc(struct sock *sk, unsigned char msgflg,
unsigned short reason, gfp_t gfp,
struct dst_entry *dst,
int ddl, unsigned char *dd, __le16 rem, __le16 loc)
{
struct sk_buff *skb = NULL;
int size = 7 + ddl + ((msgflg == NSP_DISCINIT) ? 1 : 0);
unsigned char *msg;
if ((dst == NULL) || (rem == 0)) {
if (net_ratelimit())
printk(KERN_DEBUG "DECnet: dn_nsp_do_disc: BUG! Please report this to SteveW@ACM.org rem=%u dst=%p\n", le16_to_cpu(rem), dst);
return;
}
if ((skb = dn_alloc_skb(sk, size, gfp)) == NULL)
return;
msg = skb_put(skb, size);
*msg++ = msgflg;
*(__le16 *)msg = rem;
msg += 2;
*(__le16 *)msg = loc;
msg += 2;
*(__le16 *)msg = cpu_to_le16(reason);
msg += 2;
if (msgflg == NSP_DISCINIT)
*msg++ = ddl;
if (ddl) {
memcpy(msg, dd, ddl);
}
/*
* This doesn't go via the dn_nsp_send() function since we need
* to be able to send disc packets out which have no socket
* associations.
*/
skb_dst_set(skb, dst_clone(dst));
dst_output(skb);
}
void dn_nsp_send_disc(struct sock *sk, unsigned char msgflg,
unsigned short reason, gfp_t gfp)
{
struct dn_scp *scp = DN_SK(sk);
int ddl = 0;
if (msgflg == NSP_DISCINIT)
ddl = le16_to_cpu(scp->discdata_out.opt_optl);
if (reason == 0)
reason = le16_to_cpu(scp->discdata_out.opt_status);
dn_nsp_do_disc(sk, msgflg, reason, gfp, sk->sk_dst_cache, ddl,
scp->discdata_out.opt_data, scp->addrrem, scp->addrloc);
}
void dn_nsp_return_disc(struct sk_buff *skb, unsigned char msgflg,
unsigned short reason)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
int ddl = 0;
gfp_t gfp = GFP_ATOMIC;
dn_nsp_do_disc(NULL, msgflg, reason, gfp, skb_dst(skb), ddl,
NULL, cb->src_port, cb->dst_port);
}
void dn_nsp_send_link(struct sock *sk, unsigned char lsflags, char fcval)
{
struct dn_scp *scp = DN_SK(sk);
struct sk_buff *skb;
unsigned char *ptr;
gfp_t gfp = GFP_ATOMIC;
if ((skb = dn_alloc_skb(sk, DN_MAX_NSP_DATA_HEADER + 2, gfp)) == NULL)
return;
skb_reserve(skb, DN_MAX_NSP_DATA_HEADER);
ptr = skb_put(skb, 2);
DN_SKB_CB(skb)->nsp_flags = 0x10;
*ptr++ = lsflags;
*ptr = fcval;
dn_nsp_queue_xmit(sk, skb, gfp, 1);
scp->persist = dn_nsp_persist(sk);
scp->persist_fxn = dn_nsp_xmit_timeout;
}
static int dn_nsp_retrans_conninit(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
if (scp->state == DN_CI)
dn_nsp_send_conninit(sk, NSP_RCI);
return 0;
}
void dn_nsp_send_conninit(struct sock *sk, unsigned char msgflg)
{
struct dn_scp *scp = DN_SK(sk);
struct nsp_conn_init_msg *msg;
unsigned char aux;
unsigned char menuver;
struct dn_skb_cb *cb;
unsigned char type = 1;
gfp_t allocation = (msgflg == NSP_CI) ? sk->sk_allocation : GFP_ATOMIC;
struct sk_buff *skb = dn_alloc_skb(sk, 200, allocation);
if (!skb)
return;
cb = DN_SKB_CB(skb);
msg = (struct nsp_conn_init_msg *)skb_put(skb,sizeof(*msg));
msg->msgflg = msgflg;
msg->dstaddr = 0x0000; /* Remote Node will assign it*/
msg->srcaddr = scp->addrloc;
msg->services = scp->services_loc; /* Requested flow control */
msg->info = scp->info_loc; /* Version Number */
msg->segsize = cpu_to_le16(scp->segsize_loc); /* Max segment size */
if (scp->peer.sdn_objnum)
type = 0;
skb_put(skb, dn_sockaddr2username(&scp->peer,
skb_tail_pointer(skb), type));
skb_put(skb, dn_sockaddr2username(&scp->addr,
skb_tail_pointer(skb), 2));
menuver = DN_MENUVER_ACC | DN_MENUVER_USR;
if (scp->peer.sdn_flags & SDF_PROXY)
menuver |= DN_MENUVER_PRX;
if (scp->peer.sdn_flags & SDF_UICPROXY)
menuver |= DN_MENUVER_UIC;
*skb_put(skb, 1) = menuver; /* Menu Version */
aux = scp->accessdata.acc_userl;
*skb_put(skb, 1) = aux;
if (aux > 0)
memcpy(skb_put(skb, aux), scp->accessdata.acc_user, aux);
aux = scp->accessdata.acc_passl;
*skb_put(skb, 1) = aux;
if (aux > 0)
memcpy(skb_put(skb, aux), scp->accessdata.acc_pass, aux);
aux = scp->accessdata.acc_accl;
*skb_put(skb, 1) = aux;
if (aux > 0)
memcpy(skb_put(skb, aux), scp->accessdata.acc_acc, aux);
aux = (__u8)le16_to_cpu(scp->conndata_out.opt_optl);
*skb_put(skb, 1) = aux;
if (aux > 0)
memcpy(skb_put(skb, aux), scp->conndata_out.opt_data, aux);
scp->persist = dn_nsp_persist(sk);
scp->persist_fxn = dn_nsp_retrans_conninit;
cb->rt_flags = DN_RT_F_RQR;
dn_nsp_send(skb);
}
| gpl-2.0 |
hiikezoe/android_kernel_stm_st3200 | drivers/net/wireless/orinoco/spectrum_cs.c | 5815 | 8775 | /*
* Driver for 802.11b cards using RAM-loadable Symbol firmware, such as
* Symbol Wireless Networker LA4137, CompactFlash cards by Socket
* Communications and Intel PRO/Wireless 2011B.
*
* The driver implements Symbol firmware download. The rest is handled
* in hermes.c and main.c.
*
* Utilities for downloading the Symbol firmware are available at
* http://sourceforge.net/projects/orinoco/
*
* Copyright (C) 2002-2005 Pavel Roskin <proski@gnu.org>
* Portions based on orinoco_cs.c:
* Copyright (C) David Gibson, Linuxcare Australia
* Portions based on Spectrum24tDnld.c from original spectrum24 driver:
* Copyright (C) Symbol Technologies.
*
* See copyright notice in file main.c.
*/
#define DRIVER_NAME "spectrum_cs"
#define PFX DRIVER_NAME ": "
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
#include "orinoco.h"
/********************************************************************/
/* Module stuff */
/********************************************************************/
MODULE_AUTHOR("Pavel Roskin <proski@gnu.org>");
MODULE_DESCRIPTION("Driver for Symbol Spectrum24 Trilogy cards with firmware downloader");
MODULE_LICENSE("Dual MPL/GPL");
/* Module parameters */
/* Some D-Link cards have buggy CIS. They do work at 5v properly, but
* don't have any CIS entry for it. This workaround it... */
static int ignore_cis_vcc; /* = 0 */
module_param(ignore_cis_vcc, int, 0);
MODULE_PARM_DESC(ignore_cis_vcc, "Allow voltage mismatch between card and socket");
/********************************************************************/
/* Data structures */
/********************************************************************/
/* PCMCIA specific device information (goes in the card field of
* struct orinoco_private */
struct orinoco_pccard {
struct pcmcia_device *p_dev;
};
/********************************************************************/
/* Function prototypes */
/********************************************************************/
static int spectrum_cs_config(struct pcmcia_device *link);
static void spectrum_cs_release(struct pcmcia_device *link);
/* Constants for the CISREG_CCSR register */
#define HCR_RUN 0x07 /* run firmware after reset */
#define HCR_IDLE 0x0E /* don't run firmware after reset */
#define HCR_MEM16 0x10 /* memory width bit, should be preserved */
/*
* Reset the card using configuration registers COR and CCSR.
* If IDLE is 1, stop the firmware, so that it can be safely rewritten.
*/
static int
spectrum_reset(struct pcmcia_device *link, int idle)
{
int ret;
u8 save_cor;
u8 ccsr;
/* Doing it if hardware is gone is guaranteed crash */
if (!pcmcia_dev_present(link))
return -ENODEV;
/* Save original COR value */
ret = pcmcia_read_config_byte(link, CISREG_COR, &save_cor);
if (ret)
goto failed;
/* Soft-Reset card */
ret = pcmcia_write_config_byte(link, CISREG_COR,
(save_cor | COR_SOFT_RESET));
if (ret)
goto failed;
udelay(1000);
/* Read CCSR */
ret = pcmcia_read_config_byte(link, CISREG_CCSR, &ccsr);
if (ret)
goto failed;
/*
* Start or stop the firmware. Memory width bit should be
* preserved from the value we've just read.
*/
ccsr = (idle ? HCR_IDLE : HCR_RUN) | (ccsr & HCR_MEM16);
ret = pcmcia_write_config_byte(link, CISREG_CCSR, ccsr);
if (ret)
goto failed;
udelay(1000);
/* Restore original COR configuration index */
ret = pcmcia_write_config_byte(link, CISREG_COR,
(save_cor & ~COR_SOFT_RESET));
if (ret)
goto failed;
udelay(1000);
return 0;
failed:
return -ENODEV;
}
/********************************************************************/
/* Device methods */
/********************************************************************/
static int
spectrum_cs_hard_reset(struct orinoco_private *priv)
{
struct orinoco_pccard *card = priv->card;
struct pcmcia_device *link = card->p_dev;
/* Soft reset using COR and HCR */
spectrum_reset(link, 0);
return 0;
}
static int
spectrum_cs_stop_firmware(struct orinoco_private *priv, int idle)
{
struct orinoco_pccard *card = priv->card;
struct pcmcia_device *link = card->p_dev;
return spectrum_reset(link, idle);
}
/********************************************************************/
/* PCMCIA stuff */
/********************************************************************/
static int
spectrum_cs_probe(struct pcmcia_device *link)
{
struct orinoco_private *priv;
struct orinoco_pccard *card;
priv = alloc_orinocodev(sizeof(*card), &link->dev,
spectrum_cs_hard_reset,
spectrum_cs_stop_firmware);
if (!priv)
return -ENOMEM;
card = priv->card;
/* Link both structures together */
card->p_dev = link;
link->priv = priv;
return spectrum_cs_config(link);
} /* spectrum_cs_attach */
static void spectrum_cs_detach(struct pcmcia_device *link)
{
struct orinoco_private *priv = link->priv;
orinoco_if_del(priv);
spectrum_cs_release(link);
free_orinocodev(priv);
} /* spectrum_cs_detach */
static int spectrum_cs_config_check(struct pcmcia_device *p_dev,
void *priv_data)
{
if (p_dev->config_index == 0)
return -EINVAL;
return pcmcia_request_io(p_dev);
};
static int
spectrum_cs_config(struct pcmcia_device *link)
{
struct orinoco_private *priv = link->priv;
struct hermes *hw = &priv->hw;
int ret;
void __iomem *mem;
link->config_flags |= CONF_AUTO_SET_VPP | CONF_AUTO_CHECK_VCC |
CONF_AUTO_SET_IO | CONF_ENABLE_IRQ;
if (ignore_cis_vcc)
link->config_flags &= ~CONF_AUTO_CHECK_VCC;
ret = pcmcia_loop_config(link, spectrum_cs_config_check, NULL);
if (ret) {
if (!ignore_cis_vcc)
printk(KERN_ERR PFX "GetNextTuple(): No matching "
"CIS configuration. Maybe you need the "
"ignore_cis_vcc=1 parameter.\n");
goto failed;
}
mem = ioport_map(link->resource[0]->start,
resource_size(link->resource[0]));
if (!mem)
goto failed;
/* We initialize the hermes structure before completing PCMCIA
* configuration just in case the interrupt handler gets
* called. */
hermes_struct_init(hw, mem, HERMES_16BIT_REGSPACING);
hw->eeprom_pda = true;
ret = pcmcia_request_irq(link, orinoco_interrupt);
if (ret)
goto failed;
ret = pcmcia_enable_device(link);
if (ret)
goto failed;
/* Reset card */
if (spectrum_cs_hard_reset(priv) != 0)
goto failed;
/* Initialise the main driver */
if (orinoco_init(priv) != 0) {
printk(KERN_ERR PFX "orinoco_init() failed\n");
goto failed;
}
/* Register an interface with the stack */
if (orinoco_if_add(priv, link->resource[0]->start,
link->irq, NULL) != 0) {
printk(KERN_ERR PFX "orinoco_if_add() failed\n");
goto failed;
}
return 0;
failed:
spectrum_cs_release(link);
return -ENODEV;
} /* spectrum_cs_config */
static void
spectrum_cs_release(struct pcmcia_device *link)
{
struct orinoco_private *priv = link->priv;
unsigned long flags;
/* We're committed to taking the device away now, so mark the
* hardware as unavailable */
priv->hw.ops->lock_irqsave(&priv->lock, &flags);
priv->hw_unavailable++;
priv->hw.ops->unlock_irqrestore(&priv->lock, &flags);
pcmcia_disable_device(link);
if (priv->hw.iobase)
ioport_unmap(priv->hw.iobase);
} /* spectrum_cs_release */
static int
spectrum_cs_suspend(struct pcmcia_device *link)
{
struct orinoco_private *priv = link->priv;
int err = 0;
/* Mark the device as stopped, to block IO until later */
orinoco_down(priv);
return err;
}
static int
spectrum_cs_resume(struct pcmcia_device *link)
{
struct orinoco_private *priv = link->priv;
int err = orinoco_up(priv);
return err;
}
/********************************************************************/
/* Module initialization */
/********************************************************************/
static const struct pcmcia_device_id spectrum_cs_ids[] = {
PCMCIA_DEVICE_MANF_CARD(0x026c, 0x0001), /* Symbol Spectrum24 LA4137 */
PCMCIA_DEVICE_MANF_CARD(0x0104, 0x0001), /* Socket Communications CF */
PCMCIA_DEVICE_PROD_ID12("Intel", "PRO/Wireless LAN PC Card", 0x816cc815, 0x6fbf459a), /* 2011B, not 2011 */
PCMCIA_DEVICE_NULL,
};
MODULE_DEVICE_TABLE(pcmcia, spectrum_cs_ids);
static struct pcmcia_driver orinoco_driver = {
.owner = THIS_MODULE,
.name = DRIVER_NAME,
.probe = spectrum_cs_probe,
.remove = spectrum_cs_detach,
.suspend = spectrum_cs_suspend,
.resume = spectrum_cs_resume,
.id_table = spectrum_cs_ids,
};
static int __init
init_spectrum_cs(void)
{
return pcmcia_register_driver(&orinoco_driver);
}
static void __exit
exit_spectrum_cs(void)
{
pcmcia_unregister_driver(&orinoco_driver);
}
module_init(init_spectrum_cs);
module_exit(exit_spectrum_cs);
| gpl-2.0 |
mifl/android_kernel_pantech_ef34k | drivers/mfd/wm831x-otp.c | 6583 | 1893 | /*
* wm831x-otp.c -- OTP for Wolfson WM831x PMICs
*
* Copyright 2009 Wolfson Microelectronics PLC.
*
* Author: Mark Brown <broonie@opensource.wolfsonmicro.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License 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/i2c.h>
#include <linux/bcd.h>
#include <linux/delay.h>
#include <linux/mfd/core.h>
#include <linux/mfd/wm831x/core.h>
#include <linux/mfd/wm831x/otp.h>
/* In bytes */
#define WM831X_UNIQUE_ID_LEN 16
/* Read the unique ID from the chip into id */
static int wm831x_unique_id_read(struct wm831x *wm831x, char *id)
{
int i, val;
for (i = 0; i < WM831X_UNIQUE_ID_LEN / 2; i++) {
val = wm831x_reg_read(wm831x, WM831X_UNIQUE_ID_1 + i);
if (val < 0)
return val;
id[i * 2] = (val >> 8) & 0xff;
id[(i * 2) + 1] = val & 0xff;
}
return 0;
}
static ssize_t wm831x_unique_id_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct wm831x *wm831x = dev_get_drvdata(dev);
int i, rval;
char id[WM831X_UNIQUE_ID_LEN];
ssize_t ret = 0;
rval = wm831x_unique_id_read(wm831x, id);
if (rval < 0)
return 0;
for (i = 0; i < WM831X_UNIQUE_ID_LEN; i++)
ret += sprintf(&buf[ret], "%02x", buf[i]);
ret += sprintf(&buf[ret], "\n");
return ret;
}
static DEVICE_ATTR(unique_id, 0444, wm831x_unique_id_show, NULL);
int wm831x_otp_init(struct wm831x *wm831x)
{
int ret;
ret = device_create_file(wm831x->dev, &dev_attr_unique_id);
if (ret != 0)
dev_err(wm831x->dev, "Unique ID attribute not created: %d\n",
ret);
return ret;
}
void wm831x_otp_exit(struct wm831x *wm831x)
{
device_remove_file(wm831x->dev, &dev_attr_unique_id);
}
| gpl-2.0 |
javifo/SM-G920F-kernel | arch/powerpc/platforms/8xx/mpc86xads_setup.c | 6839 | 3894 | /*arch/powerpc/platforms/8xx/mpc86xads_setup.c
*
* Platform setup for the Freescale mpc86xads board
*
* Vitaly Bordug <vbordug@ru.mvista.com>
*
* Copyright 2005 MontaVista Software Inc.
*
* Heavily modified by Scott Wood <scottwood@freescale.com>
* Copyright 2007 Freescale Semiconductor, Inc.
*
* 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/of_platform.h>
#include <asm/io.h>
#include <asm/machdep.h>
#include <asm/time.h>
#include <asm/8xx_immap.h>
#include <asm/cpm1.h>
#include <asm/fs_pd.h>
#include <asm/udbg.h>
#include "mpc86xads.h"
#include "mpc8xx.h"
struct cpm_pin {
int port, pin, flags;
};
static struct cpm_pin mpc866ads_pins[] = {
/* SMC1 */
{CPM_PORTB, 24, CPM_PIN_INPUT}, /* RX */
{CPM_PORTB, 25, CPM_PIN_INPUT | CPM_PIN_SECONDARY}, /* TX */
/* SMC2 */
{CPM_PORTB, 21, CPM_PIN_INPUT}, /* RX */
{CPM_PORTB, 20, CPM_PIN_INPUT | CPM_PIN_SECONDARY}, /* TX */
/* SCC1 */
{CPM_PORTA, 6, CPM_PIN_INPUT}, /* CLK1 */
{CPM_PORTA, 7, CPM_PIN_INPUT}, /* CLK2 */
{CPM_PORTA, 14, CPM_PIN_INPUT}, /* TX */
{CPM_PORTA, 15, CPM_PIN_INPUT}, /* RX */
{CPM_PORTB, 19, CPM_PIN_INPUT | CPM_PIN_SECONDARY}, /* TENA */
{CPM_PORTC, 10, CPM_PIN_INPUT | CPM_PIN_SECONDARY | CPM_PIN_GPIO}, /* RENA */
{CPM_PORTC, 11, CPM_PIN_INPUT | CPM_PIN_SECONDARY | CPM_PIN_GPIO}, /* CLSN */
/* MII */
{CPM_PORTD, 3, CPM_PIN_OUTPUT},
{CPM_PORTD, 4, CPM_PIN_OUTPUT},
{CPM_PORTD, 5, CPM_PIN_OUTPUT},
{CPM_PORTD, 6, CPM_PIN_OUTPUT},
{CPM_PORTD, 7, CPM_PIN_OUTPUT},
{CPM_PORTD, 8, CPM_PIN_OUTPUT},
{CPM_PORTD, 9, CPM_PIN_OUTPUT},
{CPM_PORTD, 10, CPM_PIN_OUTPUT},
{CPM_PORTD, 11, CPM_PIN_OUTPUT},
{CPM_PORTD, 12, CPM_PIN_OUTPUT},
{CPM_PORTD, 13, CPM_PIN_OUTPUT},
{CPM_PORTD, 14, CPM_PIN_OUTPUT},
{CPM_PORTD, 15, CPM_PIN_OUTPUT},
/* I2C */
{CPM_PORTB, 26, CPM_PIN_INPUT | CPM_PIN_OPENDRAIN},
{CPM_PORTB, 27, CPM_PIN_INPUT | CPM_PIN_OPENDRAIN},
};
static void __init init_ioports(void)
{
int i;
for (i = 0; i < ARRAY_SIZE(mpc866ads_pins); i++) {
struct cpm_pin *pin = &mpc866ads_pins[i];
cpm1_set_pin(pin->port, pin->pin, pin->flags);
}
cpm1_clk_setup(CPM_CLK_SMC1, CPM_BRG1, CPM_CLK_RTX);
cpm1_clk_setup(CPM_CLK_SMC2, CPM_BRG2, CPM_CLK_RTX);
cpm1_clk_setup(CPM_CLK_SCC1, CPM_CLK1, CPM_CLK_TX);
cpm1_clk_setup(CPM_CLK_SCC1, CPM_CLK2, CPM_CLK_RX);
/* Set FEC1 and FEC2 to MII mode */
clrbits32(&mpc8xx_immr->im_cpm.cp_cptr, 0x00000180);
}
static void __init mpc86xads_setup_arch(void)
{
struct device_node *np;
u32 __iomem *bcsr_io;
cpm_reset();
init_ioports();
np = of_find_compatible_node(NULL, NULL, "fsl,mpc866ads-bcsr");
if (!np) {
printk(KERN_CRIT "Could not find fsl,mpc866ads-bcsr node\n");
return;
}
bcsr_io = of_iomap(np, 0);
of_node_put(np);
if (bcsr_io == NULL) {
printk(KERN_CRIT "Could not remap BCSR\n");
return;
}
clrbits32(bcsr_io, BCSR1_RS232EN_1 | BCSR1_RS232EN_2 | BCSR1_ETHEN);
iounmap(bcsr_io);
}
static int __init mpc86xads_probe(void)
{
unsigned long root = of_get_flat_dt_root();
return of_flat_dt_is_compatible(root, "fsl,mpc866ads");
}
static struct of_device_id __initdata of_bus_ids[] = {
{ .name = "soc", },
{ .name = "cpm", },
{ .name = "localbus", },
{},
};
static int __init declare_of_platform_devices(void)
{
of_platform_bus_probe(NULL, of_bus_ids, NULL);
return 0;
}
machine_device_initcall(mpc86x_ads, declare_of_platform_devices);
define_machine(mpc86x_ads) {
.name = "MPC86x ADS",
.probe = mpc86xads_probe,
.setup_arch = mpc86xads_setup_arch,
.init_IRQ = mpc8xx_pics_init,
.get_irq = mpc8xx_get_irq,
.restart = mpc8xx_restart,
.calibrate_decr = mpc8xx_calibrate_decr,
.set_rtc_time = mpc8xx_set_rtc_time,
.get_rtc_time = mpc8xx_get_rtc_time,
.progress = udbg_progress,
};
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.