repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
ZFine0/kernel_3.4.49 | drivers/isdn/hardware/eicon/os_4bri.c | 9596 | 28951 | /* $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 |
jgcaaprom/f2fs | lib/decompress_unxz.c | 10876 | 10892 | /*
* Wrapper for decompressing XZ-compressed kernel, initramfs, and initrd
*
* Author: Lasse Collin <lasse.collin@tukaani.org>
*
* This file has been put into the public domain.
* You can do whatever you want with this file.
*/
/*
* Important notes about in-place decompression
*
* At least on x86, the kernel is decompressed in place: the compressed data
* is placed to the end of the output buffer, and the decompressor overwrites
* most of the compressed data. There must be enough safety margin to
* guarantee that the write position is always behind the read position.
*
* The safety margin for XZ with LZMA2 or BCJ+LZMA2 is calculated below.
* Note that the margin with XZ is bigger than with Deflate (gzip)!
*
* The worst case for in-place decompression is that the beginning of
* the file is compressed extremely well, and the rest of the file is
* uncompressible. Thus, we must look for worst-case expansion when the
* compressor is encoding uncompressible data.
*
* The structure of the .xz file in case of a compresed kernel is as follows.
* Sizes (as bytes) of the fields are in parenthesis.
*
* Stream Header (12)
* Block Header:
* Block Header (8-12)
* Compressed Data (N)
* Block Padding (0-3)
* CRC32 (4)
* Index (8-20)
* Stream Footer (12)
*
* Normally there is exactly one Block, but let's assume that there are
* 2-4 Blocks just in case. Because Stream Header and also Block Header
* of the first Block don't make the decompressor produce any uncompressed
* data, we can ignore them from our calculations. Block Headers of possible
* additional Blocks have to be taken into account still. With these
* assumptions, it is safe to assume that the total header overhead is
* less than 128 bytes.
*
* Compressed Data contains LZMA2 or BCJ+LZMA2 encoded data. Since BCJ
* doesn't change the size of the data, it is enough to calculate the
* safety margin for LZMA2.
*
* LZMA2 stores the data in chunks. Each chunk has a header whose size is
* a maximum of 6 bytes, but to get round 2^n numbers, let's assume that
* the maximum chunk header size is 8 bytes. After the chunk header, there
* may be up to 64 KiB of actual payload in the chunk. Often the payload is
* quite a bit smaller though; to be safe, let's assume that an average
* chunk has only 32 KiB of payload.
*
* The maximum uncompressed size of the payload is 2 MiB. The minimum
* uncompressed size of the payload is in practice never less than the
* payload size itself. The LZMA2 format would allow uncompressed size
* to be less than the payload size, but no sane compressor creates such
* files. LZMA2 supports storing uncompressible data in uncompressed form,
* so there's never a need to create payloads whose uncompressed size is
* smaller than the compressed size.
*
* The assumption, that the uncompressed size of the payload is never
* smaller than the payload itself, is valid only when talking about
* the payload as a whole. It is possible that the payload has parts where
* the decompressor consumes more input than it produces output. Calculating
* the worst case for this would be tricky. Instead of trying to do that,
* let's simply make sure that the decompressor never overwrites any bytes
* of the payload which it is currently reading.
*
* Now we have enough information to calculate the safety margin. We need
* - 128 bytes for the .xz file format headers;
* - 8 bytes per every 32 KiB of uncompressed size (one LZMA2 chunk header
* per chunk, each chunk having average payload size of 32 KiB); and
* - 64 KiB (biggest possible LZMA2 chunk payload size) to make sure that
* the decompressor never overwrites anything from the LZMA2 chunk
* payload it is currently reading.
*
* We get the following formula:
*
* safety_margin = 128 + uncompressed_size * 8 / 32768 + 65536
* = 128 + (uncompressed_size >> 12) + 65536
*
* For comparison, according to arch/x86/boot/compressed/misc.c, the
* equivalent formula for Deflate is this:
*
* safety_margin = 18 + (uncompressed_size >> 12) + 32768
*
* Thus, when updating Deflate-only in-place kernel decompressor to
* support XZ, the fixed overhead has to be increased from 18+32768 bytes
* to 128+65536 bytes.
*/
/*
* STATIC is defined to "static" if we are being built for kernel
* decompression (pre-boot code). <linux/decompress/mm.h> will define
* STATIC to empty if it wasn't already defined. Since we will need to
* know later if we are being used for kernel decompression, we define
* XZ_PREBOOT here.
*/
#ifdef STATIC
# define XZ_PREBOOT
#endif
#ifdef __KERNEL__
# include <linux/decompress/mm.h>
#endif
#define XZ_EXTERN STATIC
#ifndef XZ_PREBOOT
# include <linux/slab.h>
# include <linux/xz.h>
#else
/*
* Use the internal CRC32 code instead of kernel's CRC32 module, which
* is not available in early phase of booting.
*/
#define XZ_INTERNAL_CRC32 1
/*
* For boot time use, we enable only the BCJ filter of the current
* architecture or none if no BCJ filter is available for the architecture.
*/
#ifdef CONFIG_X86
# define XZ_DEC_X86
#endif
#ifdef CONFIG_PPC
# define XZ_DEC_POWERPC
#endif
#ifdef CONFIG_ARM
# define XZ_DEC_ARM
#endif
#ifdef CONFIG_IA64
# define XZ_DEC_IA64
#endif
#ifdef CONFIG_SPARC
# define XZ_DEC_SPARC
#endif
/*
* This will get the basic headers so that memeq() and others
* can be defined.
*/
#include "xz/xz_private.h"
/*
* Replace the normal allocation functions with the versions from
* <linux/decompress/mm.h>. vfree() needs to support vfree(NULL)
* when XZ_DYNALLOC is used, but the pre-boot free() doesn't support it.
* Workaround it here because the other decompressors don't need it.
*/
#undef kmalloc
#undef kfree
#undef vmalloc
#undef vfree
#define kmalloc(size, flags) malloc(size)
#define kfree(ptr) free(ptr)
#define vmalloc(size) malloc(size)
#define vfree(ptr) do { if (ptr != NULL) free(ptr); } while (0)
/*
* FIXME: Not all basic memory functions are provided in architecture-specific
* files (yet). We define our own versions here for now, but this should be
* only a temporary solution.
*
* memeq and memzero are not used much and any remotely sane implementation
* is fast enough. memcpy/memmove speed matters in multi-call mode, but
* the kernel image is decompressed in single-call mode, in which only
* memcpy speed can matter and only if there is a lot of uncompressible data
* (LZMA2 stores uncompressible chunks in uncompressed form). Thus, the
* functions below should just be kept small; it's probably not worth
* optimizing for speed.
*/
#ifndef memeq
static bool memeq(const void *a, const void *b, size_t size)
{
const uint8_t *x = a;
const uint8_t *y = b;
size_t i;
for (i = 0; i < size; ++i)
if (x[i] != y[i])
return false;
return true;
}
#endif
#ifndef memzero
static void memzero(void *buf, size_t size)
{
uint8_t *b = buf;
uint8_t *e = b + size;
while (b != e)
*b++ = '\0';
}
#endif
#ifndef memmove
/* Not static to avoid a conflict with the prototype in the Linux headers. */
void *memmove(void *dest, const void *src, size_t size)
{
uint8_t *d = dest;
const uint8_t *s = src;
size_t i;
if (d < s) {
for (i = 0; i < size; ++i)
d[i] = s[i];
} else if (d > s) {
i = size;
while (i-- > 0)
d[i] = s[i];
}
return dest;
}
#endif
/*
* Since we need memmove anyway, would use it as memcpy too.
* Commented out for now to avoid breaking things.
*/
/*
#ifndef memcpy
# define memcpy memmove
#endif
*/
#include "xz/xz_crc32.c"
#include "xz/xz_dec_stream.c"
#include "xz/xz_dec_lzma2.c"
#include "xz/xz_dec_bcj.c"
#endif /* XZ_PREBOOT */
/* Size of the input and output buffers in multi-call mode */
#define XZ_IOBUF_SIZE 4096
/*
* This function implements the API defined in <linux/decompress/generic.h>.
*
* This wrapper will automatically choose single-call or multi-call mode
* of the native XZ decoder API. The single-call mode can be used only when
* both input and output buffers are available as a single chunk, i.e. when
* fill() and flush() won't be used.
*/
STATIC int INIT unxz(unsigned char *in, int in_size,
int (*fill)(void *dest, unsigned int size),
int (*flush)(void *src, unsigned int size),
unsigned char *out, int *in_used,
void (*error)(char *x))
{
struct xz_buf b;
struct xz_dec *s;
enum xz_ret ret;
bool must_free_in = false;
#if XZ_INTERNAL_CRC32
xz_crc32_init();
#endif
if (in_used != NULL)
*in_used = 0;
if (fill == NULL && flush == NULL)
s = xz_dec_init(XZ_SINGLE, 0);
else
s = xz_dec_init(XZ_DYNALLOC, (uint32_t)-1);
if (s == NULL)
goto error_alloc_state;
if (flush == NULL) {
b.out = out;
b.out_size = (size_t)-1;
} else {
b.out_size = XZ_IOBUF_SIZE;
b.out = malloc(XZ_IOBUF_SIZE);
if (b.out == NULL)
goto error_alloc_out;
}
if (in == NULL) {
must_free_in = true;
in = malloc(XZ_IOBUF_SIZE);
if (in == NULL)
goto error_alloc_in;
}
b.in = in;
b.in_pos = 0;
b.in_size = in_size;
b.out_pos = 0;
if (fill == NULL && flush == NULL) {
ret = xz_dec_run(s, &b);
} else {
do {
if (b.in_pos == b.in_size && fill != NULL) {
if (in_used != NULL)
*in_used += b.in_pos;
b.in_pos = 0;
in_size = fill(in, XZ_IOBUF_SIZE);
if (in_size < 0) {
/*
* This isn't an optimal error code
* but it probably isn't worth making
* a new one either.
*/
ret = XZ_BUF_ERROR;
break;
}
b.in_size = in_size;
}
ret = xz_dec_run(s, &b);
if (flush != NULL && (b.out_pos == b.out_size
|| (ret != XZ_OK && b.out_pos > 0))) {
/*
* Setting ret here may hide an error
* returned by xz_dec_run(), but probably
* it's not too bad.
*/
if (flush(b.out, b.out_pos) != (int)b.out_pos)
ret = XZ_BUF_ERROR;
b.out_pos = 0;
}
} while (ret == XZ_OK);
if (must_free_in)
free(in);
if (flush != NULL)
free(b.out);
}
if (in_used != NULL)
*in_used += b.in_pos;
xz_dec_end(s);
switch (ret) {
case XZ_STREAM_END:
return 0;
case XZ_MEM_ERROR:
/* This can occur only in multi-call mode. */
error("XZ decompressor ran out of memory");
break;
case XZ_FORMAT_ERROR:
error("Input is not in the XZ format (wrong magic bytes)");
break;
case XZ_OPTIONS_ERROR:
error("Input was encoded with settings that are not "
"supported by this XZ decoder");
break;
case XZ_DATA_ERROR:
case XZ_BUF_ERROR:
error("XZ-compressed data is corrupt");
break;
default:
error("Bug in the XZ decompressor");
break;
}
return -1;
error_alloc_in:
if (flush != NULL)
free(b.out);
error_alloc_out:
xz_dec_end(s);
error_alloc_state:
error("XZ decompressor ran out of memory");
return -1;
}
/*
* This macro is used by architecture-specific files to decompress
* the kernel image.
*/
#define decompress unxz
| gpl-2.0 |
milaq/android_kernel_hp_tenderloin | net/bridge/netfilter/ebt_arpreply.c | 13692 | 2428 | /*
* ebt_arpreply
*
* Authors:
* Grzegorz Borowiak <grzes@gnu.univ.gda.pl>
* Bart De Schuymer <bdschuym@pandora.be>
*
* August, 2003
*
*/
#include <linux/if_arp.h>
#include <net/arp.h>
#include <linux/module.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_bridge/ebtables.h>
#include <linux/netfilter_bridge/ebt_arpreply.h>
static unsigned int
ebt_arpreply_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
const struct ebt_arpreply_info *info = par->targinfo;
const __be32 *siptr, *diptr;
__be32 _sip, _dip;
const struct arphdr *ap;
struct arphdr _ah;
const unsigned char *shp;
unsigned char _sha[ETH_ALEN];
ap = skb_header_pointer(skb, 0, sizeof(_ah), &_ah);
if (ap == NULL)
return EBT_DROP;
if (ap->ar_op != htons(ARPOP_REQUEST) ||
ap->ar_hln != ETH_ALEN ||
ap->ar_pro != htons(ETH_P_IP) ||
ap->ar_pln != 4)
return EBT_CONTINUE;
shp = skb_header_pointer(skb, sizeof(_ah), ETH_ALEN, &_sha);
if (shp == NULL)
return EBT_DROP;
siptr = skb_header_pointer(skb, sizeof(_ah) + ETH_ALEN,
sizeof(_sip), &_sip);
if (siptr == NULL)
return EBT_DROP;
diptr = skb_header_pointer(skb,
sizeof(_ah) + 2 * ETH_ALEN + sizeof(_sip),
sizeof(_dip), &_dip);
if (diptr == NULL)
return EBT_DROP;
arp_send(ARPOP_REPLY, ETH_P_ARP, *siptr, (struct net_device *)par->in,
*diptr, shp, info->mac, shp);
return info->target;
}
static int ebt_arpreply_tg_check(const struct xt_tgchk_param *par)
{
const struct ebt_arpreply_info *info = par->targinfo;
const struct ebt_entry *e = par->entryinfo;
if (BASE_CHAIN && info->target == EBT_RETURN)
return -EINVAL;
if (e->ethproto != htons(ETH_P_ARP) ||
e->invflags & EBT_IPROTO)
return -EINVAL;
return 0;
}
static struct xt_target ebt_arpreply_tg_reg __read_mostly = {
.name = "arpreply",
.revision = 0,
.family = NFPROTO_BRIDGE,
.table = "nat",
.hooks = (1 << NF_BR_NUMHOOKS) | (1 << NF_BR_PRE_ROUTING),
.target = ebt_arpreply_tg,
.checkentry = ebt_arpreply_tg_check,
.targetsize = sizeof(struct ebt_arpreply_info),
.me = THIS_MODULE,
};
static int __init ebt_arpreply_init(void)
{
return xt_register_target(&ebt_arpreply_tg_reg);
}
static void __exit ebt_arpreply_fini(void)
{
xt_unregister_target(&ebt_arpreply_tg_reg);
}
module_init(ebt_arpreply_init);
module_exit(ebt_arpreply_fini);
MODULE_DESCRIPTION("Ebtables: ARP reply target");
MODULE_LICENSE("GPL");
| gpl-2.0 |
alwold/rpi-linux | arch/x86/kernel/tsc.c | 125 | 26519 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/timer.h>
#include <linux/acpi_pmtmr.h>
#include <linux/cpufreq.h>
#include <linux/delay.h>
#include <linux/clocksource.h>
#include <linux/percpu.h>
#include <linux/timex.h>
#include <asm/hpet.h>
#include <asm/timer.h>
#include <asm/vgtod.h>
#include <asm/time.h>
#include <asm/delay.h>
#include <asm/hypervisor.h>
#include <asm/nmi.h>
#include <asm/x86_init.h>
unsigned int __read_mostly cpu_khz; /* TSC clocks / usec, not used here */
EXPORT_SYMBOL(cpu_khz);
unsigned int __read_mostly tsc_khz;
EXPORT_SYMBOL(tsc_khz);
/*
* TSC can be unstable due to cpufreq or due to unsynced TSCs
*/
static int __read_mostly tsc_unstable;
/* native_sched_clock() is called before tsc_init(), so
we must start with the TSC soft disabled to prevent
erroneous rdtsc usage on !cpu_has_tsc processors */
static int __read_mostly tsc_disabled = -1;
int tsc_clocksource_reliable;
/*
* Scheduler clock - returns current time in nanosec units.
*/
u64 native_sched_clock(void)
{
u64 this_offset;
/*
* Fall back to jiffies if there's no TSC available:
* ( But note that we still use it if the TSC is marked
* unstable. We do this because unlike Time Of Day,
* the scheduler clock tolerates small errors and it's
* very important for it to be as fast as the platform
* can achieve it. )
*/
if (unlikely(tsc_disabled)) {
/* No locking but a rare wrong value is not a big deal: */
return (jiffies_64 - INITIAL_JIFFIES) * (1000000000 / HZ);
}
/* read the Time Stamp Counter: */
rdtscll(this_offset);
/* return the value in ns */
return __cycles_2_ns(this_offset);
}
/* We need to define a real function for sched_clock, to override the
weak default version */
#ifdef CONFIG_PARAVIRT
unsigned long long sched_clock(void)
{
return paravirt_sched_clock();
}
#else
unsigned long long
sched_clock(void) __attribute__((alias("native_sched_clock")));
#endif
int check_tsc_unstable(void)
{
return tsc_unstable;
}
EXPORT_SYMBOL_GPL(check_tsc_unstable);
#ifdef CONFIG_X86_TSC
int __init notsc_setup(char *str)
{
pr_warn("Kernel compiled with CONFIG_X86_TSC, cannot disable TSC completely\n");
tsc_disabled = 1;
return 1;
}
#else
/*
* disable flag for tsc. Takes effect by clearing the TSC cpu flag
* in cpu/common.c
*/
int __init notsc_setup(char *str)
{
setup_clear_cpu_cap(X86_FEATURE_TSC);
return 1;
}
#endif
__setup("notsc", notsc_setup);
static int no_sched_irq_time;
static int __init tsc_setup(char *str)
{
if (!strcmp(str, "reliable"))
tsc_clocksource_reliable = 1;
if (!strncmp(str, "noirqtime", 9))
no_sched_irq_time = 1;
return 1;
}
__setup("tsc=", tsc_setup);
#define MAX_RETRIES 5
#define SMI_TRESHOLD 50000
/*
* Read TSC and the reference counters. Take care of SMI disturbance
*/
static u64 tsc_read_refs(u64 *p, int hpet)
{
u64 t1, t2;
int i;
for (i = 0; i < MAX_RETRIES; i++) {
t1 = get_cycles();
if (hpet)
*p = hpet_readl(HPET_COUNTER) & 0xFFFFFFFF;
else
*p = acpi_pm_read_early();
t2 = get_cycles();
if ((t2 - t1) < SMI_TRESHOLD)
return t2;
}
return ULLONG_MAX;
}
/*
* Calculate the TSC frequency from HPET reference
*/
static unsigned long calc_hpet_ref(u64 deltatsc, u64 hpet1, u64 hpet2)
{
u64 tmp;
if (hpet2 < hpet1)
hpet2 += 0x100000000ULL;
hpet2 -= hpet1;
tmp = ((u64)hpet2 * hpet_readl(HPET_PERIOD));
do_div(tmp, 1000000);
do_div(deltatsc, tmp);
return (unsigned long) deltatsc;
}
/*
* Calculate the TSC frequency from PMTimer reference
*/
static unsigned long calc_pmtimer_ref(u64 deltatsc, u64 pm1, u64 pm2)
{
u64 tmp;
if (!pm1 && !pm2)
return ULONG_MAX;
if (pm2 < pm1)
pm2 += (u64)ACPI_PM_OVRRUN;
pm2 -= pm1;
tmp = pm2 * 1000000000LL;
do_div(tmp, PMTMR_TICKS_PER_SEC);
do_div(deltatsc, tmp);
return (unsigned long) deltatsc;
}
#define CAL_MS 10
#define CAL_LATCH (PIT_TICK_RATE / (1000 / CAL_MS))
#define CAL_PIT_LOOPS 1000
#define CAL2_MS 50
#define CAL2_LATCH (PIT_TICK_RATE / (1000 / CAL2_MS))
#define CAL2_PIT_LOOPS 5000
/*
* Try to calibrate the TSC against the Programmable
* Interrupt Timer and return the frequency of the TSC
* in kHz.
*
* Return ULONG_MAX on failure to calibrate.
*/
static unsigned long pit_calibrate_tsc(u32 latch, unsigned long ms, int loopmin)
{
u64 tsc, t1, t2, delta;
unsigned long tscmin, tscmax;
int pitcnt;
/* Set the Gate high, disable speaker */
outb((inb(0x61) & ~0x02) | 0x01, 0x61);
/*
* Setup CTC channel 2* for mode 0, (interrupt on terminal
* count mode), binary count. Set the latch register to 50ms
* (LSB then MSB) to begin countdown.
*/
outb(0xb0, 0x43);
outb(latch & 0xff, 0x42);
outb(latch >> 8, 0x42);
tsc = t1 = t2 = get_cycles();
pitcnt = 0;
tscmax = 0;
tscmin = ULONG_MAX;
while ((inb(0x61) & 0x20) == 0) {
t2 = get_cycles();
delta = t2 - tsc;
tsc = t2;
if ((unsigned long) delta < tscmin)
tscmin = (unsigned int) delta;
if ((unsigned long) delta > tscmax)
tscmax = (unsigned int) delta;
pitcnt++;
}
/*
* Sanity checks:
*
* If we were not able to read the PIT more than loopmin
* times, then we have been hit by a massive SMI
*
* If the maximum is 10 times larger than the minimum,
* then we got hit by an SMI as well.
*/
if (pitcnt < loopmin || tscmax > 10 * tscmin)
return ULONG_MAX;
/* Calculate the PIT value */
delta = t2 - t1;
do_div(delta, ms);
return delta;
}
/*
* This reads the current MSB of the PIT counter, and
* checks if we are running on sufficiently fast and
* non-virtualized hardware.
*
* Our expectations are:
*
* - the PIT is running at roughly 1.19MHz
*
* - each IO is going to take about 1us on real hardware,
* but we allow it to be much faster (by a factor of 10) or
* _slightly_ slower (ie we allow up to a 2us read+counter
* update - anything else implies a unacceptably slow CPU
* or PIT for the fast calibration to work.
*
* - with 256 PIT ticks to read the value, we have 214us to
* see the same MSB (and overhead like doing a single TSC
* read per MSB value etc).
*
* - We're doing 2 reads per loop (LSB, MSB), and we expect
* them each to take about a microsecond on real hardware.
* So we expect a count value of around 100. But we'll be
* generous, and accept anything over 50.
*
* - if the PIT is stuck, and we see *many* more reads, we
* return early (and the next caller of pit_expect_msb()
* then consider it a failure when they don't see the
* next expected value).
*
* These expectations mean that we know that we have seen the
* transition from one expected value to another with a fairly
* high accuracy, and we didn't miss any events. We can thus
* use the TSC value at the transitions to calculate a pretty
* good value for the TSC frequencty.
*/
static inline int pit_verify_msb(unsigned char val)
{
/* Ignore LSB */
inb(0x42);
return inb(0x42) == val;
}
static inline int pit_expect_msb(unsigned char val, u64 *tscp, unsigned long *deltap)
{
int count;
u64 tsc = 0, prev_tsc = 0;
for (count = 0; count < 50000; count++) {
if (!pit_verify_msb(val))
break;
prev_tsc = tsc;
tsc = get_cycles();
}
*deltap = get_cycles() - prev_tsc;
*tscp = tsc;
/*
* We require _some_ success, but the quality control
* will be based on the error terms on the TSC values.
*/
return count > 5;
}
/*
* How many MSB values do we want to see? We aim for
* a maximum error rate of 500ppm (in practice the
* real error is much smaller), but refuse to spend
* more than 50ms on it.
*/
#define MAX_QUICK_PIT_MS 50
#define MAX_QUICK_PIT_ITERATIONS (MAX_QUICK_PIT_MS * PIT_TICK_RATE / 1000 / 256)
static unsigned long quick_pit_calibrate(void)
{
int i;
u64 tsc, delta;
unsigned long d1, d2;
/* Set the Gate high, disable speaker */
outb((inb(0x61) & ~0x02) | 0x01, 0x61);
/*
* Counter 2, mode 0 (one-shot), binary count
*
* NOTE! Mode 2 decrements by two (and then the
* output is flipped each time, giving the same
* final output frequency as a decrement-by-one),
* so mode 0 is much better when looking at the
* individual counts.
*/
outb(0xb0, 0x43);
/* Start at 0xffff */
outb(0xff, 0x42);
outb(0xff, 0x42);
/*
* The PIT starts counting at the next edge, so we
* need to delay for a microsecond. The easiest way
* to do that is to just read back the 16-bit counter
* once from the PIT.
*/
pit_verify_msb(0);
if (pit_expect_msb(0xff, &tsc, &d1)) {
for (i = 1; i <= MAX_QUICK_PIT_ITERATIONS; i++) {
if (!pit_expect_msb(0xff-i, &delta, &d2))
break;
/*
* Iterate until the error is less than 500 ppm
*/
delta -= tsc;
if (d1+d2 >= delta >> 11)
continue;
/*
* Check the PIT one more time to verify that
* all TSC reads were stable wrt the PIT.
*
* This also guarantees serialization of the
* last cycle read ('d2') in pit_expect_msb.
*/
if (!pit_verify_msb(0xfe - i))
break;
goto success;
}
}
pr_err("Fast TSC calibration failed\n");
return 0;
success:
/*
* Ok, if we get here, then we've seen the
* MSB of the PIT decrement 'i' times, and the
* error has shrunk to less than 500 ppm.
*
* As a result, we can depend on there not being
* any odd delays anywhere, and the TSC reads are
* reliable (within the error).
*
* kHz = ticks / time-in-seconds / 1000;
* kHz = (t2 - t1) / (I * 256 / PIT_TICK_RATE) / 1000
* kHz = ((t2 - t1) * PIT_TICK_RATE) / (I * 256 * 1000)
*/
delta *= PIT_TICK_RATE;
do_div(delta, i*256*1000);
pr_info("Fast TSC calibration using PIT\n");
return delta;
}
/**
* native_calibrate_tsc - calibrate the tsc on boot
*/
unsigned long native_calibrate_tsc(void)
{
u64 tsc1, tsc2, delta, ref1, ref2;
unsigned long tsc_pit_min = ULONG_MAX, tsc_ref_min = ULONG_MAX;
unsigned long flags, latch, ms, fast_calibrate;
int hpet = is_hpet_enabled(), i, loopmin;
local_irq_save(flags);
fast_calibrate = quick_pit_calibrate();
local_irq_restore(flags);
if (fast_calibrate)
return fast_calibrate;
/*
* Run 5 calibration loops to get the lowest frequency value
* (the best estimate). We use two different calibration modes
* here:
*
* 1) PIT loop. We set the PIT Channel 2 to oneshot mode and
* load a timeout of 50ms. We read the time right after we
* started the timer and wait until the PIT count down reaches
* zero. In each wait loop iteration we read the TSC and check
* the delta to the previous read. We keep track of the min
* and max values of that delta. The delta is mostly defined
* by the IO time of the PIT access, so we can detect when a
* SMI/SMM disturbance happened between the two reads. If the
* maximum time is significantly larger than the minimum time,
* then we discard the result and have another try.
*
* 2) Reference counter. If available we use the HPET or the
* PMTIMER as a reference to check the sanity of that value.
* We use separate TSC readouts and check inside of the
* reference read for a SMI/SMM disturbance. We dicard
* disturbed values here as well. We do that around the PIT
* calibration delay loop as we have to wait for a certain
* amount of time anyway.
*/
/* Preset PIT loop values */
latch = CAL_LATCH;
ms = CAL_MS;
loopmin = CAL_PIT_LOOPS;
for (i = 0; i < 3; i++) {
unsigned long tsc_pit_khz;
/*
* Read the start value and the reference count of
* hpet/pmtimer when available. Then do the PIT
* calibration, which will take at least 50ms, and
* read the end value.
*/
local_irq_save(flags);
tsc1 = tsc_read_refs(&ref1, hpet);
tsc_pit_khz = pit_calibrate_tsc(latch, ms, loopmin);
tsc2 = tsc_read_refs(&ref2, hpet);
local_irq_restore(flags);
/* Pick the lowest PIT TSC calibration so far */
tsc_pit_min = min(tsc_pit_min, tsc_pit_khz);
/* hpet or pmtimer available ? */
if (ref1 == ref2)
continue;
/* Check, whether the sampling was disturbed by an SMI */
if (tsc1 == ULLONG_MAX || tsc2 == ULLONG_MAX)
continue;
tsc2 = (tsc2 - tsc1) * 1000000LL;
if (hpet)
tsc2 = calc_hpet_ref(tsc2, ref1, ref2);
else
tsc2 = calc_pmtimer_ref(tsc2, ref1, ref2);
tsc_ref_min = min(tsc_ref_min, (unsigned long) tsc2);
/* Check the reference deviation */
delta = ((u64) tsc_pit_min) * 100;
do_div(delta, tsc_ref_min);
/*
* If both calibration results are inside a 10% window
* then we can be sure, that the calibration
* succeeded. We break out of the loop right away. We
* use the reference value, as it is more precise.
*/
if (delta >= 90 && delta <= 110) {
pr_info("PIT calibration matches %s. %d loops\n",
hpet ? "HPET" : "PMTIMER", i + 1);
return tsc_ref_min;
}
/*
* Check whether PIT failed more than once. This
* happens in virtualized environments. We need to
* give the virtual PC a slightly longer timeframe for
* the HPET/PMTIMER to make the result precise.
*/
if (i == 1 && tsc_pit_min == ULONG_MAX) {
latch = CAL2_LATCH;
ms = CAL2_MS;
loopmin = CAL2_PIT_LOOPS;
}
}
/*
* Now check the results.
*/
if (tsc_pit_min == ULONG_MAX) {
/* PIT gave no useful value */
pr_warn("Unable to calibrate against PIT\n");
/* We don't have an alternative source, disable TSC */
if (!hpet && !ref1 && !ref2) {
pr_notice("No reference (HPET/PMTIMER) available\n");
return 0;
}
/* The alternative source failed as well, disable TSC */
if (tsc_ref_min == ULONG_MAX) {
pr_warn("HPET/PMTIMER calibration failed\n");
return 0;
}
/* Use the alternative source */
pr_info("using %s reference calibration\n",
hpet ? "HPET" : "PMTIMER");
return tsc_ref_min;
}
/* We don't have an alternative source, use the PIT calibration value */
if (!hpet && !ref1 && !ref2) {
pr_info("Using PIT calibration value\n");
return tsc_pit_min;
}
/* The alternative source failed, use the PIT calibration value */
if (tsc_ref_min == ULONG_MAX) {
pr_warn("HPET/PMTIMER calibration failed. Using PIT calibration.\n");
return tsc_pit_min;
}
/*
* The calibration values differ too much. In doubt, we use
* the PIT value as we know that there are PMTIMERs around
* running at double speed. At least we let the user know:
*/
pr_warn("PIT calibration deviates from %s: %lu %lu\n",
hpet ? "HPET" : "PMTIMER", tsc_pit_min, tsc_ref_min);
pr_info("Using PIT calibration value\n");
return tsc_pit_min;
}
int recalibrate_cpu_khz(void)
{
#ifndef CONFIG_SMP
unsigned long cpu_khz_old = cpu_khz;
if (cpu_has_tsc) {
tsc_khz = x86_platform.calibrate_tsc();
cpu_khz = tsc_khz;
cpu_data(0).loops_per_jiffy =
cpufreq_scale(cpu_data(0).loops_per_jiffy,
cpu_khz_old, cpu_khz);
return 0;
} else
return -ENODEV;
#else
return -ENODEV;
#endif
}
EXPORT_SYMBOL(recalibrate_cpu_khz);
/* Accelerators for sched_clock()
* convert from cycles(64bits) => nanoseconds (64bits)
* basic equation:
* ns = cycles / (freq / ns_per_sec)
* ns = cycles * (ns_per_sec / freq)
* ns = cycles * (10^9 / (cpu_khz * 10^3))
* ns = cycles * (10^6 / cpu_khz)
*
* Then we use scaling math (suggested by george@mvista.com) to get:
* ns = cycles * (10^6 * SC / cpu_khz) / SC
* ns = cycles * cyc2ns_scale / SC
*
* And since SC is a constant power of two, we can convert the div
* into a shift.
*
* We can use khz divisor instead of mhz to keep a better precision, since
* cyc2ns_scale is limited to 10^6 * 2^10, which fits in 32 bits.
* (mathieu.desnoyers@polymtl.ca)
*
* -johnstul@us.ibm.com "math is hard, lets go shopping!"
*/
DEFINE_PER_CPU(unsigned long, cyc2ns);
DEFINE_PER_CPU(unsigned long long, cyc2ns_offset);
static void set_cyc2ns_scale(unsigned long cpu_khz, int cpu)
{
unsigned long long tsc_now, ns_now, *offset;
unsigned long flags, *scale;
local_irq_save(flags);
sched_clock_idle_sleep_event();
scale = &per_cpu(cyc2ns, cpu);
offset = &per_cpu(cyc2ns_offset, cpu);
rdtscll(tsc_now);
ns_now = __cycles_2_ns(tsc_now);
if (cpu_khz) {
*scale = (NSEC_PER_MSEC << CYC2NS_SCALE_FACTOR)/cpu_khz;
*offset = ns_now - mult_frac(tsc_now, *scale,
(1UL << CYC2NS_SCALE_FACTOR));
}
sched_clock_idle_wakeup_event(0);
local_irq_restore(flags);
}
static unsigned long long cyc2ns_suspend;
void tsc_save_sched_clock_state(void)
{
if (!sched_clock_stable)
return;
cyc2ns_suspend = sched_clock();
}
/*
* Even on processors with invariant TSC, TSC gets reset in some the
* ACPI system sleep states. And in some systems BIOS seem to reinit TSC to
* arbitrary value (still sync'd across cpu's) during resume from such sleep
* states. To cope up with this, recompute the cyc2ns_offset for each cpu so
* that sched_clock() continues from the point where it was left off during
* suspend.
*/
void tsc_restore_sched_clock_state(void)
{
unsigned long long offset;
unsigned long flags;
int cpu;
if (!sched_clock_stable)
return;
local_irq_save(flags);
__this_cpu_write(cyc2ns_offset, 0);
offset = cyc2ns_suspend - sched_clock();
for_each_possible_cpu(cpu)
per_cpu(cyc2ns_offset, cpu) = offset;
local_irq_restore(flags);
}
#ifdef CONFIG_CPU_FREQ
/* Frequency scaling support. Adjust the TSC based timer when the cpu frequency
* changes.
*
* RED-PEN: On SMP we assume all CPUs run with the same frequency. It's
* not that important because current Opteron setups do not support
* scaling on SMP anyroads.
*
* Should fix up last_tsc too. Currently gettimeofday in the
* first tick after the change will be slightly wrong.
*/
static unsigned int ref_freq;
static unsigned long loops_per_jiffy_ref;
static unsigned long tsc_khz_ref;
static int time_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
void *data)
{
struct cpufreq_freqs *freq = data;
unsigned long *lpj;
if (cpu_has(&cpu_data(freq->cpu), X86_FEATURE_CONSTANT_TSC))
return 0;
lpj = &boot_cpu_data.loops_per_jiffy;
#ifdef CONFIG_SMP
if (!(freq->flags & CPUFREQ_CONST_LOOPS))
lpj = &cpu_data(freq->cpu).loops_per_jiffy;
#endif
if (!ref_freq) {
ref_freq = freq->old;
loops_per_jiffy_ref = *lpj;
tsc_khz_ref = tsc_khz;
}
if ((val == CPUFREQ_PRECHANGE && freq->old < freq->new) ||
(val == CPUFREQ_POSTCHANGE && freq->old > freq->new) ||
(val == CPUFREQ_RESUMECHANGE)) {
*lpj = cpufreq_scale(loops_per_jiffy_ref, ref_freq, freq->new);
tsc_khz = cpufreq_scale(tsc_khz_ref, ref_freq, freq->new);
if (!(freq->flags & CPUFREQ_CONST_LOOPS))
mark_tsc_unstable("cpufreq changes");
}
set_cyc2ns_scale(tsc_khz, freq->cpu);
return 0;
}
static struct notifier_block time_cpufreq_notifier_block = {
.notifier_call = time_cpufreq_notifier
};
static int __init cpufreq_tsc(void)
{
if (!cpu_has_tsc)
return 0;
if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
return 0;
cpufreq_register_notifier(&time_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
return 0;
}
core_initcall(cpufreq_tsc);
#endif /* CONFIG_CPU_FREQ */
/* clocksource code */
static struct clocksource clocksource_tsc;
/*
* We compare the TSC to the cycle_last value in the clocksource
* structure to avoid a nasty time-warp. This can be observed in a
* very small window right after one CPU updated cycle_last under
* xtime/vsyscall_gtod lock and the other CPU reads a TSC value which
* is smaller than the cycle_last reference value due to a TSC which
* is slighty behind. This delta is nowhere else observable, but in
* that case it results in a forward time jump in the range of hours
* due to the unsigned delta calculation of the time keeping core
* code, which is necessary to support wrapping clocksources like pm
* timer.
*/
static cycle_t read_tsc(struct clocksource *cs)
{
cycle_t ret = (cycle_t)get_cycles();
return ret >= clocksource_tsc.cycle_last ?
ret : clocksource_tsc.cycle_last;
}
static void resume_tsc(struct clocksource *cs)
{
clocksource_tsc.cycle_last = 0;
}
static struct clocksource clocksource_tsc = {
.name = "tsc",
.rating = 300,
.read = read_tsc,
.resume = resume_tsc,
.mask = CLOCKSOURCE_MASK(64),
.flags = CLOCK_SOURCE_IS_CONTINUOUS |
CLOCK_SOURCE_MUST_VERIFY,
#ifdef CONFIG_X86_64
.archdata = { .vclock_mode = VCLOCK_TSC },
#endif
};
void mark_tsc_unstable(char *reason)
{
if (!tsc_unstable) {
tsc_unstable = 1;
sched_clock_stable = 0;
disable_sched_clock_irqtime();
pr_info("Marking TSC unstable due to %s\n", reason);
/* Change only the rating, when not registered */
if (clocksource_tsc.mult)
clocksource_mark_unstable(&clocksource_tsc);
else {
clocksource_tsc.flags |= CLOCK_SOURCE_UNSTABLE;
clocksource_tsc.rating = 0;
}
}
}
EXPORT_SYMBOL_GPL(mark_tsc_unstable);
static void __init check_system_tsc_reliable(void)
{
#ifdef CONFIG_MGEODE_LX
/* RTSC counts during suspend */
#define RTSC_SUSP 0x100
unsigned long res_low, res_high;
rdmsr_safe(MSR_GEODE_BUSCONT_CONF0, &res_low, &res_high);
/* Geode_LX - the OLPC CPU has a very reliable TSC */
if (res_low & RTSC_SUSP)
tsc_clocksource_reliable = 1;
#endif
if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE))
tsc_clocksource_reliable = 1;
}
/*
* Make an educated guess if the TSC is trustworthy and synchronized
* over all CPUs.
*/
__cpuinit int unsynchronized_tsc(void)
{
if (!cpu_has_tsc || tsc_unstable)
return 1;
#ifdef CONFIG_SMP
if (apic_is_clustered_box())
return 1;
#endif
if (boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
return 0;
if (tsc_clocksource_reliable)
return 0;
/*
* Intel systems are normally all synchronized.
* Exceptions must mark TSC as unstable:
*/
if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL) {
/* assume multi socket systems are not synchronized: */
if (num_possible_cpus() > 1)
return 1;
}
return 0;
}
static void tsc_refine_calibration_work(struct work_struct *work);
static DECLARE_DELAYED_WORK(tsc_irqwork, tsc_refine_calibration_work);
/**
* tsc_refine_calibration_work - Further refine tsc freq calibration
* @work - ignored.
*
* This functions uses delayed work over a period of a
* second to further refine the TSC freq value. Since this is
* timer based, instead of loop based, we don't block the boot
* process while this longer calibration is done.
*
* If there are any calibration anomalies (too many SMIs, etc),
* or the refined calibration is off by 1% of the fast early
* calibration, we throw out the new calibration and use the
* early calibration.
*/
static void tsc_refine_calibration_work(struct work_struct *work)
{
static u64 tsc_start = -1, ref_start;
static int hpet;
u64 tsc_stop, ref_stop, delta;
unsigned long freq;
/* Don't bother refining TSC on unstable systems */
if (check_tsc_unstable())
goto out;
/*
* Since the work is started early in boot, we may be
* delayed the first time we expire. So set the workqueue
* again once we know timers are working.
*/
if (tsc_start == -1) {
/*
* Only set hpet once, to avoid mixing hardware
* if the hpet becomes enabled later.
*/
hpet = is_hpet_enabled();
schedule_delayed_work(&tsc_irqwork, HZ);
tsc_start = tsc_read_refs(&ref_start, hpet);
return;
}
tsc_stop = tsc_read_refs(&ref_stop, hpet);
/* hpet or pmtimer available ? */
if (ref_start == ref_stop)
goto out;
/* Check, whether the sampling was disturbed by an SMI */
if (tsc_start == ULLONG_MAX || tsc_stop == ULLONG_MAX)
goto out;
delta = tsc_stop - tsc_start;
delta *= 1000000LL;
if (hpet)
freq = calc_hpet_ref(delta, ref_start, ref_stop);
else
freq = calc_pmtimer_ref(delta, ref_start, ref_stop);
/* Make sure we're within 1% */
if (abs(tsc_khz - freq) > tsc_khz/100)
goto out;
tsc_khz = freq;
pr_info("Refined TSC clocksource calibration: %lu.%03lu MHz\n",
(unsigned long)tsc_khz / 1000,
(unsigned long)tsc_khz % 1000);
out:
clocksource_register_khz(&clocksource_tsc, tsc_khz);
}
static int __init init_tsc_clocksource(void)
{
if (!cpu_has_tsc || tsc_disabled > 0 || !tsc_khz)
return 0;
if (tsc_clocksource_reliable)
clocksource_tsc.flags &= ~CLOCK_SOURCE_MUST_VERIFY;
/* lower the rating if we already know its unstable: */
if (check_tsc_unstable()) {
clocksource_tsc.rating = 0;
clocksource_tsc.flags &= ~CLOCK_SOURCE_IS_CONTINUOUS;
}
/*
* Trust the results of the earlier calibration on systems
* exporting a reliable TSC.
*/
if (boot_cpu_has(X86_FEATURE_TSC_RELIABLE)) {
clocksource_register_khz(&clocksource_tsc, tsc_khz);
return 0;
}
schedule_delayed_work(&tsc_irqwork, 0);
return 0;
}
/*
* We use device_initcall here, to ensure we run after the hpet
* is fully initialized, which may occur at fs_initcall time.
*/
device_initcall(init_tsc_clocksource);
void __init tsc_init(void)
{
u64 lpj;
int cpu;
x86_init.timers.tsc_pre_init();
if (!cpu_has_tsc)
return;
tsc_khz = x86_platform.calibrate_tsc();
cpu_khz = tsc_khz;
if (!tsc_khz) {
mark_tsc_unstable("could not calculate TSC khz");
return;
}
pr_info("Detected %lu.%03lu MHz processor\n",
(unsigned long)cpu_khz / 1000,
(unsigned long)cpu_khz % 1000);
/*
* Secondary CPUs do not run through tsc_init(), so set up
* all the scale factors for all CPUs, assuming the same
* speed as the bootup CPU. (cpufreq notifiers will fix this
* up if their speed diverges)
*/
for_each_possible_cpu(cpu)
set_cyc2ns_scale(cpu_khz, cpu);
if (tsc_disabled > 0)
return;
/* now allow native_sched_clock() to use rdtsc */
tsc_disabled = 0;
if (!no_sched_irq_time)
enable_sched_clock_irqtime();
lpj = ((u64)tsc_khz * 1000);
do_div(lpj, HZ);
lpj_fine = lpj;
use_tsc_delay();
if (unsynchronized_tsc())
mark_tsc_unstable("TSCs unsynchronized");
check_system_tsc_reliable();
}
#ifdef CONFIG_SMP
/*
* If we have a constant TSC and are using the TSC for the delay loop,
* we can skip clock calibration if another cpu in the same socket has already
* been calibrated. This assumes that CONSTANT_TSC applies to all
* cpus in the socket - this should be a safe assumption.
*/
unsigned long __cpuinit calibrate_delay_is_known(void)
{
int i, cpu = smp_processor_id();
if (!tsc_disabled && !cpu_has(&cpu_data(cpu), X86_FEATURE_CONSTANT_TSC))
return 0;
for_each_online_cpu(i)
if (cpu_data(i).phys_proc_id == cpu_data(cpu).phys_proc_id)
return cpu_data(i).loops_per_jiffy;
return 0;
}
#endif
| gpl-2.0 |
NoelMacwan/android_kernel_sony_u8500 | drivers/modem/m6718_spi/netlink.c | 125 | 4749 | /*
* Copyright (C) ST-Ericsson SA 2010,2011
*
* Author: Chris Blair <chris.blair@stericsson.com> for ST-Ericsson
* based on shrm_protocol.c
*
* License terms: GNU General Public License (GPL) version 2
*
* U9500 <-> M6718 IPC protocol implementation using SPI:
* netlink related functionality
*/
#include <linux/netlink.h>
#include <linux/spi/spi.h>
#include <linux/modem/m6718_spi/modem_net.h>
#include <linux/modem/m6718_spi/modem_char.h>
#include "modem_protocol.h"
#include "modem_private.h"
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_MODEM_STATE
#include "modem_state.h"
#endif
static struct sock *netlink_sk;
struct modem_spi_dev *modem_dev;
#define MAX_PAYLOAD 1024
/*
* Netlink broadcast message values: this must correspond to those values
* expected by userspace for the appropriate message.
*/
enum netlink_msg_id {
NETLINK_MODEM_RESET = 1,
NETLINK_MODEM_QUERY_STATE,
NETLINK_USER_REQUEST_MODEM_RESET,
NETLINK_MODEM_STATUS_ONLINE,
NETLINK_MODEM_STATUS_OFFLINE
};
static void netlink_multicast_tasklet(unsigned long data)
{
struct sk_buff *skb;
struct nlmsghdr *nlh;
enum netlink_msg_id nlmsg = (enum netlink_msg_id)data;
if (netlink_sk == NULL) {
pr_err("could not send multicast, no socket\n");
return;
}
/* prepare netlink message */
skb = alloc_skb(NLMSG_SPACE(MAX_PAYLOAD), GFP_ATOMIC);
if (!skb) {
pr_err("failed to allocate socket buffer\n");
return;
}
if (nlmsg == NETLINK_MODEM_RESET)
modem_isa_reset(modem_dev);
nlh = (struct nlmsghdr *)skb->data;
nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
nlh->nlmsg_pid = 0; /* from kernel */
nlh->nlmsg_flags = 0;
*(int *)NLMSG_DATA(nlh) = nlmsg;
skb_put(skb, MAX_PAYLOAD);
/* sender is in group 1<<0 */
NETLINK_CB(skb).pid = 0; /* from kernel */
/* to mcast group 1<<0 */
NETLINK_CB(skb).dst_group = 1;
/* multicast the message to all listening processes */
pr_debug("sending netlink multicast message %d\n", nlmsg);
netlink_broadcast(netlink_sk, skb, 0, 1, GFP_ATOMIC);
}
static void send_unicast(int dst_pid)
{
struct sk_buff *skb;
struct nlmsghdr *nlh;
if (netlink_sk == NULL) {
pr_err("could not send unicast, no socket\n");
return;
}
/* prepare the message for unicast */
skb = alloc_skb(NLMSG_SPACE(MAX_PAYLOAD), GFP_KERNEL);
if (!skb) {
pr_err("failed to allocate socket buffer\n");
return;
}
nlh = (struct nlmsghdr *)skb->data;
nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
nlh->nlmsg_pid = 0; /* from kernel */
nlh->nlmsg_flags = 0;
if (modem_m6718_spi_is_boot_done()) {
pr_debug("sending netlink unicast message %d\n",
NETLINK_MODEM_STATUS_ONLINE);
*(int *)NLMSG_DATA(nlh) = NETLINK_MODEM_STATUS_ONLINE;
} else {
pr_debug("sending netlink unicast message %d\n",
NETLINK_MODEM_STATUS_OFFLINE);
*(int *)NLMSG_DATA(nlh) = NETLINK_MODEM_STATUS_OFFLINE;
}
skb_put(skb, MAX_PAYLOAD);
/* sender is in group 1<<0 */
NETLINK_CB(skb).pid = 0; /* from kernel */
NETLINK_CB(skb).dst_group = 0;
/* unicast the message to the querying process */
netlink_unicast(netlink_sk, skb, dst_pid, MSG_DONTWAIT);
}
static void netlink_receive(struct sk_buff *skb)
{
struct nlmsghdr *nlh = NULL;
int msg;
nlh = (struct nlmsghdr *)skb->data;
msg = *((int *)(NLMSG_DATA(nlh)));
switch (msg) {
case NETLINK_MODEM_QUERY_STATE:
send_unicast(nlh->nlmsg_pid);
break;
case NETLINK_USER_REQUEST_MODEM_RESET:
pr_info("user requested modem reset!\n");
#ifdef CONFIG_DEBUG_FS
if (l1_context.msr_disable) {
pr_info("MSR is disabled, ignoring reset request\n");
break;
}
#endif
#ifdef CONFIG_MODEM_M6718_SPI_ENABLE_FEATURE_MODEM_STATE
modem_state_force_reset();
#else
pr_err("modestate integration is not enabled in IPC, "
"unable to reset modem\n");
#endif
break;
default:
pr_debug("ignoring invalid netlink message\n");
break;
}
}
bool ipc_create_netlink_socket(struct ipc_link_context *context)
{
if (netlink_sk != NULL)
return true;
netlink_sk = netlink_kernel_create(NULL, NETLINK_MODEM, 1,
netlink_receive, NULL, THIS_MODULE);
if (netlink_sk == NULL) {
dev_err(&context->sdev->dev,
"failed to create netlink socket\n");
return false;
}
modem_dev = spi_get_drvdata(context->sdev);
return true;
}
DECLARE_TASKLET(modem_online_tasklet, netlink_multicast_tasklet,
NETLINK_MODEM_STATUS_ONLINE);
DECLARE_TASKLET(modem_reset_tasklet, netlink_multicast_tasklet,
NETLINK_MODEM_RESET);
void ipc_broadcast_modem_online(struct ipc_link_context *context)
{
dev_info(&context->sdev->dev, "broadcast modem online event!\n");
tasklet_schedule(&modem_online_tasklet);
}
void ipc_broadcast_modem_reset(struct ipc_link_context *context)
{
dev_info(&context->sdev->dev, "broadcast modem reset event!\n");
tasklet_schedule(&modem_reset_tasklet);
}
| gpl-2.0 |
mangosxx/InfinityCore | dep/acelite/ace/Unbounded_Set_Ex.cpp | 381 | 13604 | // $Id: Unbounded_Set_Ex.cpp 81702 2008-05-15 10:18:07Z johnnyw $
#ifndef ACE_UNBOUNDED_SET_EX_CPP
#define ACE_UNBOUNDED_SET_EX_CPP
#include "ace/Unbounded_Set.h"
#include "ace/Malloc_Base.h"
#include "ace/Log_Msg.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#if !defined (__ACE_INLINE__)
#include "ace/Unbounded_Set_Ex.inl"
#endif /* __ACE_INLINE__ */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Ex)
template <class T, class C> size_t
ACE_Unbounded_Set_Ex<T, C>::size (void) const
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::size");
return this->cur_size_;
}
template <class T, class C> int
ACE_Unbounded_Set_Ex<T, C>::insert_tail (const T &item)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::insert_tail");
NODE *temp = 0;
// Insert <item> into the old dummy node location.
this->head_->item_ = item;
// Create a new dummy node.
ACE_NEW_MALLOC_RETURN (temp,
static_cast<NODE*> (this->allocator_->malloc (sizeof (NODE))),
NODE (this->head_->next_),
-1);
// Link this pointer into the list.
this->head_->next_ = temp;
// Point the head to the new dummy node.
this->head_ = temp;
++this->cur_size_;
return 0;
}
template <class T, class C> void
ACE_Unbounded_Set_Ex<T, C>::reset (void)
{
ACE_TRACE ("reset");
this->delete_nodes ();
}
template <class T, class C> void
ACE_Unbounded_Set_Ex<T, C>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::dump");
ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_ = %u"), this->head_));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nhead_->next_ = %u"), this->head_->next_));
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\ncur_size_ = %d\n"), this->cur_size_));
T *item = 0;
#if !defined (ACE_NLOGGING)
size_t count = 1;
#endif /* ! ACE_NLOGGING */
const_iterator const the_end = this->end ();
for (const_iterator i (this->begin ());
i != end;
++i)
ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("count = %u\n"), count++));
ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
template <class T, class C> void
ACE_Unbounded_Set_Ex<T, C>::copy_nodes (const ACE_Unbounded_Set_Ex<T, C> &us)
{
for (NODE *curr = us.head_->next_;
curr != us.head_;
curr = curr->next_)
this->insert_tail (curr->item_);
}
template <class T, class C> void
ACE_Unbounded_Set_Ex<T, C>::delete_nodes (void)
{
NODE *curr = this->head_->next_;
// Keep looking until we've hit the dummy node.
while (curr != this->head_)
{
NODE *temp = curr;
curr = curr->next_;
ACE_DES_FREE_TEMPLATE2 (temp,
this->allocator_->free,
ACE_Node,
T, C);
--this->cur_size_;
}
// Reset the list to be a circular list with just a dummy node.
this->head_->next_ = this->head_;
}
template <class T, class C>
ACE_Unbounded_Set_Ex<T, C>::~ACE_Unbounded_Set_Ex (void)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::~ACE_Unbounded_Set_Ex");
this->delete_nodes ();
// Delete the dummy node.
ACE_DES_FREE_TEMPLATE2 (head_,
this->allocator_->free,
ACE_Node,
T, C);
this->head_ = 0;
}
template <class T, class C>
ACE_Unbounded_Set_Ex<T, C>::ACE_Unbounded_Set_Ex (ACE_Allocator *alloc)
: head_ (0),
cur_size_ (0),
allocator_ (alloc)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::ACE_Unbounded_Set_Ex");
if (this->allocator_ == 0)
this->allocator_ = ACE_Allocator::instance ();
ACE_NEW_MALLOC (this->head_,
(NODE*) this->allocator_->malloc (sizeof (NODE)),
NODE);
// Make the list circular by pointing it back to itself.
this->head_->next_ = this->head_;
}
template <class T, class C>
ACE_Unbounded_Set_Ex<T, C>::ACE_Unbounded_Set_Ex (const C &comp,
ACE_Allocator *alloc)
: head_ (0),
cur_size_ (0),
allocator_ (alloc),
comp_ (comp)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::ACE_Unbounded_Set_Ex");
if (this->allocator_ == 0)
this->allocator_ = ACE_Allocator::instance ();
ACE_NEW_MALLOC (this->head_,
(NODE*) this->allocator_->malloc (sizeof (NODE)),
NODE);
// Make the list circular by pointing it back to itself.
this->head_->next_ = this->head_;
}
template <class T, class C>
ACE_Unbounded_Set_Ex<T, C>::ACE_Unbounded_Set_Ex (const ACE_Unbounded_Set_Ex<T, C> &us)
: head_ (0),
cur_size_ (0),
allocator_ (us.allocator_),
comp_ (us.comp_)
{
ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::ACE_Unbounded_Set_Ex");
if (this->allocator_ == 0)
this->allocator_ = ACE_Allocator::instance ();
ACE_NEW_MALLOC (this->head_,
(NODE*) this->allocator_->malloc (sizeof (NODE)),
NODE);
this->head_->next_ = this->head_;
this->copy_nodes (us);
}
template <class T, class C> ACE_Unbounded_Set_Ex<T, C> &
ACE_Unbounded_Set_Ex<T, C>::operator= (const ACE_Unbounded_Set_Ex<T, C> &us)
{
ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::operator=");
if (this != &us)
{
this->delete_nodes ();
this->copy_nodes (us);
}
return *this;
}
template <class T, class C> int
ACE_Unbounded_Set_Ex<T, C>::find (const T &item) const
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::find");
const_iterator const the_end = this->end ();
for (const_iterator i = this->begin (); i != the_end; ++i)
if (this->comp_(*i, item))
return 0;
return -1;
}
template <class T, class C> int
ACE_Unbounded_Set_Ex<T, C>::insert (const T &item)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::insert");
if (this->find (item) == 0)
return 1;
else
return this->insert_tail (item);
}
template <class T, class C> int
ACE_Unbounded_Set_Ex<T, C>::remove (const T &item)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::remove");
// Insert the item to be founded into the dummy node.
this->head_->item_ = item;
NODE *curr = this->head_;
while (!(this->comp_ (curr->next_->item_, item)))
curr = curr->next_;
if (curr->next_ == this->head_)
return -1; // Item was not found.
else
{
NODE *temp = curr->next_;
// Skip over the node that we're deleting.
curr->next_ = temp->next_;
--this->cur_size_;
ACE_DES_FREE_TEMPLATE2 (temp,
this->allocator_->free,
ACE_Node,
T, C);
return 0;
}
}
template <class T, class C> typename ACE_Unbounded_Set_Ex<T, C>::iterator
ACE_Unbounded_Set_Ex<T, C>::begin (void)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::begin");
return iterator (*this);
}
template <class T, class C> typename ACE_Unbounded_Set_Ex<T, C>::iterator
ACE_Unbounded_Set_Ex<T, C>::end (void)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::end");
return iterator (*this, 1);
}
template <class T, class C> typename ACE_Unbounded_Set_Ex<T, C>::const_iterator
ACE_Unbounded_Set_Ex<T, C>::begin (void) const
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::begin");
return const_iterator (*this);
}
template <class T, class C> typename ACE_Unbounded_Set_Ex<T, C>::const_iterator
ACE_Unbounded_Set_Ex<T, C>::end (void) const
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex<T, C>::end");
return const_iterator (*this, 1);
}
ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Ex_Iterator)
template <class T, class C> void
ACE_Unbounded_Set_Ex_Iterator<T, C>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::dump");
#endif /* ACE_HAS_DUMP */
}
template <class T, class C>
ACE_Unbounded_Set_Ex_Iterator<T, C>::ACE_Unbounded_Set_Ex_Iterator (
ACE_Unbounded_Set_Ex<T, C> &s,
bool end)
: current_ (!end ? s.head_->next_ : s.head_ ),
set_ (&s)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::ACE_Unbounded_Set_Ex_Iterator");
}
template <class T, class C> int
ACE_Unbounded_Set_Ex_Iterator<T, C>::advance (void)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::advance");
this->current_ = this->current_->next_;
return this->current_ != this->set_->head_;
}
template <class T, class C> int
ACE_Unbounded_Set_Ex_Iterator<T, C>::first (void)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::first");
this->current_ = this->set_->head_->next_;
return this->current_ != this->set_->head_;
}
template <class T, class C> int
ACE_Unbounded_Set_Ex_Iterator<T, C>::done (void) const
{
ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::done");
return this->current_ == this->set_->head_;
}
template <class T, class C> int
ACE_Unbounded_Set_Ex_Iterator<T, C>::next (T *&item)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::next");
if (this->current_ == this->set_->head_)
return 0;
else
{
item = &this->current_->item_;
return 1;
}
}
template <class T, class C> ACE_Unbounded_Set_Ex_Iterator<T, C>
ACE_Unbounded_Set_Ex_Iterator<T, C>::operator++ (int)
{
//ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::operator++ (int)");
ACE_Unbounded_Set_Ex_Iterator<T, C> retv (*this);
// postfix operator
this->advance ();
return retv;
}
template <class T, class C> ACE_Unbounded_Set_Ex_Iterator<T, C>&
ACE_Unbounded_Set_Ex_Iterator<T, C>::operator++ (void)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::operator++ (void)");
// prefix operator
this->advance ();
return *this;
}
template <class T, class C> T&
ACE_Unbounded_Set_Ex_Iterator<T, C>::operator* (void)
{
//ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::operator*");
T *retv = 0;
int result = this->next (retv);
ACE_ASSERT (result != 0);
ACE_UNUSED_ARG (result);
return *retv;
}
template <class T, class C> bool
ACE_Unbounded_Set_Ex_Iterator<T, C>::operator== (const ACE_Unbounded_Set_Ex_Iterator<T, C> &rhs) const
{
//ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::operator==");
return (this->set_ == rhs.set_ && this->current_ == rhs.current_);
}
template <class T, class C> bool
ACE_Unbounded_Set_Ex_Iterator<T, C>::operator!= (const ACE_Unbounded_Set_Ex_Iterator<T, C> &rhs) const
{
//ACE_TRACE ("ACE_Unbounded_Set_Ex_Iterator<T, C>::operator!=");
return (this->set_ != rhs.set_ || this->current_ != rhs.current_);
}
ACE_ALLOC_HOOK_DEFINE(ACE_Unbounded_Set_Ex_Const_Iterator)
template <class T, class C> void
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::dump");
#endif /* ACE_HAS_DUMP */
}
template <class T, class C>
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::ACE_Unbounded_Set_Ex_Const_Iterator (
const ACE_Unbounded_Set_Ex<T, C> &s,
bool end)
: current_ (!end ? s.head_->next_ : s.head_ ),
set_ (&s)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::ACE_Unbounded_Set_Ex_Const_Iterator");
}
template <class T, class C> int
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::advance (void)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::advance");
this->current_ = this->current_->next_;
return this->current_ != this->set_->head_;
}
template <class T, class C> int
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::first (void)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::first");
this->current_ = this->set_->head_->next_;
return this->current_ != this->set_->head_;
}
template <class T, class C> int
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::done (void) const
{
ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::done");
return this->current_ == this->set_->head_;
}
template <class T, class C> int
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::next (T *&item)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::next");
if (this->current_ == this->set_->head_)
return 0;
else
{
item = &this->current_->item_;
return 1;
}
}
template <class T, class C> ACE_Unbounded_Set_Ex_Const_Iterator<T, C>
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator++ (int)
{
//ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator++ (int)");
ACE_Unbounded_Set_Ex_Const_Iterator<T, C> retv (*this);
// postfix operator
this->advance ();
return retv;
}
template <class T, class C> ACE_Unbounded_Set_Ex_Const_Iterator<T, C>&
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator++ (void)
{
// ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator++ (void)");
// prefix operator
this->advance ();
return *this;
}
template <class T, class C> T&
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator* (void)
{
//ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator*");
T *retv = 0;
int const result = this->next (retv);
ACE_ASSERT (result != 0);
ACE_UNUSED_ARG (result);
return *retv;
}
template <class T, class C> bool
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator== (const ACE_Unbounded_Set_Ex_Const_Iterator<T, C> &rhs) const
{
//ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator==");
return (this->set_ == rhs.set_ && this->current_ == rhs.current_);
}
template <class T, class C> bool
ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator!= (const ACE_Unbounded_Set_Ex_Const_Iterator<T, C> &rhs) const
{
//ACE_TRACE ("ACE_Unbounded_Set_Ex_Const_Iterator<T, C>::operator!=");
return (this->set_ != rhs.set_ || this->current_ != rhs.current_);
}
ACE_END_VERSIONED_NAMESPACE_DECL
#endif /* ACE_UNBOUNDED_SET_EX_CPP */
| gpl-2.0 |
fbocharov/au-linux-kernel-spring-2016 | linux/drivers/staging/rdma/hfi1/intr.c | 381 | 6437 | /*
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2015 Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* BSD LICENSE
*
* Copyright(c) 2015 Intel Corporation.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <linux/pci.h>
#include <linux/delay.h>
#include "hfi.h"
#include "common.h"
#include "sdma.h"
/**
* format_hwmsg - format a single hwerror message
* @msg message buffer
* @msgl length of message buffer
* @hwmsg message to add to message buffer
*/
static void format_hwmsg(char *msg, size_t msgl, const char *hwmsg)
{
strlcat(msg, "[", msgl);
strlcat(msg, hwmsg, msgl);
strlcat(msg, "]", msgl);
}
/**
* hfi1_format_hwerrors - format hardware error messages for display
* @hwerrs hardware errors bit vector
* @hwerrmsgs hardware error descriptions
* @nhwerrmsgs number of hwerrmsgs
* @msg message buffer
* @msgl message buffer length
*/
void hfi1_format_hwerrors(u64 hwerrs, const struct hfi1_hwerror_msgs *hwerrmsgs,
size_t nhwerrmsgs, char *msg, size_t msgl)
{
int i;
for (i = 0; i < nhwerrmsgs; i++)
if (hwerrs & hwerrmsgs[i].mask)
format_hwmsg(msg, msgl, hwerrmsgs[i].msg);
}
static void signal_ib_event(struct hfi1_pportdata *ppd, enum ib_event_type ev)
{
struct ib_event event;
struct hfi1_devdata *dd = ppd->dd;
/*
* Only call ib_dispatch_event() if the IB device has been
* registered. HFI1_INITED is set iff the driver has successfully
* registered with the IB core.
*/
if (!(dd->flags & HFI1_INITTED))
return;
event.device = &dd->verbs_dev.ibdev;
event.element.port_num = ppd->port;
event.event = ev;
ib_dispatch_event(&event);
}
/*
* Handle a linkup or link down notification.
* This is called outside an interrupt.
*/
void handle_linkup_change(struct hfi1_devdata *dd, u32 linkup)
{
struct hfi1_pportdata *ppd = &dd->pport[0];
enum ib_event_type ev;
if (!(ppd->linkup ^ !!linkup))
return; /* no change, nothing to do */
if (linkup) {
/*
* Quick linkup and all link up on the simulator does not
* trigger or implement:
* - VerifyCap interrupt
* - VerifyCap frames
* But rather moves directly to LinkUp.
*
* Do the work of the VerifyCap interrupt handler,
* handle_verify_cap(), but do not try moving the state to
* LinkUp as we are already there.
*
* NOTE: This uses this device's vAU, vCU, and vl15_init for
* the remote values. Both sides must be using the values.
*/
if (quick_linkup
|| dd->icode == ICODE_FUNCTIONAL_SIMULATOR) {
set_up_vl15(dd, dd->vau, dd->vl15_init);
assign_remote_cm_au_table(dd, dd->vcu);
ppd->neighbor_guid =
read_csr(dd,
DC_DC8051_STS_REMOTE_GUID);
ppd->neighbor_type =
read_csr(dd, DC_DC8051_STS_REMOTE_NODE_TYPE) &
DC_DC8051_STS_REMOTE_NODE_TYPE_VAL_MASK;
ppd->neighbor_port_number =
read_csr(dd, DC_DC8051_STS_REMOTE_PORT_NO) &
DC_DC8051_STS_REMOTE_PORT_NO_VAL_SMASK;
dd_dev_info(dd,
"Neighbor GUID: %llx Neighbor type %d\n",
ppd->neighbor_guid,
ppd->neighbor_type);
}
/* physical link went up */
ppd->linkup = 1;
ppd->offline_disabled_reason = OPA_LINKDOWN_REASON_NONE;
/* link widths are not available until the link is fully up */
get_linkup_link_widths(ppd);
} else {
/* physical link went down */
ppd->linkup = 0;
/* clear HW details of the previous connection */
reset_link_credits(dd);
/* freeze after a link down to guarantee a clean egress */
start_freeze_handling(ppd, FREEZE_SELF|FREEZE_LINK_DOWN);
ev = IB_EVENT_PORT_ERR;
hfi1_set_uevent_bits(ppd, _HFI1_EVENT_LINKDOWN_BIT);
/* if we are down, the neighbor is down */
ppd->neighbor_normal = 0;
/* notify IB of the link change */
signal_ib_event(ppd, ev);
}
}
/*
* Handle receive or urgent interrupts for user contexts. This means a user
* process was waiting for a packet to arrive, and didn't want to poll.
*/
void handle_user_interrupt(struct hfi1_ctxtdata *rcd)
{
struct hfi1_devdata *dd = rcd->dd;
unsigned long flags;
spin_lock_irqsave(&dd->uctxt_lock, flags);
if (!rcd->cnt)
goto done;
if (test_and_clear_bit(HFI1_CTXT_WAITING_RCV, &rcd->event_flags)) {
wake_up_interruptible(&rcd->wait);
hfi1_rcvctrl(dd, HFI1_RCVCTRL_INTRAVAIL_DIS, rcd->ctxt);
} else if (test_and_clear_bit(HFI1_CTXT_WAITING_URG,
&rcd->event_flags)) {
rcd->urgent++;
wake_up_interruptible(&rcd->wait);
}
done:
spin_unlock_irqrestore(&dd->uctxt_lock, flags);
}
| gpl-2.0 |
cmvienneau/android_kernel_htc_m4 | fs/signalfd.c | 381 | 7067 | /*
* fs/signalfd.c
*
* Copyright (C) 2003 Linus Torvalds
*
* Mon Mar 5, 2007: Davide Libenzi <davidel@xmailserver.org>
* Changed ->read() to return a siginfo strcture instead of signal number.
* Fixed locking in ->poll().
* Added sighand-detach notification.
* Added fd re-use in sys_signalfd() syscall.
* Now using anonymous inode source.
* Thanks to Oleg Nesterov for useful code review and suggestions.
* More comments and suggestions from Arnd Bergmann.
* Sat May 19, 2007: Davi E. M. Arnaut <davi@haxent.com.br>
* Retrieve multiple signals with one read() call
* Sun Jul 15, 2007: Davide Libenzi <davidel@xmailserver.org>
* Attach to the sighand only during read() and poll().
*/
#include <linux/file.h>
#include <linux/poll.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/list.h>
#include <linux/anon_inodes.h>
#include <linux/signalfd.h>
#include <linux/syscalls.h>
void signalfd_cleanup(struct sighand_struct *sighand)
{
wait_queue_head_t *wqh = &sighand->signalfd_wqh;
if (likely(!waitqueue_active(wqh)))
return;
wake_up_poll(wqh, POLLHUP | POLLFREE);
}
struct signalfd_ctx {
sigset_t sigmask;
};
static int signalfd_release(struct inode *inode, struct file *file)
{
kfree(file->private_data);
return 0;
}
static unsigned int signalfd_poll(struct file *file, poll_table *wait)
{
struct signalfd_ctx *ctx = file->private_data;
unsigned int events = 0;
poll_wait(file, ¤t->sighand->signalfd_wqh, wait);
spin_lock_irq(¤t->sighand->siglock);
if (next_signal(¤t->pending, &ctx->sigmask) ||
next_signal(¤t->signal->shared_pending,
&ctx->sigmask))
events |= POLLIN;
spin_unlock_irq(¤t->sighand->siglock);
return events;
}
static int signalfd_copyinfo(struct signalfd_siginfo __user *uinfo,
siginfo_t const *kinfo)
{
long err;
BUILD_BUG_ON(sizeof(struct signalfd_siginfo) != 128);
err = __clear_user(uinfo, sizeof(*uinfo));
err |= __put_user(kinfo->si_signo, &uinfo->ssi_signo);
err |= __put_user(kinfo->si_errno, &uinfo->ssi_errno);
err |= __put_user((short) kinfo->si_code, &uinfo->ssi_code);
switch (kinfo->si_code & __SI_MASK) {
case __SI_KILL:
err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid);
err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid);
break;
case __SI_TIMER:
err |= __put_user(kinfo->si_tid, &uinfo->ssi_tid);
err |= __put_user(kinfo->si_overrun, &uinfo->ssi_overrun);
err |= __put_user((long) kinfo->si_ptr, &uinfo->ssi_ptr);
err |= __put_user(kinfo->si_int, &uinfo->ssi_int);
break;
case __SI_POLL:
err |= __put_user(kinfo->si_band, &uinfo->ssi_band);
err |= __put_user(kinfo->si_fd, &uinfo->ssi_fd);
break;
case __SI_FAULT:
err |= __put_user((long) kinfo->si_addr, &uinfo->ssi_addr);
#ifdef __ARCH_SI_TRAPNO
err |= __put_user(kinfo->si_trapno, &uinfo->ssi_trapno);
#endif
#ifdef BUS_MCEERR_AO
if (kinfo->si_code == BUS_MCEERR_AR ||
kinfo->si_code == BUS_MCEERR_AO)
err |= __put_user((short) kinfo->si_addr_lsb,
&uinfo->ssi_addr_lsb);
#endif
break;
case __SI_CHLD:
err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid);
err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid);
err |= __put_user(kinfo->si_status, &uinfo->ssi_status);
err |= __put_user(kinfo->si_utime, &uinfo->ssi_utime);
err |= __put_user(kinfo->si_stime, &uinfo->ssi_stime);
break;
case __SI_RT:
case __SI_MESGQ:
err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid);
err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid);
err |= __put_user((long) kinfo->si_ptr, &uinfo->ssi_ptr);
err |= __put_user(kinfo->si_int, &uinfo->ssi_int);
break;
default:
err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid);
err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid);
err |= __put_user((long) kinfo->si_ptr, &uinfo->ssi_ptr);
err |= __put_user(kinfo->si_int, &uinfo->ssi_int);
break;
}
return err ? -EFAULT: sizeof(*uinfo);
}
static ssize_t signalfd_dequeue(struct signalfd_ctx *ctx, siginfo_t *info,
int nonblock)
{
ssize_t ret;
DECLARE_WAITQUEUE(wait, current);
spin_lock_irq(¤t->sighand->siglock);
ret = dequeue_signal(current, &ctx->sigmask, info);
switch (ret) {
case 0:
if (!nonblock)
break;
ret = -EAGAIN;
default:
spin_unlock_irq(¤t->sighand->siglock);
return ret;
}
add_wait_queue(¤t->sighand->signalfd_wqh, &wait);
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
ret = dequeue_signal(current, &ctx->sigmask, info);
if (ret != 0)
break;
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
spin_unlock_irq(¤t->sighand->siglock);
schedule();
spin_lock_irq(¤t->sighand->siglock);
}
spin_unlock_irq(¤t->sighand->siglock);
remove_wait_queue(¤t->sighand->signalfd_wqh, &wait);
__set_current_state(TASK_RUNNING);
return ret;
}
static ssize_t signalfd_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
struct signalfd_ctx *ctx = file->private_data;
struct signalfd_siginfo __user *siginfo;
int nonblock = file->f_flags & O_NONBLOCK;
ssize_t ret, total = 0;
siginfo_t info;
count /= sizeof(struct signalfd_siginfo);
if (!count)
return -EINVAL;
siginfo = (struct signalfd_siginfo __user *) buf;
do {
ret = signalfd_dequeue(ctx, &info, nonblock);
if (unlikely(ret <= 0))
break;
ret = signalfd_copyinfo(siginfo, &info);
if (ret < 0)
break;
siginfo++;
total += ret;
nonblock = 1;
} while (--count);
return total ? total: ret;
}
static const struct file_operations signalfd_fops = {
.release = signalfd_release,
.poll = signalfd_poll,
.read = signalfd_read,
.llseek = noop_llseek,
};
SYSCALL_DEFINE4(signalfd4, int, ufd, sigset_t __user *, user_mask,
size_t, sizemask, int, flags)
{
sigset_t sigmask;
struct signalfd_ctx *ctx;
BUILD_BUG_ON(SFD_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(SFD_NONBLOCK != O_NONBLOCK);
if (flags & ~(SFD_CLOEXEC | SFD_NONBLOCK))
return -EINVAL;
if (sizemask != sizeof(sigset_t) ||
copy_from_user(&sigmask, user_mask, sizeof(sigmask)))
return -EINVAL;
sigdelsetmask(&sigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
signotset(&sigmask);
if (ufd == -1) {
ctx = kmalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->sigmask = sigmask;
ufd = anon_inode_getfd("[signalfd]", &signalfd_fops, ctx,
O_RDWR | (flags & (O_CLOEXEC | O_NONBLOCK)));
if (ufd < 0)
kfree(ctx);
} else {
struct file *file = fget(ufd);
if (!file)
return -EBADF;
ctx = file->private_data;
if (file->f_op != &signalfd_fops) {
fput(file);
return -EINVAL;
}
spin_lock_irq(¤t->sighand->siglock);
ctx->sigmask = sigmask;
spin_unlock_irq(¤t->sighand->siglock);
wake_up(¤t->sighand->signalfd_wqh);
fput(file);
}
return ufd;
}
SYSCALL_DEFINE3(signalfd, int, ufd, sigset_t __user *, user_mask,
size_t, sizemask)
{
return sys_signalfd4(ufd, user_mask, sizemask, 0);
}
| gpl-2.0 |
Dazzozo/android_kernel_huawei_u8815 | arch/arm/perfmon/per-axi.c | 893 | 17656 | /* Copyright (c) 2010, Code Aurora Forum. 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.
*/
/*
per-axi
DESCRIPTION
Functions related to AXI bus performance counter manipulations.
*/
#include <linux/io.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/proc_fs.h>
#include "asm/uaccess.h"
#include "per-axi.h"
#include "perf.h"
/*
Definitions for AXI register addresses, macros to set and get register values
*/
#define AXI_BASE_SIZE 0x00004000
#define AXI_REG_BASE (AXI_BASE + 0x00000000)
#define AXI_REG_BASE_PHYS 0xa8200000
#define __inpdw(port) ioread32(port)
#define in_dword_masked(addr, mask) (__inpdw(addr) & (mask))
#define __outpdw(port, val) (iowrite32((uint32_t) (val), port))
#define out_dword(addr, val) __outpdw(addr, val)
#define HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_ADDR \
(AXI_REG_BASE + 0x00003434)
#define HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_RMSK 0xffff
#define HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_IN \
in_dword_masked(HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_ADDR, \
HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_RMSK)
#define HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_ADDR (AXI_REG_BASE + 0x00003438)
#define HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_RMSK 0xffff
#define HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_IN \
in_dword_masked(HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_ADDR, \
HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_RMSK)
#define HWIO_AXI_MONITOR_SELECTION_REG0_ADDR (AXI_REG_BASE + 0x00003428)
#define HWIO_AXI_MONITOR_SELECTION_REG1_ADDR (AXI_REG_BASE + 0x0000342c)
#define HWIO_AXI_MONITOR_TENURE_SELECTION_REG_ADDR (AXI_REG_BASE + 0x00003430)
#define HWIO_AXI_MONITOR_SELECTION_REG0_ETC_BMSK 0x4000
#define HWIO_AXI_MONITOR_SELECTION_REG0_ECC_BMSK 0x2000
#define HWIO_AXI_MONITOR_SELECTION_REG0_EEC1_BMSK 0x800
#define HWIO_AXI_MONITOR_SELECTION_REG0_EEC0_BMSK 0x200
#define HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_OUT(v) \
out_dword(HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_ADDR, v)
#define HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_OUT(v) \
out_dword(HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_ADDR, v)
#define HWIO_AXI_MONITOR_SELECTION_REG0_OUT(v) \
out_dword(HWIO_AXI_MONITOR_SELECTION_REG0_ADDR, v)
#define HWIO_AXI_MONITOR_SELECTION_REG1_OUT(v) \
out_dword(HWIO_AXI_MONITOR_SELECTION_REG1_ADDR, v)
#define HWIO_AXI_MONITOR_TENURE_SELECTION_REG_OUT(v) \
out_dword(HWIO_AXI_MONITOR_TENURE_SELECTION_REG_ADDR, v)
#define HWIO_AXI_MONITOR_SELECTION_REG0_RMSK 0xffff
#define HWIO_AXI_MONITOR_SELECTION_REG0_IN \
in_dword_masked(HWIO_AXI_MONITOR_SELECTION_REG0_ADDR, \
HWIO_AXI_MONITOR_SELECTION_REG0_RMSK)
#define HWIO_AXI_CONFIGURATION_REG_ADDR (AXI_REG_BASE + 0x00000008)
#define HWIO_AXI_CONFIGURATION_REG_OUT(v) \
out_dword(HWIO_AXI_CONFIGURATION_REG_ADDR, v)
#define HWIO_AXI_CONFIGURATION_REG_PPDM_BMSK 0x0
#define HWIO_AXI_CONFIGURATION_REG_DISABLE 0x2
#define AXI_EVTSEL_ENABLE_MASK 0x6a00
#define AXI_EVTSEL_DISABLE_MASK 0x95ff
#define AXI_EVTSEL_RESET_MASK 0xfe40
#define HWIO_AXI_MONITOR_EVENT_LOWER_REG0_ADDR (AXI_REG_BASE + 0x00003450)
#define HWIO_AXI_MONITOR_EVENT_LOWER_REG0_RMSK 0xffff
#define HWIO_AXI_MONITOR_EVENT_LOWER_REG0_SHFT 0
#define HWIO_AXI_MONITOR_EVENT_LOWER_REG0_IN \
in_dword_masked(HWIO_AXI_MONITOR_EVENT_LOWER_REG0_ADDR, \
HWIO_AXI_MONITOR_EVENT_LOWER_REG0_RMSK)
#define HWIO_AXI_MONITOR_EVENT_UPPER_REG0_ADDR (AXI_REG_BASE + 0x00003454)
#define HWIO_AXI_MONITOR_EVENT_UPPER_REG0_RMSK 0xffff
#define HWIO_AXI_MONITOR_EVENT_UPPER_REG0_SHFT 0
#define HWIO_AXI_MONITOR_EVENT_UPPER_REG0_IN \
in_dword_masked(HWIO_AXI_MONITOR_EVENT_UPPER_REG0_ADDR, \
HWIO_AXI_MONITOR_EVENT_UPPER_REG0_RMSK)
#define HWIO_AXI_MONITOR_EVENT_LOWER_REG1_ADDR (AXI_REG_BASE + 0x00003458)
#define HWIO_AXI_MONITOR_EVENT_LOWER_REG1_RMSK 0xffff
#define HWIO_AXI_MONITOR_EVENT_LOWER_REG1_SHFT 0
#define HWIO_AXI_MONITOR_EVENT_LOWER_REG1_IN \
in_dword_masked(HWIO_AXI_MONITOR_EVENT_LOWER_REG1_ADDR, \
HWIO_AXI_MONITOR_EVENT_LOWER_REG1_RMSK)
#define HWIO_AXI_MONITOR_EVENT_UPPER_REG1_ADDR (AXI_REG_BASE + 0x0000345c)
#define HWIO_AXI_MONITOR_EVENT_UPPER_REG1_RMSK 0xffff
#define HWIO_AXI_MONITOR_EVENT_UPPER_REG1_SHFT 0
#define HWIO_AXI_MONITOR_EVENT_UPPER_REG1_IN \
in_dword_masked(HWIO_AXI_MONITOR_EVENT_UPPER_REG1_ADDR, \
HWIO_AXI_MONITOR_EVENT_UPPER_REG1_RMSK)
#define HWIO_AXI_MONITOR_TENURE_LOWER_REG_ADDR (AXI_REG_BASE + 0x00003448)
#define HWIO_AXI_MONITOR_TENURE_LOWER_REG_RMSK 0xffff
#define HWIO_AXI_MONITOR_TENURE_LOWER_REG_SHFT 0
#define HWIO_AXI_MONITOR_TENURE_LOWER_REG_IN \
in_dword_masked(HWIO_AXI_MONITOR_TENURE_LOWER_REG_ADDR, \
HWIO_AXI_MONITOR_TENURE_LOWER_REG_RMSK)
#define HWIO_AXI_MONITOR_TENURE_UPPER_REG_ADDR (AXI_REG_BASE + 0x00003444)
#define HWIO_AXI_MONITOR_TENURE_UPPER_REG_RMSK 0xffff
#define HWIO_AXI_MONITOR_TENURE_UPPER_REG_SHFT 0
#define HWIO_AXI_MONITOR_TENURE_UPPER_REG_IN \
in_dword_masked(HWIO_AXI_MONITOR_TENURE_UPPER_REG_ADDR, \
HWIO_AXI_MONITOR_TENURE_UPPER_REG_RMSK)
#define HWIO_AXI_MONITOR_MIN_REG_ADDR (AXI_REG_BASE + 0x0000343c)
#define HWIO_AXI_MONITOR_MIN_REG_RMSK 0xffff
#define HWIO_AXI_MONITOR_MIN_REG_SHFT 0
#define HWIO_AXI_MONITOR_MIN_REG_IN \
in_dword_masked(HWIO_AXI_MONITOR_MIN_REG_ADDR, \
HWIO_AXI_MONITOR_MIN_REG_RMSK)
#define HWIO_AXI_MONITOR_MAX_REG_ADDR (AXI_REG_BASE + 0x00003440)
#define HWIO_AXI_MONITOR_MAX_REG_RMSK 0xffff
#define HWIO_AXI_MONITOR_MAX_REG_SHFT 0
#define HWIO_AXI_MONITOR_MAX_REG_IN \
in_dword_masked(HWIO_AXI_MONITOR_MAX_REG_ADDR, \
HWIO_AXI_MONITOR_MAX_REG_RMSK)
#define HWIO_AXI_MONITOR_LAST_TENURE_REG_ADDR (AXI_REG_BASE + 0x0000344c)
#define HWIO_AXI_MONITOR_LAST_TENURE_REG_RMSK 0xffff
#define HWIO_AXI_MONITOR_LAST_TENURE_REG_SHFT 0
#define HWIO_AXI_MONITOR_LAST_TENURE_REG_IN \
in_dword_masked(HWIO_AXI_MONITOR_LAST_TENURE_REG_ADDR, \
HWIO_AXI_MONITOR_LAST_TENURE_REG_RMSK)
#define HWIO_AXI_MONITOR_TENURE_UPPER_REG_OUT(v) \
out_dword(HWIO_AXI_MONITOR_TENURE_UPPER_REG_ADDR, v)
#define HWIO_AXI_MONITOR_TENURE_LOWER_REG_OUT(v) \
out_dword(HWIO_AXI_MONITOR_TENURE_LOWER_REG_ADDR, v)
#define HWIO_AXI_RESET_ALL 0x9400
#define HWIO_AXI_ENABLE_ALL_NOCYCLES 0x4a00
#define HWIO_AXI_DISABLE_ALL 0xb500
uint32_t AXI_BASE;
unsigned int is_first = 1;
struct perf_mon_axi_data pm_axi_info;
struct perf_mon_axi_cnts axi_cnts;
/*
FUNCTION get_axi_sel_reg0
DESCRIPTION
Retrieve the value of AXI_SEL_REG0
DEPENDENCIES
RETURN VALUE
AXI_SEL_REG0
SIDE EFFECTS
*/
unsigned long get_axi_sel_reg0(void)
{
return pm_axi_info.sel_reg0;
}
/*
FUNCTION get_axi_sel_reg1
DESCRIPTION
Retrieve the value of AXI_SEL_REG1
DEPENDENCIES
RETURN VALUE
AXI_SEL_REG1
SIDE EFFECTS
*/
unsigned long get_axi_sel_reg1(void)
{
return pm_axi_info.sel_reg1;
}
/*
FUNCTION get_axi_ten_sel_reg
DESCRIPTION
Retrieve the value of AXI_TEN_REG
DEPENDENCIES
RETURN VALUE
AXI_TEN_REG
SIDE EFFECTS
*/
unsigned long get_axi_ten_sel_reg(void)
{
return pm_axi_info.ten_sel_reg;
}
/*
FUNCTION get_axi_valid
DESCRIPTION
Retrieve the value of AXI valid bit
DEPENDENCIES
RETURN VALUE
AXI Valid bit
SIDE EFFECTS
*/
unsigned long get_axi_valid(void)
{
return pm_axi_info.valid;
}
/*
FUNCTION get_axi_enable
DESCRIPTION
Retrieve the value of AXI enable bit
DEPENDENCIES
RETURN VALUE
AXI enable bit
SIDE EFFECTS
*/
unsigned long get_axi_enable(void)
{
return pm_axi_info.enable;
}
/*
FUNCTION get_axi_clear
DESCRIPTION
Retrieve the value of AXI clear bit
DEPENDENCIES
RETURN VALUE
AXI clear bit
SIDE EFFECTS
*/
unsigned long get_axi_clear(void)
{
return pm_axi_info.clear;
}
/*
FUNCTION pm_axi_cnts_write
DESCRIPTION
Write handler for the /proc axi results directory.
DEPENDENCIES
RETURN VALUE
Number of characters to output.
SIDE EFFECTS
*/
int pm_axi_cnts_write(struct file *file, const char *buff,
unsigned long cnt, void *data)
{
char *newbuf;
struct PerfMonAxiCnts *p =
(struct PerfMonAxiCnts *)data;
if (p == 0)
return cnt;
/*
* Alloc the user data in kernel space. and then copy user to kernel
*/
newbuf = kmalloc(cnt + 1, GFP_KERNEL);
if (0 == newbuf)
return cnt;
if (copy_from_user(newbuf, buff, cnt) != 0) {
printk(KERN_INFO "%s copy_from_user failed\n", __func__);
return cnt;
}
return cnt;
}
/*
FUNCTION pm_axi_update_cnts
DESCRIPTION
Read the current AXI counter values. Check for overflows and
adjust the values stored accordingly.
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void pm_axi_update_cnts(void)
{
if (is_first) {
pm_axi_start();
} else {
if (pm_axi_info.valid == 1) {
pm_axi_info.valid = 0;
pm_axi_update();
} else {
pm_axi_enable();
}
}
is_first = 0;
axi_cnts.cycles += pm_get_axi_cycle_count();
axi_cnts.cnt0 += pm_get_axi_evt0_count();
axi_cnts.cnt1 += pm_get_axi_evt1_count();
axi_cnts.tenure_total += pm_get_axi_ten_total_count();
axi_cnts.tenure_min = pm_get_axi_ten_min_count();
axi_cnts.tenure_max = pm_get_axi_ten_max_count();
axi_cnts.tenure_last = pm_get_axi_ten_last_count();
pm_axi_start();
}
/*
FUNCTION pm_axi_clear_cnts
DESCRIPTION
Clear the locally stored AXI counter values.
Also clear the AXI counter registers.
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void pm_axi_clear_cnts(void)
{
axi_cnts.cycles = 0;
axi_cnts.cnt0 = 0;
axi_cnts.cnt1 = 0;
axi_cnts.tenure_total = 0;
axi_cnts.tenure_min = 0;
axi_cnts.tenure_max = 0;
axi_cnts.tenure_last = 0;
pm_axi_start();
}
/*
FUNCTION pm_axi_read_decimal
DESCRIPTION
Read handler for the /proc axi results directory in decimal format.
DEPENDENCIES
RETURN VALUE
Number of characters to output.
SIDE EFFECTS
*/
int pm_axi_read_decimal(char *page, char **start, off_t off, int count,
int *eof, void *data)
{
struct perf_mon_axi_cnts *p = (struct perf_mon_axi_cnts *)data;
return sprintf(page, "cnt0:%llu cnt1:%llu tenure:%llu ten_max:%llu \
ten_min:%llu ten_last:%llu cycles:%llu\n",
p->cnt0,
p->cnt1,
p->tenure_total,
p->tenure_max,
p->tenure_min,
p->tenure_last,
p->cycles);
}
/*
FUNCTION pm_axi_read_hex
DESCRIPTION
Read handler for the /proc axi results directory in hex format.
DEPENDENCIES
RETURN VALUE
Number of characters to output.
SIDE EFFECTS
*/
int pm_axi_read_hex(char *page, char **start, off_t off, int count,
int *eof, void *data)
{
struct perf_mon_axi_cnts *p = (struct perf_mon_axi_cnts *)data;
return sprintf(page, "cnt0:%llx cnt1:%llx tenure:%llx ten_max:%llx \
ten_min:%llx ten_last:%llx cycles:%llx\n",
p->cnt0,
p->cnt1,
p->tenure_total,
p->tenure_max,
p->tenure_min,
p->tenure_last,
p->cycles);
}
/*
FUNCTION pm_axi_set_proc_entry
DESCRIPTION
Create a generic entry for the /proc axi settings directory.
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void pm_axi_set_proc_entry(char *name, unsigned long *var,
struct proc_dir_entry *d, int hex)
{
struct proc_dir_entry *pe;
pe = create_proc_entry(name, 0777, d);
if (0 == pe)
return;
if (hex) {
pe->read_proc = per_process_read;
pe->write_proc = per_process_write_hex;
} else {
pe->read_proc = per_process_read_decimal;
pe->write_proc = per_process_write_dec;
}
pe->data = (void *)var;
}
/*
FUNCTION pm_axi_get_cnt_proc_entry
DESCRIPTION
Create a generic entry for the /proc axi results directory.
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void pm_axi_get_cnt_proc_entry(char *name, struct perf_mon_axi_cnts *var,
struct proc_dir_entry *d, int hex)
{
struct proc_dir_entry *pe;
pe = create_proc_entry(name, 0777, d);
if (0 == pe)
return;
if (hex) {
pe->read_proc = pm_axi_read_hex;
pe->write_proc = pm_axi_cnts_write;
} else {
pe->read_proc = pm_axi_read_decimal;
pe->write_proc = pm_axi_cnts_write;
}
pe->data = (void *)var;
}
/*
FUNCTION pm_axi_clear_tenure
DESCRIPTION
Clear AXI tenure cntr manually. Temporary solution till hardware bug
is fixed
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void pm_axi_clear_tenure(void)
{
HWIO_AXI_MONITOR_TENURE_UPPER_REG_OUT(0x0);
HWIO_AXI_MONITOR_TENURE_LOWER_REG_OUT(0x0);
}
/*
FUNCTION pm_axi_init
DESCRIPTION
Map AXI region to virtual memory.
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void pm_axi_init()
{
/*Map the AXI regs*/
#ifdef CONFIG_ARCH_QSD8X50
{
/*Map the AXI regs*/
AXI_BASE = (uint32_t)ioremap(AXI_REG_BASE_PHYS, AXI_BASE_SIZE);
if (!AXI_BASE)
printk(KERN_ERR "Mem map failed\n");
}
#else
{
AXI_BASE = (uint32_t)kmalloc(AXI_BASE_SIZE, GFP_KERNEL);
}
#endif
}
/*
FUNCTION pm_axi_start
DESCRIPTION
Set event0, event1 and tenure registers based on the /proc entries.
Set cycle cntr to fffffffe to start counters.
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void
pm_axi_start()
{
unsigned long sel_reg0, sel_reg1, ten_sel_reg;
sel_reg0 = get_axi_sel_reg0();
sel_reg1 = get_axi_sel_reg1();
ten_sel_reg = get_axi_ten_sel_reg();
HWIO_AXI_CONFIGURATION_REG_OUT(HWIO_AXI_CONFIGURATION_REG_PPDM_BMSK);
/*Set AXI Cycle Counter to enable AXI Monitors*/
HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_OUT(0xffff);
HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_OUT(0xfffe);
/*Set master/slave*/
HWIO_AXI_MONITOR_SELECTION_REG1_OUT(sel_reg1);
HWIO_AXI_MONITOR_SELECTION_REG0_OUT(HWIO_AXI_RESET_ALL);
HWIO_AXI_MONITOR_SELECTION_REG0_OUT(HWIO_AXI_ENABLE_ALL_NOCYCLES);
HWIO_AXI_MONITOR_SELECTION_REG0_OUT(HWIO_AXI_MONITOR_SELECTION_REG0_IN
| sel_reg0);
HWIO_AXI_MONITOR_SELECTION_REG0_OUT(HWIO_AXI_MONITOR_SELECTION_REG0_IN
| HWIO_AXI_MONITOR_SELECTION_REG0_ECC_BMSK);
HWIO_AXI_CONFIGURATION_REG_OUT(HWIO_AXI_CONFIGURATION_REG_PPDM_BMSK);
}
/*
FUNCTION pm_axi_update
DESCRIPTION
Set event0, event1 and tenure registers based on the /proc entries.
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void
pm_axi_update()
{
HWIO_AXI_CONFIGURATION_REG_OUT(HWIO_AXI_CONFIGURATION_REG_PPDM_BMSK);
HWIO_AXI_MONITOR_SELECTION_REG0_OUT(HWIO_AXI_MONITOR_SELECTION_REG0_IN
| HWIO_AXI_RESET_ALL);
HWIO_AXI_MONITOR_SELECTION_REG0_OUT(HWIO_AXI_MONITOR_SELECTION_REG0_IN
& HWIO_AXI_DISABLE_ALL);
pm_axi_start();
}
/*
FUNCTION pm_axi_disable
DESCRIPTION
Disable all cntrs.
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void
pm_axi_disable(void)
{
unsigned long sel_reg0;
/*Disable cntrs*/
sel_reg0 = get_axi_sel_reg0();
HWIO_AXI_MONITOR_SELECTION_REG0_OUT(sel_reg0 & AXI_EVTSEL_DISABLE_MASK);
/*Disable clk*/
HWIO_AXI_CONFIGURATION_REG_OUT(HWIO_AXI_CONFIGURATION_REG_DISABLE);
}
/*
FUNCTION pm_axi_enable
DESCRIPTION
Enable all cntrs.
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
void
pm_axi_enable(void)
{
unsigned long sel_reg0;
/*Enable cntrs*/
sel_reg0 = get_axi_sel_reg0();
HWIO_AXI_MONITOR_SELECTION_REG0_OUT(sel_reg0 | 0x6a00);
/*Enable clk*/
HWIO_AXI_CONFIGURATION_REG_OUT(HWIO_AXI_CONFIGURATION_REG_PPDM_BMSK);
}
/*
FUNCTION pm_axi_disable_cnts
DESCRIPTION
Read cycle cntr value
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
unsigned long
pm_get_axi_cycle_count(void)
{
if (HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_IN == 0x0 &&
HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_IN == 0x0) {
/*Set AXI Cycle Counter to enable AXI Monitors*/
HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_OUT(0xffff);
HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_OUT(0xfffe);
}
return 0xfffffffe - ((HWIO_AXI_MONITOR_CYCLE_COUNT_UPPER_REG_IN << 16)
+ HWIO_AXI_MONITOR_CYCLE_COUNT_LOWER_REG_IN);
}
/*
FUNCTION pm_get_axi_evt0_count
DESCRIPTION
Read Event0 cntr value
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
unsigned long
pm_get_axi_evt0_count(void)
{
return (HWIO_AXI_MONITOR_EVENT_UPPER_REG0_IN << 16)
+ HWIO_AXI_MONITOR_EVENT_LOWER_REG0_IN;
}
/*
FUNCTION pm_get_axi_evt1_count
DESCRIPTION
Read Event1 cntr value
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
unsigned long
pm_get_axi_evt1_count(void)
{
return (HWIO_AXI_MONITOR_EVENT_UPPER_REG1_IN << 16)
+ HWIO_AXI_MONITOR_EVENT_LOWER_REG1_IN;
}
/*
FUNCTION pm_get_axi_ten_min_count
DESCRIPTION
Read min tenure cntr value
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
unsigned long
pm_get_axi_ten_min_count(void)
{
return HWIO_AXI_MONITOR_MIN_REG_IN;
}
/*
FUNCTION pm_get_axi_ten_max_count
DESCRIPTION
Read max tenure cntr value
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
unsigned long
pm_get_axi_ten_max_count(void)
{
return HWIO_AXI_MONITOR_MAX_REG_IN;
}
/*
FUNCTION pm_get_axi_ten_total_count
DESCRIPTION
Read total tenure cntr value
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
unsigned long
pm_get_axi_ten_total_count(void)
{
return (HWIO_AXI_MONITOR_TENURE_UPPER_REG_IN << 16)
+ HWIO_AXI_MONITOR_TENURE_LOWER_REG_IN;
}
/*
FUNCTION pm_get_axi_ten_last_count
DESCRIPTION
Read last tenure cntr value
DEPENDENCIES
RETURN VALUE
SIDE EFFECTS
*/
unsigned long
pm_get_axi_ten_last_count(void)
{
return HWIO_AXI_MONITOR_LAST_TENURE_REG_IN;
}
| gpl-2.0 |
jderrick/linux-block | fs/ext4/bitmap.c | 1149 | 2699 | /*
* linux/fs/ext4/bitmap.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*/
#include <linux/buffer_head.h>
#include "ext4.h"
unsigned int ext4_count_free(char *bitmap, unsigned int numchars)
{
return numchars * BITS_PER_BYTE - memweight(bitmap, numchars);
}
int ext4_inode_bitmap_csum_verify(struct super_block *sb, ext4_group_t group,
struct ext4_group_desc *gdp,
struct buffer_head *bh, int sz)
{
__u32 hi;
__u32 provided, calculated;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (!ext4_has_metadata_csum(sb))
return 1;
provided = le16_to_cpu(gdp->bg_inode_bitmap_csum_lo);
calculated = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)bh->b_data, sz);
if (sbi->s_desc_size >= EXT4_BG_INODE_BITMAP_CSUM_HI_END) {
hi = le16_to_cpu(gdp->bg_inode_bitmap_csum_hi);
provided |= (hi << 16);
} else
calculated &= 0xFFFF;
return provided == calculated;
}
void ext4_inode_bitmap_csum_set(struct super_block *sb, ext4_group_t group,
struct ext4_group_desc *gdp,
struct buffer_head *bh, int sz)
{
__u32 csum;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (!ext4_has_metadata_csum(sb))
return;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)bh->b_data, sz);
gdp->bg_inode_bitmap_csum_lo = cpu_to_le16(csum & 0xFFFF);
if (sbi->s_desc_size >= EXT4_BG_INODE_BITMAP_CSUM_HI_END)
gdp->bg_inode_bitmap_csum_hi = cpu_to_le16(csum >> 16);
}
int ext4_block_bitmap_csum_verify(struct super_block *sb, ext4_group_t group,
struct ext4_group_desc *gdp,
struct buffer_head *bh)
{
__u32 hi;
__u32 provided, calculated;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int sz = EXT4_CLUSTERS_PER_GROUP(sb) / 8;
if (!ext4_has_metadata_csum(sb))
return 1;
provided = le16_to_cpu(gdp->bg_block_bitmap_csum_lo);
calculated = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)bh->b_data, sz);
if (sbi->s_desc_size >= EXT4_BG_BLOCK_BITMAP_CSUM_HI_END) {
hi = le16_to_cpu(gdp->bg_block_bitmap_csum_hi);
provided |= (hi << 16);
} else
calculated &= 0xFFFF;
if (provided == calculated)
return 1;
return 0;
}
void ext4_block_bitmap_csum_set(struct super_block *sb, ext4_group_t group,
struct ext4_group_desc *gdp,
struct buffer_head *bh)
{
int sz = EXT4_CLUSTERS_PER_GROUP(sb) / 8;
__u32 csum;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (!ext4_has_metadata_csum(sb))
return;
csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)bh->b_data, sz);
gdp->bg_block_bitmap_csum_lo = cpu_to_le16(csum & 0xFFFF);
if (sbi->s_desc_size >= EXT4_BG_BLOCK_BITMAP_CSUM_HI_END)
gdp->bg_block_bitmap_csum_hi = cpu_to_le16(csum >> 16);
}
| gpl-2.0 |
CaptainThrowback/kernel_htc_m8whl | drivers/bif/qpnp-bsi.c | 1405 | 45792 | /* Copyright (c) 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.
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/atomic.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <linux/spmi.h>
#include <linux/workqueue.h>
#include <linux/bif/driver.h>
#include <linux/qpnp/qpnp-adc.h>
enum qpnp_bsi_irq {
QPNP_BSI_IRQ_ERR,
QPNP_BSI_IRQ_RX,
QPNP_BSI_IRQ_TX,
QPNP_BSI_IRQ_COUNT,
};
enum qpnp_bsi_com_mode {
QPNP_BSI_COM_MODE_IRQ,
QPNP_BSI_COM_MODE_POLL,
};
struct qpnp_bsi_chip {
struct bif_ctrl_desc bdesc;
struct spmi_device *spmi_dev;
struct bif_ctrl_dev *bdev;
struct work_struct slave_irq_work;
u16 base_addr;
u16 batt_id_stat_addr;
int r_pullup_ohm;
int vid_ref_uV;
int tau_index;
int tau_sampling_mask;
enum bif_bus_state state;
enum qpnp_bsi_com_mode com_mode;
int irq[QPNP_BSI_IRQ_COUNT];
atomic_t irq_flag[QPNP_BSI_IRQ_COUNT];
int batt_present_irq;
enum qpnp_vadc_channels batt_id_adc_channel;
struct qpnp_vadc_chip *vadc_dev;
};
#define QPNP_BSI_DRIVER_NAME "qcom,qpnp-bsi"
enum qpnp_bsi_registers {
QPNP_BSI_REG_TYPE = 0x04,
QPNP_BSI_REG_SUBTYPE = 0x05,
QPNP_BSI_REG_STATUS = 0x08,
QPNP_BSI_REG_ENABLE = 0x46,
QPNP_BSI_REG_CLEAR_ERROR = 0x4F,
QPNP_BSI_REG_FORCE_BCL_LOW = 0x51,
QPNP_BSI_REG_TAU_CONFIG = 0x52,
QPNP_BSI_REG_MODE = 0x53,
QPNP_BSI_REG_RX_TX_ENABLE = 0x54,
QPNP_BSI_REG_TX_DATA_LOW = 0x5A,
QPNP_BSI_REG_TX_DATA_HIGH = 0x5B,
QPNP_BSI_REG_TX_CTRL = 0x5D,
QPNP_BSI_REG_RX_DATA_LOW = 0x60,
QPNP_BSI_REG_RX_DATA_HIGH = 0x61,
QPNP_BSI_REG_RX_SOURCE = 0x62,
QPNP_BSI_REG_BSI_ERROR = 0x70,
};
#define QPNP_BSI_TYPE 0x02
#define QPNP_BSI_SUBTYPE 0x10
#define QPNP_BSI_STATUS_ERROR 0x10
#define QPNP_BSI_STATUS_TX_BUSY 0x08
#define QPNP_BSI_STATUS_RX_BUSY 0x04
#define QPNP_BSI_STATUS_TX_GO_BUSY 0x02
#define QPNP_BSI_STATUS_RX_DATA_READY 0x01
#define QPNP_BSI_ENABLE_MASK 0x80
#define QPNP_BSI_ENABLE 0x80
#define QPNP_BSI_DISABLE 0x00
#define QPNP_BSI_TAU_CONFIG_SAMPLE_MASK 0x10
#define QPNP_BSI_TAU_CONFIG_SAMPLE_8X 0x10
#define QPNP_BSI_TAU_CONFIG_SAMPLE_4X 0x00
#define QPNP_BSI_TAU_CONFIG_SPEED_MASK 0x07
#define QPNP_BSI_MODE_TX_PULSE_MASK 0x10
#define QPNP_BSI_MODE_TX_PULSE_INT 0x10
#define QPNP_BSI_MODE_TX_PULSE_DATA 0x00
#define QPNP_BSI_MODE_RX_PULSE_MASK 0x08
#define QPNP_BSI_MODE_RX_PULSE_INT 0x08
#define QPNP_BSI_MODE_RX_PULSE_DATA 0x00
#define QPNP_BSI_MODE_TX_PULSE_T_MASK 0x04
#define QPNP_BSI_MODE_TX_PULSE_T_WAKE 0x04
#define QPNP_BSI_MODE_TX_PULSE_T_1_TAU 0x00
#define QPNP_BSI_MODE_RX_FORMAT_MASK 0x02
#define QPNP_BSI_MODE_RX_FORMAT_17_BIT 0x02
#define QPNP_BSI_MODE_RX_FORMAT_11_BIT 0x00
#define QPNP_BSI_MODE_TX_FORMAT_MASK 0x01
#define QPNP_BSI_MODE_TX_FORMAT_17_BIT 0x01
#define QPNP_BSI_MODE_TX_FORMAT_11_BIT 0x00
#define QPNP_BSI_TX_ENABLE_MASK 0x80
#define QPNP_BSI_TX_ENABLE 0x80
#define QPNP_BSI_TX_DISABLE 0x00
#define QPNP_BSI_RX_ENABLE_MASK 0x40
#define QPNP_BSI_RX_ENABLE 0x40
#define QPNP_BSI_RX_DISABLE 0x00
#define QPNP_BSI_TX_DATA_HIGH_MASK 0x07
#define QPNP_BSI_TX_CTRL_GO 0x01
#define QPNP_BSI_RX_DATA_HIGH_MASK 0x07
#define QPNP_BSI_RX_SRC_LOOPBACK_FLAG 0x10
#define QPNP_BSI_BSI_ERROR_CLEAR 0x80
#define QPNP_SMBB_BAT_IF_BATT_PRES_MASK 0x80
#define QPNP_SMBB_BAT_IF_BATT_ID_MASK 0x01
#define QPNP_BSI_NUM_CLOCK_PERIODS 8
struct qpnp_bsi_tau {
int period_4x_ns[QPNP_BSI_NUM_CLOCK_PERIODS];
int period_8x_ns[QPNP_BSI_NUM_CLOCK_PERIODS];
int period_4x_us[QPNP_BSI_NUM_CLOCK_PERIODS];
int period_8x_us[QPNP_BSI_NUM_CLOCK_PERIODS];
};
/* Tau BIF clock periods in ns supported by BSI for either 4x or 8x sampling. */
static const struct qpnp_bsi_tau qpnp_bsi_tau_period = {
.period_4x_ns = {
150420, 122080, 61040, 31670, 15830, 7920, 3960, 2080
},
.period_8x_ns = {
150420, 122080, 63330, 31670, 15830, 7920, 4170, 2080
},
.period_4x_us = {
151, 122, 61, 32, 16, 8, 4, 2
},
.period_8x_us = {
151, 122, 64, 32, 16, 8, 4, 2
},
};
#define QPNP_BSI_MIN_CLOCK_SPEED_NS 2080
#define QPNP_BSI_MAX_CLOCK_SPEED_NS 150420
#define QPNP_BSI_MIN_PULLUP_OHM 1000
#define QPNP_BSI_MAX_PULLUP_OHM 500000
#define QPNP_BSI_DEFAULT_PULLUP_OHM 100000
#define QPNP_BSI_MIN_VID_REF_UV 500000
#define QPNP_BSI_MAX_VID_REF_UV 5000000
#define QPNP_BSI_DEFAULT_VID_REF_UV 1800000
/* These have units of tau_bif. */
#define QPNP_BSI_MAX_TRANSMIT_CYCLES 46
#define QPNP_BSI_MIN_RECEIVE_CYCLES 24
#define QPNP_BSI_MAX_BUS_QUERY_CYCLES 17
/*
* Maximum time in microseconds for a slave to transition from suspend to active
* state.
*/
#define QPNP_BSI_MAX_SLAVE_ACTIVIATION_DELAY_US 50
/*
* Maximum time in milliseconds for a slave to transition from power down to
* active state.
*/
#define QPNP_BSI_MAX_SLAVE_POWER_UP_DELAY_MS 10
#define QPNP_BSI_POWER_UP_LOW_DELAY_US 240
/*
* Latencies that are used when determining if polling or interrupts should be
* used for a given transaction.
*/
#define QPNP_BSI_MAX_IRQ_LATENCY_US 170
#define QPNP_BSI_MAX_BSI_DATA_READ_LATENCY_US 16
static int qpnp_bsi_set_bus_state(struct bif_ctrl_dev *bdev, int state);
static inline int qpnp_bsi_read(struct qpnp_bsi_chip *chip, u16 addr, u8 *buf,
int len)
{
int rc;
rc = spmi_ext_register_readl(chip->spmi_dev->ctrl,
chip->spmi_dev->sid, chip->base_addr + addr, buf, len);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: spmi_ext_register_readl() failed. sid=%d, addr=%04X, len=%d, rc=%d\n",
__func__, chip->spmi_dev->sid, chip->base_addr + addr,
len, rc);
return rc;
}
static inline int qpnp_bsi_write(struct qpnp_bsi_chip *chip, u16 addr, u8 *buf,
int len)
{
int rc;
rc = spmi_ext_register_writel(chip->spmi_dev->ctrl,
chip->spmi_dev->sid, chip->base_addr + addr, buf, len);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: spmi_ext_register_writel() failed. sid=%d, addr=%04X, len=%d, rc=%d\n",
__func__, chip->spmi_dev->sid, chip->base_addr + addr,
len, rc);
return rc;
}
enum qpnp_bsi_rx_tx_state {
QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF,
QPNP_BSI_RX_TX_STATE_RX_OFF_TX_DATA,
QPNP_BSI_RX_TX_STATE_RX_OFF_TX_INT,
QPNP_BSI_RX_TX_STATE_RX_INT_TX_DATA,
QPNP_BSI_RX_TX_STATE_RX_DATA_TX_DATA,
QPNP_BSI_RX_TX_STATE_RX_INT_TX_OFF,
};
static int qpnp_bsi_rx_tx_config(struct qpnp_bsi_chip *chip,
enum qpnp_bsi_rx_tx_state state)
{
u8 buf[2] = {0, 0};
int rc;
buf[0] = QPNP_BSI_MODE_TX_FORMAT_11_BIT
| QPNP_BSI_MODE_RX_FORMAT_11_BIT;
switch (state) {
case QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF:
buf[0] |= QPNP_BSI_MODE_TX_PULSE_DATA |
QPNP_BSI_MODE_RX_PULSE_DATA;
buf[1] = QPNP_BSI_TX_DISABLE | QPNP_BSI_RX_DISABLE;
break;
case QPNP_BSI_RX_TX_STATE_RX_OFF_TX_DATA:
buf[0] |= QPNP_BSI_MODE_TX_PULSE_DATA |
QPNP_BSI_MODE_RX_PULSE_DATA;
buf[1] = QPNP_BSI_TX_ENABLE | QPNP_BSI_RX_DISABLE;
break;
case QPNP_BSI_RX_TX_STATE_RX_OFF_TX_INT:
buf[0] |= QPNP_BSI_MODE_TX_PULSE_INT |
QPNP_BSI_MODE_RX_PULSE_DATA;
buf[1] = QPNP_BSI_TX_ENABLE | QPNP_BSI_RX_DISABLE;
break;
case QPNP_BSI_RX_TX_STATE_RX_INT_TX_DATA:
buf[0] |= QPNP_BSI_MODE_TX_PULSE_DATA |
QPNP_BSI_MODE_RX_PULSE_INT;
buf[1] = QPNP_BSI_TX_ENABLE | QPNP_BSI_RX_ENABLE;
break;
case QPNP_BSI_RX_TX_STATE_RX_DATA_TX_DATA:
buf[0] |= QPNP_BSI_MODE_TX_PULSE_DATA |
QPNP_BSI_MODE_RX_PULSE_DATA;
buf[1] = QPNP_BSI_TX_ENABLE | QPNP_BSI_RX_ENABLE;
break;
case QPNP_BSI_RX_TX_STATE_RX_INT_TX_OFF:
buf[0] |= QPNP_BSI_MODE_TX_PULSE_DATA |
QPNP_BSI_MODE_RX_PULSE_INT;
buf[1] = QPNP_BSI_TX_DISABLE | QPNP_BSI_RX_DISABLE;
break;
default:
dev_err(&chip->spmi_dev->dev, "%s: invalid state=%d\n",
__func__, state);
return -EINVAL;
}
rc = qpnp_bsi_write(chip, QPNP_BSI_REG_MODE, buf, 2);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
return rc;
}
static void qpnp_bsi_slave_irq_work(struct work_struct *work)
{
struct qpnp_bsi_chip *chip
= container_of(work, struct qpnp_bsi_chip, slave_irq_work);
int rc;
rc = bif_ctrl_notify_slave_irq(chip->bdev);
if (rc)
pr_err("Could not notify BIF core about slave interrupt, rc=%d\n",
rc);
}
static irqreturn_t qpnp_bsi_isr(int irq, void *data)
{
struct qpnp_bsi_chip *chip = data;
bool found = false;
int i;
for (i = 0; i < QPNP_BSI_IRQ_COUNT; i++) {
if (irq == chip->irq[i]) {
found = true;
atomic_cmpxchg(&chip->irq_flag[i], 0, 1);
/* Check if this is a slave interrupt. */
if (i == QPNP_BSI_IRQ_RX
&& chip->state == BIF_BUS_STATE_INTERRUPT) {
/* Slave IRQ makes the bus active. */
qpnp_bsi_rx_tx_config(chip,
QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF);
chip->state = BIF_BUS_STATE_ACTIVE;
schedule_work(&chip->slave_irq_work);
}
}
}
if (!found)
pr_err("Unknown interrupt: %d\n", irq);
return IRQ_HANDLED;
}
static irqreturn_t qpnp_bsi_batt_present_isr(int irq, void *data)
{
struct qpnp_bsi_chip *chip = data;
int rc;
if (!chip->bdev)
return IRQ_HANDLED;
rc = bif_ctrl_notify_battery_changed(chip->bdev);
if (rc)
pr_err("Could not notify about battery state change, rc=%d\n",
rc);
return IRQ_HANDLED;
}
static void qpnp_bsi_set_com_mode(struct qpnp_bsi_chip *chip,
enum qpnp_bsi_com_mode mode)
{
int i;
if (chip->com_mode == mode)
return;
if (mode == QPNP_BSI_COM_MODE_IRQ)
for (i = 0; i < QPNP_BSI_IRQ_COUNT; i++)
enable_irq(chip->irq[i]);
else
for (i = 0; i < QPNP_BSI_IRQ_COUNT; i++)
disable_irq(chip->irq[i]);
chip->com_mode = mode;
}
static inline bool qpnp_bsi_check_irq(struct qpnp_bsi_chip *chip, int irq)
{
return atomic_cmpxchg(&chip->irq_flag[irq], 1, 0);
}
static void qpnp_bsi_clear_irq_flags(struct qpnp_bsi_chip *chip)
{
int i;
for (i = 0; i < QPNP_BSI_IRQ_COUNT; i++)
atomic_set(&chip->irq_flag[i], 0);
}
static inline int qpnp_bsi_get_tau_ns(struct qpnp_bsi_chip *chip)
{
if (chip->tau_sampling_mask == QPNP_BSI_TAU_CONFIG_SAMPLE_4X)
return qpnp_bsi_tau_period.period_4x_ns[chip->tau_index];
else
return qpnp_bsi_tau_period.period_8x_ns[chip->tau_index];
}
static inline int qpnp_bsi_get_tau_us(struct qpnp_bsi_chip *chip)
{
if (chip->tau_sampling_mask == QPNP_BSI_TAU_CONFIG_SAMPLE_4X)
return qpnp_bsi_tau_period.period_4x_us[chip->tau_index];
else
return qpnp_bsi_tau_period.period_8x_us[chip->tau_index];
}
/* Checks if BSI is in an error state and clears the error if it is. */
static int qpnp_bsi_clear_bsi_error(struct qpnp_bsi_chip *chip)
{
int rc, delay_us;
u8 reg;
rc = qpnp_bsi_read(chip, QPNP_BSI_REG_BSI_ERROR, ®, 1);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_read() failed, rc=%d\n",
__func__, rc);
return rc;
}
if (reg > 0) {
/*
* Delay before clearing the BSI error in case a transaction is
* still in flight.
*/
delay_us = QPNP_BSI_MAX_TRANSMIT_CYCLES
* qpnp_bsi_get_tau_us(chip);
udelay(delay_us);
pr_info("PMIC BSI module in error state, error=%d\n", reg);
reg = QPNP_BSI_BSI_ERROR_CLEAR;
rc = qpnp_bsi_write(chip, QPNP_BSI_REG_CLEAR_ERROR, ®, 1);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
}
return rc;
}
static int qpnp_bsi_get_bsi_error(struct qpnp_bsi_chip *chip)
{
int rc;
u8 reg;
rc = qpnp_bsi_read(chip, QPNP_BSI_REG_BSI_ERROR, ®, 1);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_read() failed, rc=%d\n",
__func__, rc);
return rc;
}
return reg;
}
static int qpnp_bsi_wait_for_tx(struct qpnp_bsi_chip *chip, int timeout)
{
int rc = 0;
/* Wait for TX or ERR IRQ. */
while (timeout > 0) {
if (qpnp_bsi_check_irq(chip, QPNP_BSI_IRQ_ERR)) {
dev_err(&chip->spmi_dev->dev, "%s: transaction error occurred, BSI error=%d\n",
__func__, qpnp_bsi_get_bsi_error(chip));
return -EIO;
}
if (qpnp_bsi_check_irq(chip, QPNP_BSI_IRQ_TX))
break;
udelay(1);
timeout--;
}
if (timeout == 0) {
rc = -ETIMEDOUT;
dev_err(&chip->spmi_dev->dev, "%s: transaction timed out, no interrupts received, rc=%d\n",
__func__, rc);
return rc;
}
return rc;
}
static int qpnp_bsi_issue_transaction(struct qpnp_bsi_chip *chip,
int transaction, u8 data)
{
int rc;
u8 buf[4];
/* MIPI_BIF_DATA_TX_0 = BIF word bits 7 to 0 */
buf[0] = data;
/* MIPI_BIF_DATA_TX_1 = BIF word BCF, bits 9 to 8 */
buf[1] = transaction & QPNP_BSI_TX_DATA_HIGH_MASK;
/* MIPI_BIF_DATA_TX_2 ignored */
buf[2] = 0x00;
/* MIPI_BIF_TX_CTL bit 0 written to start the transaction. */
buf[3] = QPNP_BSI_TX_CTRL_GO;
/* Write the TX_DATA bytes and initiate the transaction. */
rc = qpnp_bsi_write(chip, QPNP_BSI_REG_TX_DATA_LOW, buf, 4);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
return rc;
}
static int qpnp_bsi_issue_transaction_wait_for_tx(struct qpnp_bsi_chip *chip,
int transaction, u8 data)
{
int rc, timeout;
rc = qpnp_bsi_issue_transaction(chip, transaction, data);
if (rc)
return rc;
timeout = QPNP_BSI_MAX_TRANSMIT_CYCLES * qpnp_bsi_get_tau_us(chip)
+ QPNP_BSI_MAX_IRQ_LATENCY_US;
rc = qpnp_bsi_wait_for_tx(chip, timeout);
return rc;
}
static int qpnp_bsi_wait_for_rx(struct qpnp_bsi_chip *chip, int timeout)
{
int rc = 0;
/* Wait for RX IRQ to indicate that data is ready to read. */
while (timeout > 0) {
if (qpnp_bsi_check_irq(chip, QPNP_BSI_IRQ_ERR)) {
dev_err(&chip->spmi_dev->dev, "%s: transaction error occurred, BSI error=%d\n",
__func__, qpnp_bsi_get_bsi_error(chip));
return -EIO;
}
if (qpnp_bsi_check_irq(chip, QPNP_BSI_IRQ_RX))
break;
udelay(1);
timeout--;
}
if (timeout == 0)
rc = -ETIMEDOUT;
return rc;
}
static int qpnp_bsi_bus_transaction(struct bif_ctrl_dev *bdev, int transaction,
u8 data)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
int rc;
qpnp_bsi_set_com_mode(chip, QPNP_BSI_COM_MODE_IRQ);
rc = qpnp_bsi_set_bus_state(bdev, BIF_BUS_STATE_ACTIVE);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: failed to set bus state, rc=%d\n",
__func__, rc);
return rc;
}
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_OFF_TX_DATA);
if (rc)
return rc;
rc = qpnp_bsi_clear_bsi_error(chip);
if (rc)
return rc;
qpnp_bsi_clear_irq_flags(chip);
rc = qpnp_bsi_issue_transaction_wait_for_tx(chip, transaction, data);
if (rc)
return rc;
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF);
return rc;
}
static int qpnp_bsi_bus_transaction_query(struct bif_ctrl_dev *bdev,
int transaction, u8 data, bool *query_response)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
int rc, timeout;
qpnp_bsi_set_com_mode(chip, QPNP_BSI_COM_MODE_IRQ);
rc = qpnp_bsi_set_bus_state(bdev, BIF_BUS_STATE_ACTIVE);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: failed to set bus state, rc=%d\n",
__func__, rc);
return rc;
}
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_INT_TX_DATA);
if (rc)
return rc;
rc = qpnp_bsi_clear_bsi_error(chip);
if (rc)
return rc;
qpnp_bsi_clear_irq_flags(chip);
rc = qpnp_bsi_issue_transaction_wait_for_tx(chip, transaction, data);
if (rc)
return rc;
timeout = QPNP_BSI_MAX_BUS_QUERY_CYCLES * qpnp_bsi_get_tau_us(chip)
+ QPNP_BSI_MAX_IRQ_LATENCY_US;
rc = qpnp_bsi_wait_for_rx(chip, timeout);
if (rc == 0) {
*query_response = true;
} else if (rc == -ETIMEDOUT) {
*query_response = false;
rc = 0;
}
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF);
return rc;
}
static int qpnp_bsi_bus_transaction_read(struct bif_ctrl_dev *bdev,
int transaction, u8 data, int *response)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
int rc, timeout;
u8 buf[3];
qpnp_bsi_set_com_mode(chip, QPNP_BSI_COM_MODE_IRQ);
rc = qpnp_bsi_set_bus_state(bdev, BIF_BUS_STATE_ACTIVE);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: failed to set bus state, rc=%d\n",
__func__, rc);
return rc;
}
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_DATA_TX_DATA);
if (rc)
return rc;
rc = qpnp_bsi_clear_bsi_error(chip);
if (rc)
return rc;
qpnp_bsi_clear_irq_flags(chip);
rc = qpnp_bsi_issue_transaction_wait_for_tx(chip, transaction, data);
if (rc)
return rc;
timeout = QPNP_BSI_MAX_TRANSMIT_CYCLES * qpnp_bsi_get_tau_us(chip)
+ QPNP_BSI_MAX_IRQ_LATENCY_US;
rc = qpnp_bsi_wait_for_rx(chip, timeout);
if (rc) {
if (rc == -ETIMEDOUT) {
/*
* No error message is printed in this case in order
* to provide silent operation when checking if a slave
* is selected using the transaction query bus command.
*/
dev_dbg(&chip->spmi_dev->dev, "%s: transaction timed out, no interrupts received, rc=%d\n",
__func__, rc);
}
return rc;
}
/* Read the RX_DATA bytes. */
rc = qpnp_bsi_read(chip, QPNP_BSI_REG_RX_DATA_LOW, buf, 3);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_read() failed, rc=%d\n",
__func__, rc);
return rc;
}
if (buf[2] & QPNP_BSI_RX_SRC_LOOPBACK_FLAG) {
rc = -EIO;
dev_err(&chip->spmi_dev->dev, "%s: unexpected loopback data read, rc=%d\n",
__func__, rc);
return rc;
}
*response = ((int)(buf[1] & QPNP_BSI_RX_DATA_HIGH_MASK) << 8) | buf[0];
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF);
return 0;
}
/*
* Wait for RX_FLOW_STATUS to be set to 1 which indicates that another BIF word
* can be read from PMIC registers.
*/
static int qpnp_bsi_wait_for_rx_data(struct qpnp_bsi_chip *chip)
{
int rc = 0;
int timeout;
u8 reg;
timeout = QPNP_BSI_MAX_TRANSMIT_CYCLES * qpnp_bsi_get_tau_us(chip);
/* Wait for RX_FLOW_STATUS == 1 or ERR_FLAG == 1. */
while (timeout > 0) {
rc = qpnp_bsi_read(chip, QPNP_BSI_REG_STATUS, ®, 1);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
return rc;
}
if (reg & QPNP_BSI_STATUS_ERROR) {
dev_err(&chip->spmi_dev->dev, "%s: transaction error occurred, BSI error=%d\n",
__func__, qpnp_bsi_get_bsi_error(chip));
return -EIO;
}
if (reg & QPNP_BSI_STATUS_RX_DATA_READY) {
/* BSI RX has data word latched. */
return 0;
}
udelay(1);
timeout--;
}
rc = -ETIMEDOUT;
dev_err(&chip->spmi_dev->dev, "%s: transaction timed out, RX_FLOW_STATUS never set to 1, rc=%d\n",
__func__, rc);
return rc;
}
/*
* Wait for TX_GO_STATUS to be set to 0 which indicates that another BIF word
* can be enqueued.
*/
static int qpnp_bsi_wait_for_tx_go(struct qpnp_bsi_chip *chip)
{
int rc = 0;
int timeout;
u8 reg;
timeout = QPNP_BSI_MAX_TRANSMIT_CYCLES * qpnp_bsi_get_tau_us(chip);
/* Wait for TX_GO_STATUS == 0 or ERR_FLAG == 1. */
while (timeout > 0) {
rc = qpnp_bsi_read(chip, QPNP_BSI_REG_STATUS, ®, 1);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
return rc;
}
if (reg & QPNP_BSI_STATUS_ERROR) {
dev_err(&chip->spmi_dev->dev, "%s: transaction error occurred, BSI error=%d\n",
__func__, qpnp_bsi_get_bsi_error(chip));
return -EIO;
}
if (!(reg & QPNP_BSI_STATUS_TX_GO_BUSY)) {
/* BSI TX is ready to accept the next word. */
return 0;
}
udelay(1);
timeout--;
}
rc = -ETIMEDOUT;
dev_err(&chip->spmi_dev->dev, "%s: transaction timed out, TX_GO_STATUS never set to 0, rc=%d\n",
__func__, rc);
return rc;
}
/*
* Wait for TX_BUSY to be set to 0 which indicates that the TX data has been
* successfully transmitted.
*/
static int qpnp_bsi_wait_for_tx_idle(struct qpnp_bsi_chip *chip)
{
int rc = 0;
int timeout;
u8 reg;
timeout = QPNP_BSI_MAX_TRANSMIT_CYCLES * qpnp_bsi_get_tau_us(chip);
/* Wait for TX_BUSY == 0 or ERR_FLAG == 1. */
while (timeout > 0) {
rc = qpnp_bsi_read(chip, QPNP_BSI_REG_STATUS, ®, 1);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
return rc;
}
if (reg & QPNP_BSI_STATUS_ERROR) {
dev_err(&chip->spmi_dev->dev, "%s: transaction error occurred, BSI error=%d\n",
__func__, qpnp_bsi_get_bsi_error(chip));
return -EIO;
}
if (!(reg & QPNP_BSI_STATUS_TX_BUSY)) {
/* BSI TX is idle. */
return 0;
}
udelay(1);
timeout--;
}
rc = -ETIMEDOUT;
dev_err(&chip->spmi_dev->dev, "%s: transaction timed out, TX_BUSY never set to 0, rc=%d\n",
__func__, rc);
return rc;
}
/*
* For burst read length greater than 1, send necessary RBL and RBE BIF bus
* commands.
*/
static int qpnp_bsi_send_burst_length(struct qpnp_bsi_chip *chip, int burst_len)
{
int rc = 0;
/*
* Send burst read length bus commands according to the following:
*
* 1 --> No RBE or RBL
* 2 - 15 = x --> RBLx
* 16 - 255 = 16 * y + x --> RBEy and RBLx (RBL0 not sent)
* 256 --> RBL0
*/
if (burst_len == 256) {
rc = qpnp_bsi_issue_transaction(chip, BIF_TRANS_BC,
BIF_CMD_RBL);
if (rc)
return rc;
rc = qpnp_bsi_wait_for_tx_go(chip);
if (rc)
return rc;
} else if (burst_len >= 16) {
rc = qpnp_bsi_issue_transaction(chip, BIF_TRANS_BC,
BIF_CMD_RBE + (burst_len / 16));
if (rc)
return rc;
rc = qpnp_bsi_wait_for_tx_go(chip);
if (rc)
return rc;
}
if (burst_len % 16 && burst_len > 1) {
rc = qpnp_bsi_issue_transaction(chip, BIF_TRANS_BC,
BIF_CMD_RBL + (burst_len % 16));
if (rc)
return rc;
rc = qpnp_bsi_wait_for_tx_go(chip);
if (rc)
return rc;
}
return rc;
}
/* Perform validation steps on received BIF data. */
static int qpnp_bsi_validate_rx_data(struct qpnp_bsi_chip *chip, int response,
u8 rx2_data, bool last_word)
{
int err = -EIO;
if (rx2_data & QPNP_BSI_RX_SRC_LOOPBACK_FLAG) {
dev_err(&chip->spmi_dev->dev, "%s: unexpected loopback data read, rc=%d\n",
__func__, err);
return err;
}
if (!(response & BIF_SLAVE_RD_ACK)) {
dev_err(&chip->spmi_dev->dev, "%s: BIF register read error=0x%02X\n",
__func__, response & BIF_SLAVE_RD_ERR);
return err;
}
if (last_word && !(response & BIF_SLAVE_RD_EOT)) {
dev_err(&chip->spmi_dev->dev, "%s: BIF register read error, last RD packet has EOT=0\n",
__func__);
return err;
} else if (!last_word && (response & BIF_SLAVE_RD_EOT)) {
dev_err(&chip->spmi_dev->dev, "%s: BIF register read error, RD packet other than last has EOT=1\n",
__func__);
return err;
}
return 0;
}
/* Performs all BIF transactions in order to utilize burst reads. */
static int qpnp_bsi_read_slave_registers(struct bif_ctrl_dev *bdev, u16 addr,
u8 *data, int len)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
int response = 0;
unsigned long flags;
int rc, rc2, i, burst_len;
u8 buf[3];
qpnp_bsi_set_com_mode(chip, QPNP_BSI_COM_MODE_POLL);
rc = qpnp_bsi_set_bus_state(bdev, BIF_BUS_STATE_ACTIVE);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: failed to set bus state, rc=%d\n",
__func__, rc);
return rc;
}
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_DATA_TX_DATA);
if (rc)
return rc;
rc = qpnp_bsi_clear_bsi_error(chip);
if (rc)
return rc;
qpnp_bsi_clear_irq_flags(chip);
while (len > 0) {
burst_len = min(len, 256);
rc = qpnp_bsi_send_burst_length(chip, burst_len);
if (rc)
return rc;
rc = qpnp_bsi_issue_transaction(chip, BIF_TRANS_ERA, addr >> 8);
if (rc)
return rc;
rc = qpnp_bsi_wait_for_tx_go(chip);
if (rc)
return rc;
/* Perform burst read in atomic context. */
local_irq_save(flags);
rc = qpnp_bsi_issue_transaction(chip, BIF_TRANS_RRA,
addr & 0xFF);
if (rc)
goto burst_err;
for (i = 0; i < burst_len; i++) {
rc = qpnp_bsi_wait_for_rx_data(chip);
if (rc)
goto burst_err;
/* Read the RX_DATA bytes. */
rc = qpnp_bsi_read(chip, QPNP_BSI_REG_RX_DATA_LOW, buf,
3);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_read() failed, rc=%d\n",
__func__, rc);
goto burst_err;
}
response = ((buf[1] & QPNP_BSI_RX_DATA_HIGH_MASK) << 8)
| buf[0];
rc = qpnp_bsi_validate_rx_data(chip, response, buf[2],
i == burst_len - 1);
if (rc)
goto burst_err;
data[i] = buf[0];
}
local_irq_restore(flags);
addr += burst_len;
data += burst_len;
len -= burst_len;
}
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF);
return rc;
burst_err:
local_irq_restore(flags);
rc2 = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF);
if (rc2 < 0)
rc = rc2;
return rc;
}
/* Performs all BIF transactions in order to utilize burst writes. */
static int qpnp_bsi_write_slave_registers(struct bif_ctrl_dev *bdev, u16 addr,
const u8 *data, int len)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
unsigned long flags;
int rc, rc2, i;
qpnp_bsi_set_com_mode(chip, QPNP_BSI_COM_MODE_POLL);
rc = qpnp_bsi_set_bus_state(bdev, BIF_BUS_STATE_ACTIVE);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: failed to set bus state, rc=%d\n",
__func__, rc);
return rc;
}
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_OFF_TX_DATA);
if (rc)
return rc;
rc = qpnp_bsi_clear_bsi_error(chip);
if (rc)
return rc;
qpnp_bsi_clear_irq_flags(chip);
rc = qpnp_bsi_issue_transaction(chip, BIF_TRANS_ERA, addr >> 8);
if (rc)
return rc;
rc = qpnp_bsi_wait_for_tx_go(chip);
if (rc)
return rc;
rc = qpnp_bsi_issue_transaction(chip, BIF_TRANS_WRA, addr & 0xFF);
if (rc)
return rc;
rc = qpnp_bsi_wait_for_tx_go(chip);
if (rc)
return rc;
/* Perform burst write in atomic context. */
local_irq_save(flags);
for (i = 0; i < len; i++) {
rc = qpnp_bsi_issue_transaction(chip, BIF_TRANS_WD, data[i]);
if (rc)
goto burst_err;
rc = qpnp_bsi_wait_for_tx_go(chip);
if (rc)
goto burst_err;
}
rc = qpnp_bsi_wait_for_tx_idle(chip);
if (rc)
goto burst_err;
local_irq_restore(flags);
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF);
return rc;
burst_err:
local_irq_restore(flags);
rc2 = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_OFF_TX_OFF);
if (rc2 < 0)
rc = rc2;
return rc;
}
static int qpnp_bsi_bus_set_interrupt_mode(struct bif_ctrl_dev *bdev)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
int rc;
qpnp_bsi_set_com_mode(chip, QPNP_BSI_COM_MODE_IRQ);
/*
* Temporarily change the bus to active state so that the EINT command
* can be issued.
*/
rc = qpnp_bsi_set_bus_state(bdev, BIF_BUS_STATE_ACTIVE);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: failed to set bus state, rc=%d\n",
__func__, rc);
return rc;
}
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_INT_TX_DATA);
if (rc)
return rc;
/*
* Set the bus state to interrupt mode so that an RX interrupt which
* occurs immediately after issuing the EINT command is handled
* properly.
*/
chip->state = BIF_BUS_STATE_INTERRUPT;
rc = qpnp_bsi_clear_bsi_error(chip);
if (rc)
return rc;
qpnp_bsi_clear_irq_flags(chip);
/* Send EINT bus command. */
rc = qpnp_bsi_issue_transaction_wait_for_tx(chip, BIF_TRANS_BC,
BIF_CMD_EINT);
if (rc)
return rc;
rc = qpnp_bsi_rx_tx_config(chip, QPNP_BSI_RX_TX_STATE_RX_INT_TX_OFF);
return rc;
}
static int qpnp_bsi_bus_set_active_mode(struct bif_ctrl_dev *bdev,
int prev_state)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
int rc;
u8 buf[2];
rc = qpnp_bsi_clear_bsi_error(chip);
if (rc)
return rc;
buf[0] = QPNP_BSI_MODE_TX_PULSE_INT |
QPNP_BSI_MODE_RX_PULSE_DATA;
buf[1] = QPNP_BSI_TX_ENABLE | QPNP_BSI_RX_DISABLE;
if (prev_state == BIF_BUS_STATE_INTERRUPT)
buf[0] |= QPNP_BSI_MODE_TX_PULSE_T_1_TAU;
else
buf[0] |= QPNP_BSI_MODE_TX_PULSE_T_WAKE;
rc = qpnp_bsi_write(chip, QPNP_BSI_REG_MODE, buf, 2);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
return rc;
}
buf[0] = QPNP_BSI_TX_CTRL_GO;
/* Initiate BCL low pulse. */
rc = qpnp_bsi_write(chip, QPNP_BSI_REG_TX_CTRL, buf, 1);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
return rc;
}
switch (prev_state) {
case BIF_BUS_STATE_INTERRUPT:
udelay(qpnp_bsi_get_tau_us(chip) * 4);
break;
case BIF_BUS_STATE_STANDBY:
udelay(qpnp_bsi_get_tau_us(chip)
+ QPNP_BSI_MAX_SLAVE_ACTIVIATION_DELAY_US
+ QPNP_BSI_POWER_UP_LOW_DELAY_US);
break;
case BIF_BUS_STATE_POWER_DOWN:
case BIF_BUS_STATE_MASTER_DISABLED:
msleep(QPNP_BSI_MAX_SLAVE_POWER_UP_DELAY_MS);
break;
}
return rc;
}
static int qpnp_bsi_get_bus_state(struct bif_ctrl_dev *bdev)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
return chip->state;
}
static int qpnp_bsi_set_bus_state(struct bif_ctrl_dev *bdev, int state)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
int rc = 0;
u8 reg;
if (state == chip->state)
return 0;
if (chip->state == BIF_BUS_STATE_MASTER_DISABLED) {
/*
* Enable the BSI peripheral when transitioning from a disabled
* bus state to any of the active bus states so that BIF
* transactions can take place.
*/
reg = QPNP_BSI_ENABLE;
rc = qpnp_bsi_write(chip, QPNP_BSI_REG_ENABLE, ®, 1);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
return rc;
}
}
switch (state) {
case BIF_BUS_STATE_MASTER_DISABLED:
/* Disable the BSI peripheral. */
reg = QPNP_BSI_DISABLE;
rc = qpnp_bsi_write(chip, QPNP_BSI_REG_ENABLE, ®, 1);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
break;
case BIF_BUS_STATE_POWER_DOWN:
rc = qpnp_bsi_bus_transaction(bdev, BIF_TRANS_BC, BIF_CMD_PDWN);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: failed to enable power down mode, rc=%d\n",
__func__, rc);
break;
case BIF_BUS_STATE_STANDBY:
rc = qpnp_bsi_bus_transaction(bdev, BIF_TRANS_BC, BIF_CMD_STBY);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: failed to enable standby mode, rc=%d\n",
__func__, rc);
break;
case BIF_BUS_STATE_ACTIVE:
rc = qpnp_bsi_bus_set_active_mode(bdev, chip->state);
if (rc)
dev_err(&chip->spmi_dev->dev, "%s: failed to enable active mode, rc=%d\n",
__func__, rc);
break;
case BIF_BUS_STATE_INTERRUPT:
/*
* qpnp_bsi_bus_set_interrupt_mode() internally sets
* chip->state = BIF_BUS_STATE_INTERRUPT immediately before
* issuing the EINT command.
*/
rc = qpnp_bsi_bus_set_interrupt_mode(bdev);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: failed to enable interrupt mode, rc=%d\n",
__func__, rc);
} else if (chip->state == BIF_BUS_STATE_ACTIVE) {
/*
* A slave interrupt was received immediately after
* issuing the EINT command. Therefore, stay in active
* communication mode.
*/
state = BIF_BUS_STATE_ACTIVE;
}
break;
default:
rc = -EINVAL;
dev_err(&chip->spmi_dev->dev, "%s: invalid state=%d\n",
__func__, state);
}
if (!rc)
chip->state = state;
return rc;
}
/* Returns the smallest tau_bif that is greater than or equal to period_ns. */
static int qpnp_bsi_tau_bif_higher(int period_ns, int sample_mask)
{
const int *supported_period_ns =
(sample_mask == QPNP_BSI_TAU_CONFIG_SAMPLE_4X ?
qpnp_bsi_tau_period.period_4x_ns :
qpnp_bsi_tau_period.period_8x_ns);
int smallest_tau_bif = INT_MAX;
int i;
for (i = QPNP_BSI_NUM_CLOCK_PERIODS - 1; i >= 0; i--) {
if (period_ns <= supported_period_ns[i]) {
smallest_tau_bif = supported_period_ns[i];
break;
}
}
return smallest_tau_bif;
}
/* Returns the largest tau_bif that is less than or equal to period_ns. */
static int qpnp_bsi_tau_bif_lower(int period_ns, int sample_mask)
{
const int *supported_period_ns =
(sample_mask == QPNP_BSI_TAU_CONFIG_SAMPLE_4X ?
qpnp_bsi_tau_period.period_4x_ns :
qpnp_bsi_tau_period.period_8x_ns);
int largest_tau_bif = 0;
int i;
for (i = 0; i < QPNP_BSI_NUM_CLOCK_PERIODS; i++) {
if (period_ns >= supported_period_ns[i]) {
largest_tau_bif = supported_period_ns[i];
break;
}
}
return largest_tau_bif;
}
/*
* Moves period_ns into allowed range and then sets tau bif to the period that
* is greater than or equal to period_ns.
*/
static int qpnp_bsi_set_tau_bif(struct qpnp_bsi_chip *chip, int period_ns)
{
const int *supported_period_ns =
(chip->tau_sampling_mask == QPNP_BSI_TAU_CONFIG_SAMPLE_4X ?
qpnp_bsi_tau_period.period_4x_ns :
qpnp_bsi_tau_period.period_8x_ns);
int idx = 0;
int i, rc;
u8 reg;
if (period_ns < chip->bdesc.bus_clock_min_ns)
period_ns = chip->bdesc.bus_clock_min_ns;
else if (period_ns > chip->bdesc.bus_clock_max_ns)
period_ns = chip->bdesc.bus_clock_max_ns;
for (i = QPNP_BSI_NUM_CLOCK_PERIODS - 1; i >= 0; i--) {
if (period_ns <= supported_period_ns[i]) {
idx = i;
break;
}
}
/* Set the tau BIF clock period and sampling rate. */
reg = chip->tau_sampling_mask | idx;
rc = qpnp_bsi_write(chip, QPNP_BSI_REG_TAU_CONFIG, ®, 1);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_bsi_write() failed, rc=%d\n",
__func__, rc);
return rc;
}
chip->tau_index = idx;
return 0;
}
static int qpnp_bsi_get_bus_period(struct bif_ctrl_dev *bdev)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
return qpnp_bsi_get_tau_ns(chip);
}
static int qpnp_bsi_set_bus_period(struct bif_ctrl_dev *bdev, int period_ns)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
return qpnp_bsi_set_tau_bif(chip, period_ns);
}
static int qpnp_bsi_get_battery_rid(struct bif_ctrl_dev *bdev)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
struct qpnp_vadc_result adc_result;
int rid_ohm, vid_uV, rc;
s64 temp;
if (chip->batt_id_adc_channel >= ADC_MAX_NUM) {
dev_err(&chip->spmi_dev->dev, "%s: no ADC channel specified for Rid measurement\n",
__func__);
return -ENXIO;
}
rc = qpnp_vadc_read(chip->vadc_dev, chip->batt_id_adc_channel,
&adc_result);
if (!rc) {
vid_uV = adc_result.physical;
if (chip->vid_ref_uV - vid_uV <= 0) {
rid_ohm = INT_MAX;
} else {
temp = (s64)chip->r_pullup_ohm * (s64)vid_uV;
do_div(temp, chip->vid_ref_uV - vid_uV);
if (temp > INT_MAX)
rid_ohm = INT_MAX;
else
rid_ohm = temp;
}
} else {
dev_err(&chip->spmi_dev->dev, "%s: qpnp_vadc_read(%d) failed, rc=%d\n",
__func__, chip->batt_id_adc_channel, rc);
rid_ohm = rc;
}
return rid_ohm;
}
/*
* Returns 1 if a battery pack is present on the BIF bus, 0 if a battery pack
* is not present, or errno if detection fails.
*
* Battery detection is based upon the idle BCL voltage.
*/
static int qpnp_bsi_get_battery_presence(struct bif_ctrl_dev *bdev)
{
struct qpnp_bsi_chip *chip = bdev_get_drvdata(bdev);
u8 reg = 0x00;
int rc;
rc = spmi_ext_register_readl(chip->spmi_dev->ctrl, chip->spmi_dev->sid,
chip->batt_id_stat_addr, ®, 1);
if (rc) {
dev_err(&chip->spmi_dev->dev, "%s: spmi_ext_register_readl() failed, rc=%d\n",
__func__, rc);
return rc;
}
return !!(reg & QPNP_SMBB_BAT_IF_BATT_PRES_MASK);
}
static struct bif_ctrl_ops qpnp_bsi_ops = {
.bus_transaction = qpnp_bsi_bus_transaction,
.bus_transaction_query = qpnp_bsi_bus_transaction_query,
.bus_transaction_read = qpnp_bsi_bus_transaction_read,
.get_bus_state = qpnp_bsi_get_bus_state,
.set_bus_state = qpnp_bsi_set_bus_state,
.get_bus_period = qpnp_bsi_get_bus_period,
.set_bus_period = qpnp_bsi_set_bus_period,
.read_slave_registers = qpnp_bsi_read_slave_registers,
.write_slave_registers = qpnp_bsi_write_slave_registers,
.get_battery_rid = qpnp_bsi_get_battery_rid,
.get_battery_presence = qpnp_bsi_get_battery_presence,
};
/* Load all BSI properties from device tree. */
static int __devinit qpnp_bsi_parse_dt(struct qpnp_bsi_chip *chip,
struct spmi_device *spmi)
{
struct device *dev = &spmi->dev;
struct device_node *node = spmi->dev.of_node;
struct resource *res;
int rc, temp;
chip->batt_id_adc_channel = ADC_MAX_NUM;
rc = of_property_read_u32(node, "qcom,channel-num",
&chip->batt_id_adc_channel);
if (!rc && (chip->batt_id_adc_channel < 0
|| chip->batt_id_adc_channel >= ADC_MAX_NUM)) {
dev_err(dev, "%s: invalid qcom,channel-num=%d specified\n",
__func__, chip->batt_id_adc_channel);
return -EINVAL;
}
chip->r_pullup_ohm = QPNP_BSI_DEFAULT_PULLUP_OHM;
rc = of_property_read_u32(node, "qcom,pullup-ohms",
&chip->r_pullup_ohm);
if (!rc && (chip->r_pullup_ohm < QPNP_BSI_MIN_PULLUP_OHM ||
chip->r_pullup_ohm > QPNP_BSI_MAX_PULLUP_OHM)) {
dev_err(dev, "%s: invalid qcom,pullup-ohms=%d property value\n",
__func__, chip->r_pullup_ohm);
return -EINVAL;
}
chip->vid_ref_uV = QPNP_BSI_DEFAULT_VID_REF_UV;
rc = of_property_read_u32(node, "qcom,vref-microvolts",
&chip->vid_ref_uV);
if (!rc && (chip->vid_ref_uV < QPNP_BSI_MIN_VID_REF_UV ||
chip->vid_ref_uV > QPNP_BSI_MAX_VID_REF_UV)) {
dev_err(dev, "%s: invalid qcom,vref-microvolts=%d property value\n",
__func__, chip->vid_ref_uV);
return -EINVAL;
}
res = spmi_get_resource_byname(spmi, NULL, IORESOURCE_MEM, "bsi-base");
if (!res) {
dev_err(dev, "%s: node is missing BSI base address\n",
__func__);
return -EINVAL;
}
chip->base_addr = res->start;
res = spmi_get_resource_byname(spmi, NULL, IORESOURCE_MEM,
"batt-id-status");
if (!res) {
dev_err(dev, "%s: node is missing BATT_ID status address\n",
__func__);
return -EINVAL;
}
chip->batt_id_stat_addr = res->start;
chip->bdesc.name = spmi_get_primary_dev_name(spmi);
if (!chip->bdesc.name) {
dev_err(dev, "%s: label binding undefined for node %s\n",
__func__, spmi->dev.of_node->full_name);
return -EINVAL;
}
/* Use maximum range by default. */
chip->bdesc.bus_clock_min_ns = QPNP_BSI_MIN_CLOCK_SPEED_NS;
chip->bdesc.bus_clock_max_ns = QPNP_BSI_MAX_CLOCK_SPEED_NS;
chip->tau_sampling_mask = QPNP_BSI_TAU_CONFIG_SAMPLE_4X;
rc = of_property_read_u32(node, "qcom,sample-rate", &temp);
if (rc == 0) {
if (temp == 4) {
chip->tau_sampling_mask = QPNP_BSI_TAU_CONFIG_SAMPLE_4X;
} else if (temp == 8) {
chip->tau_sampling_mask = QPNP_BSI_TAU_CONFIG_SAMPLE_8X;
} else {
dev_err(dev, "%s: invalid qcom,sample-rate=%d. Only values of 4 and 8 are supported.\n",
__func__, temp);
return -EINVAL;
}
}
rc = of_property_read_u32(node, "qcom,min-clock-period", &temp);
if (rc == 0)
chip->bdesc.bus_clock_min_ns = qpnp_bsi_tau_bif_higher(temp,
chip->tau_sampling_mask);
rc = of_property_read_u32(node, "qcom,max-clock-period", &temp);
if (rc == 0)
chip->bdesc.bus_clock_max_ns = qpnp_bsi_tau_bif_lower(temp,
chip->tau_sampling_mask);
if (chip->bdesc.bus_clock_min_ns > chip->bdesc.bus_clock_max_ns) {
dev_err(dev, "%s: invalid qcom,min/max-clock-period.\n",
__func__);
return -EINVAL;
}
chip->irq[QPNP_BSI_IRQ_ERR] = spmi_get_irq_byname(spmi, NULL, "err");
if (chip->irq[QPNP_BSI_IRQ_ERR] < 0) {
dev_err(dev, "%s: node is missing err irq\n", __func__);
return chip->irq[QPNP_BSI_IRQ_ERR];
}
chip->irq[QPNP_BSI_IRQ_RX] = spmi_get_irq_byname(spmi, NULL, "rx");
if (chip->irq[QPNP_BSI_IRQ_RX] < 0) {
dev_err(dev, "%s: node is missing rx irq\n", __func__);
return chip->irq[QPNP_BSI_IRQ_RX];
}
chip->irq[QPNP_BSI_IRQ_TX] = spmi_get_irq_byname(spmi, NULL, "tx");
if (chip->irq[QPNP_BSI_IRQ_TX] < 0) {
dev_err(dev, "%s: node is missing tx irq\n", __func__);
return chip->irq[QPNP_BSI_IRQ_TX];
}
chip->batt_present_irq = spmi_get_irq_byname(spmi, NULL,
"batt-present");
if (chip->batt_present_irq < 0) {
dev_err(dev, "%s: node is missing batt-present irq\n",
__func__);
return chip->batt_present_irq;
}
return rc;
}
/* Request all BSI and battery presence IRQs and set them as wakeable. */
static int __devinit qpnp_bsi_init_irqs(struct qpnp_bsi_chip *chip,
struct device *dev)
{
int rc;
rc = devm_request_irq(dev, chip->irq[QPNP_BSI_IRQ_ERR],
qpnp_bsi_isr, IRQF_TRIGGER_RISING, "bsi-err", chip);
if (rc < 0) {
dev_err(dev, "%s: request for bsi-err irq %d failed, rc=%d\n",
__func__, chip->irq[QPNP_BSI_IRQ_ERR], rc);
return rc;
}
rc = irq_set_irq_wake(chip->irq[QPNP_BSI_IRQ_ERR], 1);
if (rc < 0) {
dev_err(dev, "%s: unable to set bsi-err irq %d as wakeable, rc=%d\n",
__func__, chip->irq[QPNP_BSI_IRQ_ERR], rc);
return rc;
}
rc = devm_request_irq(dev, chip->irq[QPNP_BSI_IRQ_RX],
qpnp_bsi_isr, IRQF_TRIGGER_RISING, "bsi-rx", chip);
if (rc < 0) {
dev_err(dev, "%s: request for bsi-rx irq %d failed, rc=%d\n",
__func__, chip->irq[QPNP_BSI_IRQ_RX], rc);
goto set_unwakeable_irq_err;
}
rc = irq_set_irq_wake(chip->irq[QPNP_BSI_IRQ_RX], 1);
if (rc < 0) {
dev_err(dev, "%s: unable to set bsi-rx irq %d as wakeable, rc=%d\n",
__func__, chip->irq[QPNP_BSI_IRQ_RX], rc);
goto set_unwakeable_irq_err;
}
rc = devm_request_irq(dev, chip->irq[QPNP_BSI_IRQ_TX],
qpnp_bsi_isr, IRQF_TRIGGER_RISING, "bsi-tx", chip);
if (rc < 0) {
dev_err(dev, "%s: request for bsi-tx irq %d failed, rc=%d\n",
__func__, chip->irq[QPNP_BSI_IRQ_TX], rc);
goto set_unwakeable_irq_rx;
}
rc = irq_set_irq_wake(chip->irq[QPNP_BSI_IRQ_TX], 1);
if (rc < 0) {
dev_err(dev, "%s: unable to set bsi-tx irq %d as wakeable, rc=%d\n",
__func__, chip->irq[QPNP_BSI_IRQ_TX], rc);
goto set_unwakeable_irq_rx;
}
rc = devm_request_threaded_irq(dev, chip->batt_present_irq, NULL,
qpnp_bsi_batt_present_isr,
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING | IRQF_SHARED
| IRQF_ONESHOT,
"bsi-batt-present", chip);
if (rc < 0) {
dev_err(dev, "%s: request for bsi-batt-present irq %d failed, rc=%d\n",
__func__, chip->batt_present_irq, rc);
goto set_unwakeable_irq_tx;
}
rc = irq_set_irq_wake(chip->batt_present_irq, 1);
if (rc < 0) {
dev_err(dev, "%s: unable to set bsi-batt-present irq %d as wakeable, rc=%d\n",
__func__, chip->batt_present_irq, rc);
goto set_unwakeable_irq_tx;
}
return rc;
set_unwakeable_irq_tx:
irq_set_irq_wake(chip->irq[QPNP_BSI_IRQ_TX], 0);
set_unwakeable_irq_rx:
irq_set_irq_wake(chip->irq[QPNP_BSI_IRQ_RX], 0);
set_unwakeable_irq_err:
irq_set_irq_wake(chip->irq[QPNP_BSI_IRQ_ERR], 0);
return rc;
}
static void qpnp_bsi_cleanup_irqs(struct qpnp_bsi_chip *chip)
{
irq_set_irq_wake(chip->irq[QPNP_BSI_IRQ_ERR], 0);
irq_set_irq_wake(chip->irq[QPNP_BSI_IRQ_RX], 0);
irq_set_irq_wake(chip->irq[QPNP_BSI_IRQ_TX], 0);
irq_set_irq_wake(chip->batt_present_irq, 0);
}
static int __devinit qpnp_bsi_probe(struct spmi_device *spmi)
{
struct device *dev = &spmi->dev;
struct qpnp_bsi_chip *chip;
int rc;
u8 type[2];
if (!spmi->dev.of_node) {
dev_err(dev, "%s: device node missing\n", __func__);
return -ENODEV;
}
chip = devm_kzalloc(dev, sizeof(struct qpnp_bsi_chip), GFP_KERNEL);
if (!chip) {
dev_err(dev, "%s: Can't allocate qpnp_bsi\n", __func__);
return -ENOMEM;
}
rc = qpnp_bsi_parse_dt(chip, spmi);
if (rc) {
dev_err(dev, "%s: device tree parsing failed, rc=%d\n",
__func__, rc);
return rc;
}
INIT_WORK(&chip->slave_irq_work, qpnp_bsi_slave_irq_work);
rc = qpnp_bsi_init_irqs(chip, dev);
if (rc) {
dev_err(dev, "%s: IRQ initialization failed, rc=%d\n",
__func__, rc);
return rc;
}
chip->spmi_dev = spmi;
chip->bdesc.ops = &qpnp_bsi_ops;
chip->state = BIF_BUS_STATE_MASTER_DISABLED;
chip->com_mode = QPNP_BSI_COM_MODE_IRQ;
rc = qpnp_bsi_read(chip, QPNP_BSI_REG_TYPE, type, 2);
if (rc) {
dev_err(dev, "%s: could not read type register, rc=%d\n",
__func__, rc);
goto cleanup_irqs;
}
if (type[0] != QPNP_BSI_TYPE || type[1] != QPNP_BSI_SUBTYPE) {
dev_err(dev, "%s: BSI peripheral is not present; type=0x%02X, subtype=0x%02X\n",
__func__, type[0], type[1]);
rc = -ENODEV;
goto cleanup_irqs;
}
/* Ensure that ADC channel is available if it was specified. */
if (chip->batt_id_adc_channel < ADC_MAX_NUM) {
chip->vadc_dev = qpnp_get_vadc(dev, "bsi");
if (IS_ERR(chip->vadc_dev)) {
rc = PTR_ERR(chip->vadc_dev);
if (rc != -EPROBE_DEFER)
pr_err("missing vadc property, rc=%d\n", rc);
/* Probe retry, do not print an error message */
goto cleanup_irqs;
}
}
rc = qpnp_bsi_set_tau_bif(chip, chip->bdesc.bus_clock_min_ns);
if (rc) {
dev_err(dev, "%s: qpnp_bsi_set_tau_bif() failed, rc=%d\n",
__func__, rc);
goto cleanup_irqs;
}
chip->bdev = bif_ctrl_register(&chip->bdesc, dev, chip,
spmi->dev.of_node);
if (IS_ERR(chip->bdev)) {
rc = PTR_ERR(chip->bdev);
dev_err(dev, "%s: bif_ctrl_register failed, rc=%d\n",
__func__, rc);
goto cleanup_irqs;
}
dev_set_drvdata(dev, chip);
return rc;
cleanup_irqs:
qpnp_bsi_cleanup_irqs(chip);
return rc;
}
static int __devexit qpnp_bsi_remove(struct spmi_device *spmi)
{
struct qpnp_bsi_chip *chip = dev_get_drvdata(&spmi->dev);
dev_set_drvdata(&spmi->dev, NULL);
if (chip) {
bif_ctrl_unregister(chip->bdev);
qpnp_bsi_cleanup_irqs(chip);
}
return 0;
}
static struct of_device_id spmi_match_table[] = {
{ .compatible = QPNP_BSI_DRIVER_NAME, },
{}
};
static const struct spmi_device_id qpnp_bsi_id[] = {
{ QPNP_BSI_DRIVER_NAME, 0 },
{ }
};
MODULE_DEVICE_TABLE(spmi, qpnp_bsi_id);
static struct spmi_driver qpnp_bsi_driver = {
.driver = {
.name = QPNP_BSI_DRIVER_NAME,
.of_match_table = spmi_match_table,
.owner = THIS_MODULE,
},
.probe = qpnp_bsi_probe,
.remove = __devexit_p(qpnp_bsi_remove),
.id_table = qpnp_bsi_id,
};
static int __init qpnp_bsi_init(void)
{
return spmi_driver_register(&qpnp_bsi_driver);
}
static void __exit qpnp_bsi_exit(void)
{
spmi_driver_unregister(&qpnp_bsi_driver);
}
MODULE_DESCRIPTION("QPNP PMIC BSI driver");
MODULE_LICENSE("GPL v2");
arch_initcall(qpnp_bsi_init);
module_exit(qpnp_bsi_exit);
| gpl-2.0 |
jamison904/d2tmo_kernel | arch/arm/plat-mxc/avic.c | 2429 | 4672 | /*
* Copyright 2004-2007 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright 2008 Juergen Beisert, 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/module.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <mach/common.h>
#include <asm/mach/irq.h>
#include <mach/hardware.h>
#include "irq-common.h"
#define AVIC_INTCNTL 0x00 /* int control reg */
#define AVIC_NIMASK 0x04 /* int mask reg */
#define AVIC_INTENNUM 0x08 /* int enable number reg */
#define AVIC_INTDISNUM 0x0C /* int disable number reg */
#define AVIC_INTENABLEH 0x10 /* int enable reg high */
#define AVIC_INTENABLEL 0x14 /* int enable reg low */
#define AVIC_INTTYPEH 0x18 /* int type reg high */
#define AVIC_INTTYPEL 0x1C /* int type reg low */
#define AVIC_NIPRIORITY(x) (0x20 + 4 * (7 - (x))) /* int priority */
#define AVIC_NIVECSR 0x40 /* norm int vector/status */
#define AVIC_FIVECSR 0x44 /* fast int vector/status */
#define AVIC_INTSRCH 0x48 /* int source reg high */
#define AVIC_INTSRCL 0x4C /* int source reg low */
#define AVIC_INTFRCH 0x50 /* int force reg high */
#define AVIC_INTFRCL 0x54 /* int force reg low */
#define AVIC_NIPNDH 0x58 /* norm int pending high */
#define AVIC_NIPNDL 0x5C /* norm int pending low */
#define AVIC_FIPNDH 0x60 /* fast int pending high */
#define AVIC_FIPNDL 0x64 /* fast int pending low */
void __iomem *avic_base;
#ifdef CONFIG_MXC_IRQ_PRIOR
static int avic_irq_set_priority(unsigned char irq, unsigned char prio)
{
unsigned int temp;
unsigned int mask = 0x0F << irq % 8 * 4;
if (irq >= MXC_INTERNAL_IRQS)
return -EINVAL;;
temp = __raw_readl(avic_base + AVIC_NIPRIORITY(irq / 8));
temp &= ~mask;
temp |= prio & mask;
__raw_writel(temp, avic_base + AVIC_NIPRIORITY(irq / 8));
return 0;
}
#endif
#ifdef CONFIG_FIQ
static int avic_set_irq_fiq(unsigned int irq, unsigned int type)
{
unsigned int irqt;
if (irq >= MXC_INTERNAL_IRQS)
return -EINVAL;
if (irq < MXC_INTERNAL_IRQS / 2) {
irqt = __raw_readl(avic_base + AVIC_INTTYPEL) & ~(1 << irq);
__raw_writel(irqt | (!!type << irq), avic_base + AVIC_INTTYPEL);
} else {
irq -= MXC_INTERNAL_IRQS / 2;
irqt = __raw_readl(avic_base + AVIC_INTTYPEH) & ~(1 << irq);
__raw_writel(irqt | (!!type << irq), avic_base + AVIC_INTTYPEH);
}
return 0;
}
#endif /* CONFIG_FIQ */
/* Disable interrupt number "irq" in the AVIC */
static void mxc_mask_irq(struct irq_data *d)
{
__raw_writel(d->irq, avic_base + AVIC_INTDISNUM);
}
/* Enable interrupt number "irq" in the AVIC */
static void mxc_unmask_irq(struct irq_data *d)
{
__raw_writel(d->irq, avic_base + AVIC_INTENNUM);
}
static struct mxc_irq_chip mxc_avic_chip = {
.base = {
.irq_ack = mxc_mask_irq,
.irq_mask = mxc_mask_irq,
.irq_unmask = mxc_unmask_irq,
},
#ifdef CONFIG_MXC_IRQ_PRIOR
.set_priority = avic_irq_set_priority,
#endif
#ifdef CONFIG_FIQ
.set_irq_fiq = avic_set_irq_fiq,
#endif
};
/*
* This function initializes the AVIC hardware and disables all the
* interrupts. It registers the interrupt enable and disable functions
* to the kernel for each interrupt source.
*/
void __init mxc_init_irq(void __iomem *irqbase)
{
int i;
avic_base = irqbase;
/* put the AVIC into the reset value with
* all interrupts disabled
*/
__raw_writel(0, avic_base + AVIC_INTCNTL);
__raw_writel(0x1f, avic_base + AVIC_NIMASK);
/* disable all interrupts */
__raw_writel(0, avic_base + AVIC_INTENABLEH);
__raw_writel(0, avic_base + AVIC_INTENABLEL);
/* all IRQ no FIQ */
__raw_writel(0, avic_base + AVIC_INTTYPEH);
__raw_writel(0, avic_base + AVIC_INTTYPEL);
for (i = 0; i < MXC_INTERNAL_IRQS; i++) {
irq_set_chip_and_handler(i, &mxc_avic_chip.base,
handle_level_irq);
set_irq_flags(i, IRQF_VALID);
}
/* Set default priority value (0) for all IRQ's */
for (i = 0; i < 8; i++)
__raw_writel(0, avic_base + AVIC_NIPRIORITY(i));
#ifdef CONFIG_FIQ
/* Initialize FIQ */
init_FIQ();
#endif
printk(KERN_INFO "MXC IRQ initialized\n");
}
| gpl-2.0 |
norux/linux | drivers/net/wireless/ath/ath5k/dma.c | 2685 | 24745 | /*
* Copyright (c) 2004-2008 Reyk Floeter <reyk@openbsd.org>
* Copyright (c) 2006-2008 Nick Kossifidis <mickflemm@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/*************************************\
* DMA and interrupt masking functions *
\*************************************/
/**
* DOC: DMA and interrupt masking functions
*
* Here we setup descriptor pointers (rxdp/txdp) start/stop dma engine and
* handle queue setup for 5210 chipset (rest are handled on qcu.c).
* Also we setup interrupt mask register (IMR) and read the various interrupt
* status registers (ISR).
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include "ath5k.h"
#include "reg.h"
#include "debug.h"
/*********\
* Receive *
\*********/
/**
* ath5k_hw_start_rx_dma() - Start DMA receive
* @ah: The &struct ath5k_hw
*/
void
ath5k_hw_start_rx_dma(struct ath5k_hw *ah)
{
ath5k_hw_reg_write(ah, AR5K_CR_RXE, AR5K_CR);
ath5k_hw_reg_read(ah, AR5K_CR);
}
/**
* ath5k_hw_stop_rx_dma() - Stop DMA receive
* @ah: The &struct ath5k_hw
*/
static int
ath5k_hw_stop_rx_dma(struct ath5k_hw *ah)
{
unsigned int i;
ath5k_hw_reg_write(ah, AR5K_CR_RXD, AR5K_CR);
/*
* It may take some time to disable the DMA receive unit
*/
for (i = 1000; i > 0 &&
(ath5k_hw_reg_read(ah, AR5K_CR) & AR5K_CR_RXE) != 0;
i--)
udelay(100);
if (!i)
ATH5K_DBG(ah, ATH5K_DEBUG_DMA,
"failed to stop RX DMA !\n");
return i ? 0 : -EBUSY;
}
/**
* ath5k_hw_get_rxdp() - Get RX Descriptor's address
* @ah: The &struct ath5k_hw
*/
u32
ath5k_hw_get_rxdp(struct ath5k_hw *ah)
{
return ath5k_hw_reg_read(ah, AR5K_RXDP);
}
/**
* ath5k_hw_set_rxdp() - Set RX Descriptor's address
* @ah: The &struct ath5k_hw
* @phys_addr: RX descriptor address
*
* Returns -EIO if rx is active
*/
int
ath5k_hw_set_rxdp(struct ath5k_hw *ah, u32 phys_addr)
{
if (ath5k_hw_reg_read(ah, AR5K_CR) & AR5K_CR_RXE) {
ATH5K_DBG(ah, ATH5K_DEBUG_DMA,
"tried to set RXDP while rx was active !\n");
return -EIO;
}
ath5k_hw_reg_write(ah, phys_addr, AR5K_RXDP);
return 0;
}
/**********\
* Transmit *
\**********/
/**
* ath5k_hw_start_tx_dma() - Start DMA transmit for a specific queue
* @ah: The &struct ath5k_hw
* @queue: The hw queue number
*
* Start DMA transmit for a specific queue and since 5210 doesn't have
* QCU/DCU, set up queue parameters for 5210 here based on queue type (one
* queue for normal data and one queue for beacons). For queue setup
* on newer chips check out qcu.c. Returns -EINVAL if queue number is out
* of range or if queue is already disabled.
*
* NOTE: Must be called after setting up tx control descriptor for that
* queue (see below).
*/
int
ath5k_hw_start_tx_dma(struct ath5k_hw *ah, unsigned int queue)
{
u32 tx_queue;
AR5K_ASSERT_ENTRY(queue, ah->ah_capabilities.cap_queues.q_tx_num);
/* Return if queue is declared inactive */
if (ah->ah_txq[queue].tqi_type == AR5K_TX_QUEUE_INACTIVE)
return -EINVAL;
if (ah->ah_version == AR5K_AR5210) {
tx_queue = ath5k_hw_reg_read(ah, AR5K_CR);
/*
* Set the queue by type on 5210
*/
switch (ah->ah_txq[queue].tqi_type) {
case AR5K_TX_QUEUE_DATA:
tx_queue |= AR5K_CR_TXE0 & ~AR5K_CR_TXD0;
break;
case AR5K_TX_QUEUE_BEACON:
tx_queue |= AR5K_CR_TXE1 & ~AR5K_CR_TXD1;
ath5k_hw_reg_write(ah, AR5K_BCR_TQ1V | AR5K_BCR_BDMAE,
AR5K_BSR);
break;
case AR5K_TX_QUEUE_CAB:
tx_queue |= AR5K_CR_TXE1 & ~AR5K_CR_TXD1;
ath5k_hw_reg_write(ah, AR5K_BCR_TQ1FV | AR5K_BCR_TQ1V |
AR5K_BCR_BDMAE, AR5K_BSR);
break;
default:
return -EINVAL;
}
/* Start queue */
ath5k_hw_reg_write(ah, tx_queue, AR5K_CR);
ath5k_hw_reg_read(ah, AR5K_CR);
} else {
/* Return if queue is disabled */
if (AR5K_REG_READ_Q(ah, AR5K_QCU_TXD, queue))
return -EIO;
/* Start queue */
AR5K_REG_WRITE_Q(ah, AR5K_QCU_TXE, queue);
}
return 0;
}
/**
* ath5k_hw_stop_tx_dma() - Stop DMA transmit on a specific queue
* @ah: The &struct ath5k_hw
* @queue: The hw queue number
*
* Stop DMA transmit on a specific hw queue and drain queue so we don't
* have any pending frames. Returns -EBUSY if we still have pending frames,
* -EINVAL if queue number is out of range or inactive.
*/
static int
ath5k_hw_stop_tx_dma(struct ath5k_hw *ah, unsigned int queue)
{
unsigned int i = 40;
u32 tx_queue, pending;
AR5K_ASSERT_ENTRY(queue, ah->ah_capabilities.cap_queues.q_tx_num);
/* Return if queue is declared inactive */
if (ah->ah_txq[queue].tqi_type == AR5K_TX_QUEUE_INACTIVE)
return -EINVAL;
if (ah->ah_version == AR5K_AR5210) {
tx_queue = ath5k_hw_reg_read(ah, AR5K_CR);
/*
* Set by queue type
*/
switch (ah->ah_txq[queue].tqi_type) {
case AR5K_TX_QUEUE_DATA:
tx_queue |= AR5K_CR_TXD0 & ~AR5K_CR_TXE0;
break;
case AR5K_TX_QUEUE_BEACON:
case AR5K_TX_QUEUE_CAB:
/* XXX Fix me... */
tx_queue |= AR5K_CR_TXD1 & ~AR5K_CR_TXD1;
ath5k_hw_reg_write(ah, 0, AR5K_BSR);
break;
default:
return -EINVAL;
}
/* Stop queue */
ath5k_hw_reg_write(ah, tx_queue, AR5K_CR);
ath5k_hw_reg_read(ah, AR5K_CR);
} else {
/*
* Enable DCU early termination to quickly
* flush any pending frames from QCU
*/
AR5K_REG_ENABLE_BITS(ah, AR5K_QUEUE_MISC(queue),
AR5K_QCU_MISC_DCU_EARLY);
/*
* Schedule TX disable and wait until queue is empty
*/
AR5K_REG_WRITE_Q(ah, AR5K_QCU_TXD, queue);
/* Wait for queue to stop */
for (i = 1000; i > 0 &&
(AR5K_REG_READ_Q(ah, AR5K_QCU_TXE, queue) != 0);
i--)
udelay(100);
if (AR5K_REG_READ_Q(ah, AR5K_QCU_TXE, queue))
ATH5K_DBG(ah, ATH5K_DEBUG_DMA,
"queue %i didn't stop !\n", queue);
/* Check for pending frames */
i = 1000;
do {
pending = ath5k_hw_reg_read(ah,
AR5K_QUEUE_STATUS(queue)) &
AR5K_QCU_STS_FRMPENDCNT;
udelay(100);
} while (--i && pending);
/* For 2413+ order PCU to drop packets using
* QUIET mechanism */
if (ah->ah_mac_version >= (AR5K_SREV_AR2414 >> 4) &&
pending) {
/* Set periodicity and duration */
ath5k_hw_reg_write(ah,
AR5K_REG_SM(100, AR5K_QUIET_CTL2_QT_PER)|
AR5K_REG_SM(10, AR5K_QUIET_CTL2_QT_DUR),
AR5K_QUIET_CTL2);
/* Enable quiet period for current TSF */
ath5k_hw_reg_write(ah,
AR5K_QUIET_CTL1_QT_EN |
AR5K_REG_SM(ath5k_hw_reg_read(ah,
AR5K_TSF_L32_5211) >> 10,
AR5K_QUIET_CTL1_NEXT_QT_TSF),
AR5K_QUIET_CTL1);
/* Force channel idle high */
AR5K_REG_ENABLE_BITS(ah, AR5K_DIAG_SW_5211,
AR5K_DIAG_SW_CHANNEL_IDLE_HIGH);
/* Wait a while and disable mechanism */
udelay(400);
AR5K_REG_DISABLE_BITS(ah, AR5K_QUIET_CTL1,
AR5K_QUIET_CTL1_QT_EN);
/* Re-check for pending frames */
i = 100;
do {
pending = ath5k_hw_reg_read(ah,
AR5K_QUEUE_STATUS(queue)) &
AR5K_QCU_STS_FRMPENDCNT;
udelay(100);
} while (--i && pending);
AR5K_REG_DISABLE_BITS(ah, AR5K_DIAG_SW_5211,
AR5K_DIAG_SW_CHANNEL_IDLE_HIGH);
if (pending)
ATH5K_DBG(ah, ATH5K_DEBUG_DMA,
"quiet mechanism didn't work q:%i !\n",
queue);
}
/*
* Disable DCU early termination
*/
AR5K_REG_DISABLE_BITS(ah, AR5K_QUEUE_MISC(queue),
AR5K_QCU_MISC_DCU_EARLY);
/* Clear register */
ath5k_hw_reg_write(ah, 0, AR5K_QCU_TXD);
if (pending) {
ATH5K_DBG(ah, ATH5K_DEBUG_DMA,
"tx dma didn't stop (q:%i, frm:%i) !\n",
queue, pending);
return -EBUSY;
}
}
/* TODO: Check for success on 5210 else return error */
return 0;
}
/**
* ath5k_hw_stop_beacon_queue() - Stop beacon queue
* @ah: The &struct ath5k_hw
* @queue: The queue number
*
* Returns -EIO if queue didn't stop
*/
int
ath5k_hw_stop_beacon_queue(struct ath5k_hw *ah, unsigned int queue)
{
int ret;
ret = ath5k_hw_stop_tx_dma(ah, queue);
if (ret) {
ATH5K_DBG(ah, ATH5K_DEBUG_DMA,
"beacon queue didn't stop !\n");
return -EIO;
}
return 0;
}
/**
* ath5k_hw_get_txdp() - Get TX Descriptor's address for a specific queue
* @ah: The &struct ath5k_hw
* @queue: The hw queue number
*
* Get TX descriptor's address for a specific queue. For 5210 we ignore
* the queue number and use tx queue type since we only have 2 queues.
* We use TXDP0 for normal data queue and TXDP1 for beacon queue.
* For newer chips with QCU/DCU we just read the corresponding TXDP register.
*
* XXX: Is TXDP read and clear ?
*/
u32
ath5k_hw_get_txdp(struct ath5k_hw *ah, unsigned int queue)
{
u16 tx_reg;
AR5K_ASSERT_ENTRY(queue, ah->ah_capabilities.cap_queues.q_tx_num);
/*
* Get the transmit queue descriptor pointer from the selected queue
*/
/*5210 doesn't have QCU*/
if (ah->ah_version == AR5K_AR5210) {
switch (ah->ah_txq[queue].tqi_type) {
case AR5K_TX_QUEUE_DATA:
tx_reg = AR5K_NOQCU_TXDP0;
break;
case AR5K_TX_QUEUE_BEACON:
case AR5K_TX_QUEUE_CAB:
tx_reg = AR5K_NOQCU_TXDP1;
break;
default:
return 0xffffffff;
}
} else {
tx_reg = AR5K_QUEUE_TXDP(queue);
}
return ath5k_hw_reg_read(ah, tx_reg);
}
/**
* ath5k_hw_set_txdp() - Set TX Descriptor's address for a specific queue
* @ah: The &struct ath5k_hw
* @queue: The hw queue number
* @phys_addr: The physical address
*
* Set TX descriptor's address for a specific queue. For 5210 we ignore
* the queue number and we use tx queue type since we only have 2 queues
* so as above we use TXDP0 for normal data queue and TXDP1 for beacon queue.
* For newer chips with QCU/DCU we just set the corresponding TXDP register.
* Returns -EINVAL if queue type is invalid for 5210 and -EIO if queue is still
* active.
*/
int
ath5k_hw_set_txdp(struct ath5k_hw *ah, unsigned int queue, u32 phys_addr)
{
u16 tx_reg;
AR5K_ASSERT_ENTRY(queue, ah->ah_capabilities.cap_queues.q_tx_num);
/*
* Set the transmit queue descriptor pointer register by type
* on 5210
*/
if (ah->ah_version == AR5K_AR5210) {
switch (ah->ah_txq[queue].tqi_type) {
case AR5K_TX_QUEUE_DATA:
tx_reg = AR5K_NOQCU_TXDP0;
break;
case AR5K_TX_QUEUE_BEACON:
case AR5K_TX_QUEUE_CAB:
tx_reg = AR5K_NOQCU_TXDP1;
break;
default:
return -EINVAL;
}
} else {
/*
* Set the transmit queue descriptor pointer for
* the selected queue on QCU for 5211+
* (this won't work if the queue is still active)
*/
if (AR5K_REG_READ_Q(ah, AR5K_QCU_TXE, queue))
return -EIO;
tx_reg = AR5K_QUEUE_TXDP(queue);
}
/* Set descriptor pointer */
ath5k_hw_reg_write(ah, phys_addr, tx_reg);
return 0;
}
/**
* ath5k_hw_update_tx_triglevel() - Update tx trigger level
* @ah: The &struct ath5k_hw
* @increase: Flag to force increase of trigger level
*
* This function increases/decreases the tx trigger level for the tx fifo
* buffer (aka FIFO threshold) that is used to indicate when PCU flushes
* the buffer and transmits its data. Lowering this results sending small
* frames more quickly but can lead to tx underruns, raising it a lot can
* result other problems. Right now we start with the lowest possible
* (64Bytes) and if we get tx underrun we increase it using the increase
* flag. Returns -EIO if we have reached maximum/minimum.
*
* XXX: Link this with tx DMA size ?
* XXX2: Use it to save interrupts ?
*/
int
ath5k_hw_update_tx_triglevel(struct ath5k_hw *ah, bool increase)
{
u32 trigger_level, imr;
int ret = -EIO;
/*
* Disable interrupts by setting the mask
*/
imr = ath5k_hw_set_imr(ah, ah->ah_imr & ~AR5K_INT_GLOBAL);
trigger_level = AR5K_REG_MS(ath5k_hw_reg_read(ah, AR5K_TXCFG),
AR5K_TXCFG_TXFULL);
if (!increase) {
if (--trigger_level < AR5K_TUNE_MIN_TX_FIFO_THRES)
goto done;
} else
trigger_level +=
((AR5K_TUNE_MAX_TX_FIFO_THRES - trigger_level) / 2);
/*
* Update trigger level on success
*/
if (ah->ah_version == AR5K_AR5210)
ath5k_hw_reg_write(ah, trigger_level, AR5K_TRIG_LVL);
else
AR5K_REG_WRITE_BITS(ah, AR5K_TXCFG,
AR5K_TXCFG_TXFULL, trigger_level);
ret = 0;
done:
/*
* Restore interrupt mask
*/
ath5k_hw_set_imr(ah, imr);
return ret;
}
/*******************\
* Interrupt masking *
\*******************/
/**
* ath5k_hw_is_intr_pending() - Check if we have pending interrupts
* @ah: The &struct ath5k_hw
*
* Check if we have pending interrupts to process. Returns 1 if we
* have pending interrupts and 0 if we haven't.
*/
bool
ath5k_hw_is_intr_pending(struct ath5k_hw *ah)
{
return ath5k_hw_reg_read(ah, AR5K_INTPEND) == 1 ? 1 : 0;
}
/**
* ath5k_hw_get_isr() - Get interrupt status
* @ah: The @struct ath5k_hw
* @interrupt_mask: Driver's interrupt mask used to filter out
* interrupts in sw.
*
* This function is used inside our interrupt handler to determine the reason
* for the interrupt by reading Primary Interrupt Status Register. Returns an
* abstract interrupt status mask which is mostly ISR with some uncommon bits
* being mapped on some standard non hw-specific positions
* (check out &ath5k_int).
*
* NOTE: We do write-to-clear, so the active PISR/SISR bits at the time this
* function gets called are cleared on return.
*/
int
ath5k_hw_get_isr(struct ath5k_hw *ah, enum ath5k_int *interrupt_mask)
{
u32 data = 0;
/*
* Read interrupt status from Primary Interrupt
* Register.
*
* Note: PISR/SISR Not available on 5210
*/
if (ah->ah_version == AR5K_AR5210) {
u32 isr = 0;
isr = ath5k_hw_reg_read(ah, AR5K_ISR);
if (unlikely(isr == AR5K_INT_NOCARD)) {
*interrupt_mask = isr;
return -ENODEV;
}
/*
* Filter out the non-common bits from the interrupt
* status.
*/
*interrupt_mask = (isr & AR5K_INT_COMMON) & ah->ah_imr;
/* Hanlde INT_FATAL */
if (unlikely(isr & (AR5K_ISR_SSERR | AR5K_ISR_MCABT
| AR5K_ISR_DPERR)))
*interrupt_mask |= AR5K_INT_FATAL;
/*
* XXX: BMISS interrupts may occur after association.
* I found this on 5210 code but it needs testing. If this is
* true we should disable them before assoc and re-enable them
* after a successful assoc + some jiffies.
interrupt_mask &= ~AR5K_INT_BMISS;
*/
data = isr;
} else {
u32 pisr = 0;
u32 pisr_clear = 0;
u32 sisr0 = 0;
u32 sisr1 = 0;
u32 sisr2 = 0;
u32 sisr3 = 0;
u32 sisr4 = 0;
/* Read PISR and SISRs... */
pisr = ath5k_hw_reg_read(ah, AR5K_PISR);
if (unlikely(pisr == AR5K_INT_NOCARD)) {
*interrupt_mask = pisr;
return -ENODEV;
}
sisr0 = ath5k_hw_reg_read(ah, AR5K_SISR0);
sisr1 = ath5k_hw_reg_read(ah, AR5K_SISR1);
sisr2 = ath5k_hw_reg_read(ah, AR5K_SISR2);
sisr3 = ath5k_hw_reg_read(ah, AR5K_SISR3);
sisr4 = ath5k_hw_reg_read(ah, AR5K_SISR4);
/*
* PISR holds the logical OR of interrupt bits
* from SISR registers:
*
* TXOK and TXDESC -> Logical OR of TXOK and TXDESC
* per-queue bits on SISR0
*
* TXERR and TXEOL -> Logical OR of TXERR and TXEOL
* per-queue bits on SISR1
*
* TXURN -> Logical OR of TXURN per-queue bits on SISR2
*
* HIUERR -> Logical OR of MCABT, SSERR and DPER bits on SISR2
*
* BCNMISC -> Logical OR of TIM, CAB_END, DTIM_SYNC
* BCN_TIMEOUT, CAB_TIMEOUT and DTIM
* (and TSFOOR ?) bits on SISR2
*
* QCBRORN and QCBRURN -> Logical OR of QCBRORN and
* QCBRURN per-queue bits on SISR3
* QTRIG -> Logical OR of QTRIG per-queue bits on SISR4
*
* If we clean these bits on PISR we 'll also clear all
* related bits from SISRs, e.g. if we write the TXOK bit on
* PISR we 'll clean all TXOK bits from SISR0 so if a new TXOK
* interrupt got fired for another queue while we were reading
* the interrupt registers and we write back the TXOK bit on
* PISR we 'll lose it. So make sure that we don't write back
* on PISR any bits that come from SISRs. Clearing them from
* SISRs will also clear PISR so no need to worry here.
*/
/* XXX: There seems to be an issue on some cards
* with tx interrupt flags not being updated
* on PISR despite that all Tx interrupt bits
* are cleared on SISRs. Since we handle all
* Tx queues all together it shouldn't be an
* issue if we clear Tx interrupt flags also
* on PISR to avoid that.
*/
pisr_clear = (pisr & ~AR5K_ISR_BITS_FROM_SISRS) |
(pisr & AR5K_INT_TX_ALL);
/*
* Write to clear them...
* Note: This means that each bit we write back
* to the registers will get cleared, leaving the
* rest unaffected. So this won't affect new interrupts
* we didn't catch while reading/processing, we 'll get
* them next time get_isr gets called.
*/
ath5k_hw_reg_write(ah, sisr0, AR5K_SISR0);
ath5k_hw_reg_write(ah, sisr1, AR5K_SISR1);
ath5k_hw_reg_write(ah, sisr2, AR5K_SISR2);
ath5k_hw_reg_write(ah, sisr3, AR5K_SISR3);
ath5k_hw_reg_write(ah, sisr4, AR5K_SISR4);
ath5k_hw_reg_write(ah, pisr_clear, AR5K_PISR);
/* Flush previous write */
ath5k_hw_reg_read(ah, AR5K_PISR);
/*
* Filter out the non-common bits from the interrupt
* status.
*/
*interrupt_mask = (pisr & AR5K_INT_COMMON) & ah->ah_imr;
/* We treat TXOK,TXDESC, TXERR and TXEOL
* the same way (schedule the tx tasklet)
* so we track them all together per queue */
if (pisr & AR5K_ISR_TXOK)
ah->ah_txq_isr_txok_all |= AR5K_REG_MS(sisr0,
AR5K_SISR0_QCU_TXOK);
if (pisr & AR5K_ISR_TXDESC)
ah->ah_txq_isr_txok_all |= AR5K_REG_MS(sisr0,
AR5K_SISR0_QCU_TXDESC);
if (pisr & AR5K_ISR_TXERR)
ah->ah_txq_isr_txok_all |= AR5K_REG_MS(sisr1,
AR5K_SISR1_QCU_TXERR);
if (pisr & AR5K_ISR_TXEOL)
ah->ah_txq_isr_txok_all |= AR5K_REG_MS(sisr1,
AR5K_SISR1_QCU_TXEOL);
/* Currently this is not much useful since we treat
* all queues the same way if we get a TXURN (update
* tx trigger level) but we might need it later on*/
if (pisr & AR5K_ISR_TXURN)
ah->ah_txq_isr_txurn |= AR5K_REG_MS(sisr2,
AR5K_SISR2_QCU_TXURN);
/* Misc Beacon related interrupts */
/* For AR5211 */
if (pisr & AR5K_ISR_TIM)
*interrupt_mask |= AR5K_INT_TIM;
/* For AR5212+ */
if (pisr & AR5K_ISR_BCNMISC) {
if (sisr2 & AR5K_SISR2_TIM)
*interrupt_mask |= AR5K_INT_TIM;
if (sisr2 & AR5K_SISR2_DTIM)
*interrupt_mask |= AR5K_INT_DTIM;
if (sisr2 & AR5K_SISR2_DTIM_SYNC)
*interrupt_mask |= AR5K_INT_DTIM_SYNC;
if (sisr2 & AR5K_SISR2_BCN_TIMEOUT)
*interrupt_mask |= AR5K_INT_BCN_TIMEOUT;
if (sisr2 & AR5K_SISR2_CAB_TIMEOUT)
*interrupt_mask |= AR5K_INT_CAB_TIMEOUT;
}
/* Below interrupts are unlikely to happen */
/* HIU = Host Interface Unit (PCI etc)
* Can be one of MCABT, SSERR, DPERR from SISR2 */
if (unlikely(pisr & (AR5K_ISR_HIUERR)))
*interrupt_mask |= AR5K_INT_FATAL;
/*Beacon Not Ready*/
if (unlikely(pisr & (AR5K_ISR_BNR)))
*interrupt_mask |= AR5K_INT_BNR;
/* A queue got CBR overrun */
if (unlikely(pisr & (AR5K_ISR_QCBRORN))) {
*interrupt_mask |= AR5K_INT_QCBRORN;
ah->ah_txq_isr_qcborn |= AR5K_REG_MS(sisr3,
AR5K_SISR3_QCBRORN);
}
/* A queue got CBR underrun */
if (unlikely(pisr & (AR5K_ISR_QCBRURN))) {
*interrupt_mask |= AR5K_INT_QCBRURN;
ah->ah_txq_isr_qcburn |= AR5K_REG_MS(sisr3,
AR5K_SISR3_QCBRURN);
}
/* A queue got triggered */
if (unlikely(pisr & (AR5K_ISR_QTRIG))) {
*interrupt_mask |= AR5K_INT_QTRIG;
ah->ah_txq_isr_qtrig |= AR5K_REG_MS(sisr4,
AR5K_SISR4_QTRIG);
}
data = pisr;
}
/*
* In case we didn't handle anything,
* print the register value.
*/
if (unlikely(*interrupt_mask == 0 && net_ratelimit()))
ATH5K_PRINTF("ISR: 0x%08x IMR: 0x%08x\n", data, ah->ah_imr);
return 0;
}
/**
* ath5k_hw_set_imr() - Set interrupt mask
* @ah: The &struct ath5k_hw
* @new_mask: The new interrupt mask to be set
*
* Set the interrupt mask in hw to save interrupts. We do that by mapping
* ath5k_int bits to hw-specific bits to remove abstraction and writing
* Interrupt Mask Register.
*/
enum ath5k_int
ath5k_hw_set_imr(struct ath5k_hw *ah, enum ath5k_int new_mask)
{
enum ath5k_int old_mask, int_mask;
old_mask = ah->ah_imr;
/*
* Disable card interrupts to prevent any race conditions
* (they will be re-enabled afterwards if AR5K_INT GLOBAL
* is set again on the new mask).
*/
if (old_mask & AR5K_INT_GLOBAL) {
ath5k_hw_reg_write(ah, AR5K_IER_DISABLE, AR5K_IER);
ath5k_hw_reg_read(ah, AR5K_IER);
}
/*
* Add additional, chipset-dependent interrupt mask flags
* and write them to the IMR (interrupt mask register).
*/
int_mask = new_mask & AR5K_INT_COMMON;
if (ah->ah_version != AR5K_AR5210) {
/* Preserve per queue TXURN interrupt mask */
u32 simr2 = ath5k_hw_reg_read(ah, AR5K_SIMR2)
& AR5K_SIMR2_QCU_TXURN;
/* Fatal interrupt abstraction for 5211+ */
if (new_mask & AR5K_INT_FATAL) {
int_mask |= AR5K_IMR_HIUERR;
simr2 |= (AR5K_SIMR2_MCABT | AR5K_SIMR2_SSERR
| AR5K_SIMR2_DPERR);
}
/* Misc beacon related interrupts */
if (new_mask & AR5K_INT_TIM)
int_mask |= AR5K_IMR_TIM;
if (new_mask & AR5K_INT_TIM)
simr2 |= AR5K_SISR2_TIM;
if (new_mask & AR5K_INT_DTIM)
simr2 |= AR5K_SISR2_DTIM;
if (new_mask & AR5K_INT_DTIM_SYNC)
simr2 |= AR5K_SISR2_DTIM_SYNC;
if (new_mask & AR5K_INT_BCN_TIMEOUT)
simr2 |= AR5K_SISR2_BCN_TIMEOUT;
if (new_mask & AR5K_INT_CAB_TIMEOUT)
simr2 |= AR5K_SISR2_CAB_TIMEOUT;
/*Beacon Not Ready*/
if (new_mask & AR5K_INT_BNR)
int_mask |= AR5K_INT_BNR;
/* Note: Per queue interrupt masks
* are set via ath5k_hw_reset_tx_queue() (qcu.c) */
ath5k_hw_reg_write(ah, int_mask, AR5K_PIMR);
ath5k_hw_reg_write(ah, simr2, AR5K_SIMR2);
} else {
/* Fatal interrupt abstraction for 5210 */
if (new_mask & AR5K_INT_FATAL)
int_mask |= (AR5K_IMR_SSERR | AR5K_IMR_MCABT
| AR5K_IMR_HIUERR | AR5K_IMR_DPERR);
/* Only common interrupts left for 5210 (no SIMRs) */
ath5k_hw_reg_write(ah, int_mask, AR5K_IMR);
}
/* If RXNOFRM interrupt is masked disable it
* by setting AR5K_RXNOFRM to zero */
if (!(new_mask & AR5K_INT_RXNOFRM))
ath5k_hw_reg_write(ah, 0, AR5K_RXNOFRM);
/* Store new interrupt mask */
ah->ah_imr = new_mask;
/* ..re-enable interrupts if AR5K_INT_GLOBAL is set */
if (new_mask & AR5K_INT_GLOBAL) {
ath5k_hw_reg_write(ah, AR5K_IER_ENABLE, AR5K_IER);
ath5k_hw_reg_read(ah, AR5K_IER);
}
return old_mask;
}
/********************\
Init/Stop functions
\********************/
/**
* ath5k_hw_dma_init() - Initialize DMA unit
* @ah: The &struct ath5k_hw
*
* Set DMA size and pre-enable interrupts
* (driver handles tx/rx buffer setup and
* dma start/stop)
*
* XXX: Save/restore RXDP/TXDP registers ?
*/
void
ath5k_hw_dma_init(struct ath5k_hw *ah)
{
/*
* Set Rx/Tx DMA Configuration
*
* Set standard DMA size (128). Note that
* a DMA size of 512 causes rx overruns and tx errors
* on pci-e cards (tested on 5424 but since rx overruns
* also occur on 5416/5418 with madwifi we set 128
* for all PCI-E cards to be safe).
*
* XXX: need to check 5210 for this
* TODO: Check out tx trigger level, it's always 64 on dumps but I
* guess we can tweak it and see how it goes ;-)
*/
if (ah->ah_version != AR5K_AR5210) {
AR5K_REG_WRITE_BITS(ah, AR5K_TXCFG,
AR5K_TXCFG_SDMAMR, AR5K_DMASIZE_128B);
AR5K_REG_WRITE_BITS(ah, AR5K_RXCFG,
AR5K_RXCFG_SDMAMW, AR5K_DMASIZE_128B);
}
/* Pre-enable interrupts on 5211/5212*/
if (ah->ah_version != AR5K_AR5210)
ath5k_hw_set_imr(ah, ah->ah_imr);
}
/**
* ath5k_hw_dma_stop() - stop DMA unit
* @ah: The &struct ath5k_hw
*
* Stop tx/rx DMA and interrupts. Returns
* -EBUSY if tx or rx dma failed to stop.
*
* XXX: Sometimes DMA unit hangs and we have
* stuck frames on tx queues, only a reset
* can fix that.
*/
int
ath5k_hw_dma_stop(struct ath5k_hw *ah)
{
int i, qmax, err;
err = 0;
/* Disable interrupts */
ath5k_hw_set_imr(ah, 0);
/* Stop rx dma */
err = ath5k_hw_stop_rx_dma(ah);
if (err)
return err;
/* Clear any pending interrupts
* and disable tx dma */
if (ah->ah_version != AR5K_AR5210) {
ath5k_hw_reg_write(ah, 0xffffffff, AR5K_PISR);
qmax = AR5K_NUM_TX_QUEUES;
} else {
/* PISR/SISR Not available on 5210 */
ath5k_hw_reg_read(ah, AR5K_ISR);
qmax = AR5K_NUM_TX_QUEUES_NOQCU;
}
for (i = 0; i < qmax; i++) {
err = ath5k_hw_stop_tx_dma(ah, i);
/* -EINVAL -> queue inactive */
if (err && err != -EINVAL)
return err;
}
return 0;
}
| gpl-2.0 |
shuiqingliu/android_kernel_lenovo_stuttgart | drivers/media/rc/keymaps/rc-msi-tvanywhere.c | 2941 | 1784 | /* msi-tvanywhere.h - Keytable for msi_tvanywhere Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
/* MSI TV@nywhere MASTER remote */
static struct rc_map_table msi_tvanywhere[] = {
/* Keys 0 to 9 */
{ 0x00, KEY_0 },
{ 0x01, KEY_1 },
{ 0x02, KEY_2 },
{ 0x03, KEY_3 },
{ 0x04, KEY_4 },
{ 0x05, KEY_5 },
{ 0x06, KEY_6 },
{ 0x07, KEY_7 },
{ 0x08, KEY_8 },
{ 0x09, KEY_9 },
{ 0x0c, KEY_MUTE },
{ 0x0f, KEY_SCREEN }, /* Full Screen */
{ 0x10, KEY_FN }, /* Function */
{ 0x11, KEY_TIME }, /* Time shift */
{ 0x12, KEY_POWER },
{ 0x13, KEY_MEDIA }, /* MTS */
{ 0x14, KEY_SLOW },
{ 0x16, KEY_REWIND }, /* backward << */
{ 0x17, KEY_ENTER }, /* Return */
{ 0x18, KEY_FASTFORWARD }, /* forward >> */
{ 0x1a, KEY_CHANNELUP },
{ 0x1b, KEY_VOLUMEUP },
{ 0x1e, KEY_CHANNELDOWN },
{ 0x1f, KEY_VOLUMEDOWN },
};
static struct rc_map_list msi_tvanywhere_map = {
.map = {
.scan = msi_tvanywhere,
.size = ARRAY_SIZE(msi_tvanywhere),
.rc_type = RC_TYPE_UNKNOWN, /* Legacy IR type */
.name = RC_MAP_MSI_TVANYWHERE,
}
};
static int __init init_rc_map_msi_tvanywhere(void)
{
return rc_map_register(&msi_tvanywhere_map);
}
static void __exit exit_rc_map_msi_tvanywhere(void)
{
rc_map_unregister(&msi_tvanywhere_map);
}
module_init(init_rc_map_msi_tvanywhere)
module_exit(exit_rc_map_msi_tvanywhere)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
dkhoi1997/android_kernel_samsung_aries | drivers/power/z2_battery.c | 2941 | 8196 | /*
* Battery measurement code for Zipit Z2
*
* Copyright (C) 2009 Peter Edwards <sweetlilmre@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/module.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/power_supply.h>
#include <linux/slab.h>
#include <linux/z2_battery.h>
#define Z2_DEFAULT_NAME "Z2"
struct z2_charger {
struct z2_battery_info *info;
int bat_status;
struct i2c_client *client;
struct power_supply batt_ps;
struct mutex work_lock;
struct work_struct bat_work;
};
static unsigned long z2_read_bat(struct z2_charger *charger)
{
int data;
data = i2c_smbus_read_byte_data(charger->client,
charger->info->batt_I2C_reg);
if (data < 0)
return 0;
return data * charger->info->batt_mult / charger->info->batt_div;
}
static int z2_batt_get_property(struct power_supply *batt_ps,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct z2_charger *charger = container_of(batt_ps, struct z2_charger,
batt_ps);
struct z2_battery_info *info = charger->info;
switch (psp) {
case POWER_SUPPLY_PROP_STATUS:
val->intval = charger->bat_status;
break;
case POWER_SUPPLY_PROP_TECHNOLOGY:
val->intval = info->batt_tech;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
if (info->batt_I2C_reg >= 0)
val->intval = z2_read_bat(charger);
else
return -EINVAL;
break;
case POWER_SUPPLY_PROP_VOLTAGE_MAX:
if (info->max_voltage >= 0)
val->intval = info->max_voltage;
else
return -EINVAL;
break;
case POWER_SUPPLY_PROP_VOLTAGE_MIN:
if (info->min_voltage >= 0)
val->intval = info->min_voltage;
else
return -EINVAL;
break;
case POWER_SUPPLY_PROP_PRESENT:
val->intval = 1;
break;
default:
return -EINVAL;
}
return 0;
}
static void z2_batt_ext_power_changed(struct power_supply *batt_ps)
{
struct z2_charger *charger = container_of(batt_ps, struct z2_charger,
batt_ps);
schedule_work(&charger->bat_work);
}
static void z2_batt_update(struct z2_charger *charger)
{
int old_status = charger->bat_status;
struct z2_battery_info *info;
info = charger->info;
mutex_lock(&charger->work_lock);
charger->bat_status = (info->charge_gpio >= 0) ?
(gpio_get_value(info->charge_gpio) ?
POWER_SUPPLY_STATUS_CHARGING :
POWER_SUPPLY_STATUS_DISCHARGING) :
POWER_SUPPLY_STATUS_UNKNOWN;
if (old_status != charger->bat_status) {
pr_debug("%s: %i -> %i\n", charger->batt_ps.name, old_status,
charger->bat_status);
power_supply_changed(&charger->batt_ps);
}
mutex_unlock(&charger->work_lock);
}
static void z2_batt_work(struct work_struct *work)
{
struct z2_charger *charger;
charger = container_of(work, struct z2_charger, bat_work);
z2_batt_update(charger);
}
static irqreturn_t z2_charge_switch_irq(int irq, void *devid)
{
struct z2_charger *charger = devid;
schedule_work(&charger->bat_work);
return IRQ_HANDLED;
}
static int z2_batt_ps_init(struct z2_charger *charger, int props)
{
int i = 0;
enum power_supply_property *prop;
struct z2_battery_info *info = charger->info;
if (info->charge_gpio >= 0)
props++; /* POWER_SUPPLY_PROP_STATUS */
if (info->batt_tech >= 0)
props++; /* POWER_SUPPLY_PROP_TECHNOLOGY */
if (info->batt_I2C_reg >= 0)
props++; /* POWER_SUPPLY_PROP_VOLTAGE_NOW */
if (info->max_voltage >= 0)
props++; /* POWER_SUPPLY_PROP_VOLTAGE_MAX */
if (info->min_voltage >= 0)
props++; /* POWER_SUPPLY_PROP_VOLTAGE_MIN */
prop = kzalloc(props * sizeof(*prop), GFP_KERNEL);
if (!prop)
return -ENOMEM;
prop[i++] = POWER_SUPPLY_PROP_PRESENT;
if (info->charge_gpio >= 0)
prop[i++] = POWER_SUPPLY_PROP_STATUS;
if (info->batt_tech >= 0)
prop[i++] = POWER_SUPPLY_PROP_TECHNOLOGY;
if (info->batt_I2C_reg >= 0)
prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_NOW;
if (info->max_voltage >= 0)
prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_MAX;
if (info->min_voltage >= 0)
prop[i++] = POWER_SUPPLY_PROP_VOLTAGE_MIN;
if (!info->batt_name) {
dev_info(&charger->client->dev,
"Please consider setting proper battery "
"name in platform definition file, falling "
"back to name \" Z2_DEFAULT_NAME \"\n");
charger->batt_ps.name = Z2_DEFAULT_NAME;
} else
charger->batt_ps.name = info->batt_name;
charger->batt_ps.properties = prop;
charger->batt_ps.num_properties = props;
charger->batt_ps.type = POWER_SUPPLY_TYPE_BATTERY;
charger->batt_ps.get_property = z2_batt_get_property;
charger->batt_ps.external_power_changed = z2_batt_ext_power_changed;
charger->batt_ps.use_for_apm = 1;
return 0;
}
static int __devinit z2_batt_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int ret = 0;
int props = 1; /* POWER_SUPPLY_PROP_PRESENT */
struct z2_charger *charger;
struct z2_battery_info *info = client->dev.platform_data;
if (info == NULL) {
dev_err(&client->dev,
"Please set platform device platform_data"
" to a valid z2_battery_info pointer!\n");
return -EINVAL;
}
charger = kzalloc(sizeof(*charger), GFP_KERNEL);
if (charger == NULL)
return -ENOMEM;
charger->bat_status = POWER_SUPPLY_STATUS_UNKNOWN;
charger->info = info;
charger->client = client;
i2c_set_clientdata(client, charger);
mutex_init(&charger->work_lock);
if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) {
ret = gpio_request(info->charge_gpio, "BATT CHRG");
if (ret)
goto err;
ret = gpio_direction_input(info->charge_gpio);
if (ret)
goto err2;
irq_set_irq_type(gpio_to_irq(info->charge_gpio),
IRQ_TYPE_EDGE_BOTH);
ret = request_irq(gpio_to_irq(info->charge_gpio),
z2_charge_switch_irq, IRQF_DISABLED,
"AC Detect", charger);
if (ret)
goto err3;
}
ret = z2_batt_ps_init(charger, props);
if (ret)
goto err3;
INIT_WORK(&charger->bat_work, z2_batt_work);
ret = power_supply_register(&client->dev, &charger->batt_ps);
if (ret)
goto err4;
schedule_work(&charger->bat_work);
return 0;
err4:
kfree(charger->batt_ps.properties);
err3:
if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio))
free_irq(gpio_to_irq(info->charge_gpio), charger);
err2:
if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio))
gpio_free(info->charge_gpio);
err:
kfree(charger);
return ret;
}
static int __devexit z2_batt_remove(struct i2c_client *client)
{
struct z2_charger *charger = i2c_get_clientdata(client);
struct z2_battery_info *info = charger->info;
cancel_work_sync(&charger->bat_work);
power_supply_unregister(&charger->batt_ps);
kfree(charger->batt_ps.properties);
if (info->charge_gpio >= 0 && gpio_is_valid(info->charge_gpio)) {
free_irq(gpio_to_irq(info->charge_gpio), charger);
gpio_free(info->charge_gpio);
}
kfree(charger);
return 0;
}
#ifdef CONFIG_PM
static int z2_batt_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct z2_charger *charger = i2c_get_clientdata(client);
flush_work_sync(&charger->bat_work);
return 0;
}
static int z2_batt_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct z2_charger *charger = i2c_get_clientdata(client);
schedule_work(&charger->bat_work);
return 0;
}
static const struct dev_pm_ops z2_battery_pm_ops = {
.suspend = z2_batt_suspend,
.resume = z2_batt_resume,
};
#define Z2_BATTERY_PM_OPS (&z2_battery_pm_ops)
#else
#define Z2_BATTERY_PM_OPS (NULL)
#endif
static const struct i2c_device_id z2_batt_id[] = {
{ "aer915", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, z2_batt_id);
static struct i2c_driver z2_batt_driver = {
.driver = {
.name = "z2-battery",
.owner = THIS_MODULE,
.pm = Z2_BATTERY_PM_OPS
},
.probe = z2_batt_probe,
.remove = z2_batt_remove,
.id_table = z2_batt_id,
};
static int __init z2_batt_init(void)
{
return i2c_add_driver(&z2_batt_driver);
}
static void __exit z2_batt_exit(void)
{
i2c_del_driver(&z2_batt_driver);
}
module_init(z2_batt_init);
module_exit(z2_batt_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Peter Edwards <sweetlilmre@gmail.com>");
MODULE_DESCRIPTION("Zipit Z2 battery driver");
| gpl-2.0 |
Ander-Alvarez/android_kernel_motorola_msm8916 | arch/sh/boards/mach-dreamcast/irq.c | 4733 | 4412 | /*
* arch/sh/boards/dreamcast/irq.c
*
* Holly IRQ support for the Sega Dreamcast.
*
* Copyright (c) 2001, 2002 M. R. Brown <mrbrown@0xd6.org>
*
* This file is part of the LinuxDC project (www.linuxdc.org)
* Released under the terms of the GNU GPL v2.0
*/
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/export.h>
#include <linux/err.h>
#include <mach/sysasic.h>
/*
* Dreamcast System ASIC Hardware Events -
*
* The Dreamcast's System ASIC (a.k.a. Holly) is responsible for receiving
* hardware events from system peripherals and triggering an SH7750 IRQ.
* Hardware events can trigger IRQs 13, 11, or 9 depending on which bits are
* set in the Event Mask Registers (EMRs). When a hardware event is
* triggered, its corresponding bit in the Event Status Registers (ESRs)
* is set, and that bit should be rewritten to the ESR to acknowledge that
* event.
*
* There are three 32-bit ESRs located at 0xa05f6900 - 0xa05f6908. Event
* types can be found in arch/sh/include/mach-dreamcast/mach/sysasic.h.
* There are three groups of EMRs that parallel the ESRs. Each EMR group
* corresponds to an IRQ, so 0xa05f6910 - 0xa05f6918 triggers IRQ 13,
* 0xa05f6920 - 0xa05f6928 triggers IRQ 11, and 0xa05f6930 - 0xa05f6938
* triggers IRQ 9.
*
* In the kernel, these events are mapped to virtual IRQs so that drivers can
* respond to them as they would a normal interrupt. In order to keep this
* mapping simple, the events are mapped as:
*
* 6900/6910 - Events 0-31, IRQ 13
* 6904/6924 - Events 32-63, IRQ 11
* 6908/6938 - Events 64-95, IRQ 9
*
*/
#define ESR_BASE 0x005f6900 /* Base event status register */
#define EMR_BASE 0x005f6910 /* Base event mask register */
/*
* Helps us determine the EMR group that this event belongs to: 0 = 0x6910,
* 1 = 0x6920, 2 = 0x6930; also determine the event offset.
*/
#define LEVEL(event) (((event) - HW_EVENT_IRQ_BASE) / 32)
/* Return the hardware event's bit position within the EMR/ESR */
#define EVENT_BIT(event) (((event) - HW_EVENT_IRQ_BASE) & 31)
/*
* For each of these *_irq routines, the IRQ passed in is the virtual IRQ
* (logically mapped to the corresponding bit for the hardware event).
*/
/* Disable the hardware event by masking its bit in its EMR */
static inline void disable_systemasic_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
__u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2);
__u32 mask;
mask = inl(emr);
mask &= ~(1 << EVENT_BIT(irq));
outl(mask, emr);
}
/* Enable the hardware event by setting its bit in its EMR */
static inline void enable_systemasic_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
__u32 emr = EMR_BASE + (LEVEL(irq) << 4) + (LEVEL(irq) << 2);
__u32 mask;
mask = inl(emr);
mask |= (1 << EVENT_BIT(irq));
outl(mask, emr);
}
/* Acknowledge a hardware event by writing its bit back to its ESR */
static void mask_ack_systemasic_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
__u32 esr = ESR_BASE + (LEVEL(irq) << 2);
disable_systemasic_irq(data);
outl((1 << EVENT_BIT(irq)), esr);
}
struct irq_chip systemasic_int = {
.name = "System ASIC",
.irq_mask = disable_systemasic_irq,
.irq_mask_ack = mask_ack_systemasic_irq,
.irq_unmask = enable_systemasic_irq,
};
/*
* Map the hardware event indicated by the processor IRQ to a virtual IRQ.
*/
int systemasic_irq_demux(int irq)
{
__u32 emr, esr, status, level;
__u32 j, bit;
switch (irq) {
case 13:
level = 0;
break;
case 11:
level = 1;
break;
case 9:
level = 2;
break;
default:
return irq;
}
emr = EMR_BASE + (level << 4) + (level << 2);
esr = ESR_BASE + (level << 2);
/* Mask the ESR to filter any spurious, unwanted interrupts */
status = inl(esr);
status &= inl(emr);
/* Now scan and find the first set bit as the event to map */
for (bit = 1, j = 0; j < 32; bit <<= 1, j++) {
if (status & bit) {
irq = HW_EVENT_IRQ_BASE + j + (level << 5);
return irq;
}
}
/* Not reached */
return irq;
}
void systemasic_irq_init(void)
{
int irq_base, i;
irq_base = irq_alloc_descs(HW_EVENT_IRQ_BASE, HW_EVENT_IRQ_BASE,
HW_EVENT_IRQ_MAX - HW_EVENT_IRQ_BASE, -1);
if (IS_ERR_VALUE(irq_base)) {
pr_err("%s: failed hooking irqs\n", __func__);
return;
}
for (i = HW_EVENT_IRQ_BASE; i < HW_EVENT_IRQ_MAX; i++)
irq_set_chip_and_handler(i, &systemasic_int, handle_level_irq);
}
| gpl-2.0 |
alsandeep/kernel-4.4 | arch/arm/mach-omap2/clockdomains2xxx_3xxx_data.c | 4733 | 2682 | /*
* OMAP2/3 clockdomain common data
*
* Copyright (C) 2008-2011 Texas Instruments, Inc.
* Copyright (C) 2008-2010 Nokia Corporation
*
* Paul Walmsley, Jouni Högander
*
* This file contains clockdomains and clockdomain wakeup/sleep
* dependencies for the OMAP2/3 chips. Some notes:
*
* A useful validation rule for struct clockdomain: Any clockdomain
* referenced by a wkdep_srcs or sleepdep_srcs array must have a
* dep_bit assigned. So wkdep_srcs/sleepdep_srcs are really just
* software-controllable dependencies. Non-software-controllable
* dependencies do exist, but they are not encoded below (yet).
*
* 24xx does not support programmable sleep dependencies (SLEEPDEP)
*
* The overly-specific dep_bit names are due to a bit name collision
* with CM_FCLKEN_{DSP,IVA2}. The DSP/IVA2 PM_WKDEP and CM_SLEEPDEP shift
* value are the same for all powerdomains: 2
*
* XXX should dep_bit be a mask, so we can test to see if it is 0 as a
* sanity check?
* XXX encode hardware fixed wakeup dependencies -- esp. for 3430 CORE
*/
/*
* To-Do List
* -> Port the Sleep/Wakeup dependencies for the domains
* from the Power domain framework
*/
#include <linux/kernel.h>
#include <linux/io.h>
#include "clockdomain.h"
#include "prm2xxx_3xxx.h"
#include "cm2xxx_3xxx.h"
#include "cm-regbits-24xx.h"
#include "cm-regbits-34xx.h"
#include "cm-regbits-44xx.h"
#include "prm-regbits-24xx.h"
#include "prm-regbits-34xx.h"
/*
* Clockdomain dependencies for wkdeps/sleepdeps
*
* XXX Hardware dependencies (e.g., dependencies that cannot be
* changed in software) are not included here yet, but should be.
*/
/* Wakeup dependency source arrays */
/* 2xxx-specific possible dependencies */
/* 2xxx PM_WKDEP_GFX: CORE, MPU, WKUP */
struct clkdm_dep gfx_24xx_wkdeps[] = {
{ .clkdm_name = "core_l3_clkdm" },
{ .clkdm_name = "core_l4_clkdm" },
{ .clkdm_name = "mpu_clkdm" },
{ .clkdm_name = "wkup_clkdm" },
{ NULL },
};
/* 2xxx PM_WKDEP_DSP: CORE, MPU, WKUP */
struct clkdm_dep dsp_24xx_wkdeps[] = {
{ .clkdm_name = "core_l3_clkdm" },
{ .clkdm_name = "core_l4_clkdm" },
{ .clkdm_name = "mpu_clkdm" },
{ .clkdm_name = "wkup_clkdm" },
{ NULL },
};
/*
* OMAP2/3-common clockdomains
*
* Even though the 2420 has a single PRCM module from the
* interconnect's perspective, internally it does appear to have
* separate PRM and CM clockdomains. The usual test case is
* sys_clkout/sys_clkout2.
*/
/* This is an implicit clockdomain - it is never defined as such in TRM */
struct clockdomain wkup_common_clkdm = {
.name = "wkup_clkdm",
.pwrdm = { .name = "wkup_pwrdm" },
.dep_bit = OMAP_EN_WKUP_SHIFT,
.flags = CLKDM_ACTIVE_WITH_MPU,
};
| gpl-2.0 |
javelinanddart/android_kernel_htc_pyramid | arch/arm/mach-omap1/io.c | 4733 | 3838 | /*
* linux/arch/arm/mach-omap1/io.c
*
* OMAP1 I/O mapping code
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <asm/tlb.h>
#include <asm/mach/map.h>
#include <plat/mux.h>
#include <plat/tc.h>
#include "iomap.h"
#include "common.h"
#include "clock.h"
extern void omap_check_revision(void);
/*
* The machine specific code may provide the extra mapping besides the
* default mapping provided here.
*/
static struct map_desc omap_io_desc[] __initdata = {
{
.virtual = OMAP1_IO_VIRT,
.pfn = __phys_to_pfn(OMAP1_IO_PHYS),
.length = OMAP1_IO_SIZE,
.type = MT_DEVICE
}
};
#if defined (CONFIG_ARCH_OMAP730) || defined (CONFIG_ARCH_OMAP850)
static struct map_desc omap7xx_io_desc[] __initdata = {
{
.virtual = OMAP7XX_DSP_BASE,
.pfn = __phys_to_pfn(OMAP7XX_DSP_START),
.length = OMAP7XX_DSP_SIZE,
.type = MT_DEVICE
}, {
.virtual = OMAP7XX_DSPREG_BASE,
.pfn = __phys_to_pfn(OMAP7XX_DSPREG_START),
.length = OMAP7XX_DSPREG_SIZE,
.type = MT_DEVICE
}
};
#endif
#ifdef CONFIG_ARCH_OMAP15XX
static struct map_desc omap1510_io_desc[] __initdata = {
{
.virtual = OMAP1510_DSP_BASE,
.pfn = __phys_to_pfn(OMAP1510_DSP_START),
.length = OMAP1510_DSP_SIZE,
.type = MT_DEVICE
}, {
.virtual = OMAP1510_DSPREG_BASE,
.pfn = __phys_to_pfn(OMAP1510_DSPREG_START),
.length = OMAP1510_DSPREG_SIZE,
.type = MT_DEVICE
}
};
#endif
#if defined(CONFIG_ARCH_OMAP16XX)
static struct map_desc omap16xx_io_desc[] __initdata = {
{
.virtual = OMAP16XX_DSP_BASE,
.pfn = __phys_to_pfn(OMAP16XX_DSP_START),
.length = OMAP16XX_DSP_SIZE,
.type = MT_DEVICE
}, {
.virtual = OMAP16XX_DSPREG_BASE,
.pfn = __phys_to_pfn(OMAP16XX_DSPREG_START),
.length = OMAP16XX_DSPREG_SIZE,
.type = MT_DEVICE
}
};
#endif
/*
* Maps common IO regions for omap1
*/
static void __init omap1_map_common_io(void)
{
iotable_init(omap_io_desc, ARRAY_SIZE(omap_io_desc));
}
#if defined (CONFIG_ARCH_OMAP730) || defined (CONFIG_ARCH_OMAP850)
void __init omap7xx_map_io(void)
{
omap1_map_common_io();
iotable_init(omap7xx_io_desc, ARRAY_SIZE(omap7xx_io_desc));
}
#endif
#ifdef CONFIG_ARCH_OMAP15XX
void __init omap15xx_map_io(void)
{
omap1_map_common_io();
iotable_init(omap1510_io_desc, ARRAY_SIZE(omap1510_io_desc));
}
#endif
#if defined(CONFIG_ARCH_OMAP16XX)
void __init omap16xx_map_io(void)
{
omap1_map_common_io();
iotable_init(omap16xx_io_desc, ARRAY_SIZE(omap16xx_io_desc));
}
#endif
/*
* Common low-level hardware init for omap1.
*/
void __init omap1_init_early(void)
{
omap_check_revision();
/* REVISIT: Refer to OMAP5910 Errata, Advisory SYS_1: "Timeout Abort
* on a Posted Write in the TIPB Bridge".
*/
omap_writew(0x0, MPU_PUBLIC_TIPB_CNTL);
omap_writew(0x0, MPU_PRIVATE_TIPB_CNTL);
/* Must init clocks early to assure that timer interrupt works
*/
omap1_clk_init();
omap1_mux_init();
omap_init_consistent_dma_size();
}
/*
* NOTE: Please use ioremap + __raw_read/write where possible instead of these
*/
u8 omap_readb(u32 pa)
{
return __raw_readb(OMAP1_IO_ADDRESS(pa));
}
EXPORT_SYMBOL(omap_readb);
u16 omap_readw(u32 pa)
{
return __raw_readw(OMAP1_IO_ADDRESS(pa));
}
EXPORT_SYMBOL(omap_readw);
u32 omap_readl(u32 pa)
{
return __raw_readl(OMAP1_IO_ADDRESS(pa));
}
EXPORT_SYMBOL(omap_readl);
void omap_writeb(u8 v, u32 pa)
{
__raw_writeb(v, OMAP1_IO_ADDRESS(pa));
}
EXPORT_SYMBOL(omap_writeb);
void omap_writew(u16 v, u32 pa)
{
__raw_writew(v, OMAP1_IO_ADDRESS(pa));
}
EXPORT_SYMBOL(omap_writew);
void omap_writel(u32 v, u32 pa)
{
__raw_writel(v, OMAP1_IO_ADDRESS(pa));
}
EXPORT_SYMBOL(omap_writel);
| gpl-2.0 |
charles1018/android_kernel_bambook_u8500 | sound/soc/ep93xx/edb93xx.c | 4989 | 3309 | /*
* SoC audio for EDB93xx
*
* Copyright (c) 2010 Alexander Sverdlin <subaparts@yandex.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This driver support CS4271 codec being master or slave, working
* in control port mode, connected either via SPI or I2C.
* The data format accepted is I2S or left-justified.
* DAPM support not implemented.
*/
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include "ep93xx-pcm.h"
static int edb93xx_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
int err;
unsigned int mclk_rate;
unsigned int rate = params_rate(params);
/*
* According to CS4271 datasheet we use MCLK/LRCK=256 for
* rates below 50kHz and 128 for higher sample rates
*/
if (rate < 50000)
mclk_rate = rate * 64 * 4;
else
mclk_rate = rate * 64 * 2;
err = snd_soc_dai_set_sysclk(codec_dai, 0, mclk_rate,
SND_SOC_CLOCK_IN);
if (err)
return err;
return snd_soc_dai_set_sysclk(cpu_dai, 0, mclk_rate,
SND_SOC_CLOCK_OUT);
}
static struct snd_soc_ops edb93xx_ops = {
.hw_params = edb93xx_hw_params,
};
static struct snd_soc_dai_link edb93xx_dai = {
.name = "CS4271",
.stream_name = "CS4271 HiFi",
.platform_name = "ep93xx-pcm-audio",
.cpu_dai_name = "ep93xx-i2s",
.codec_name = "spi0.0",
.codec_dai_name = "cs4271-hifi",
.dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_IF |
SND_SOC_DAIFMT_CBS_CFS,
.ops = &edb93xx_ops,
};
static struct snd_soc_card snd_soc_edb93xx = {
.name = "EDB93XX",
.owner = THIS_MODULE,
.dai_link = &edb93xx_dai,
.num_links = 1,
};
static int __devinit edb93xx_probe(struct platform_device *pdev)
{
struct snd_soc_card *card = &snd_soc_edb93xx;
int ret;
ret = ep93xx_i2s_acquire();
if (ret)
return ret;
card->dev = &pdev->dev;
ret = snd_soc_register_card(card);
if (ret) {
dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n",
ret);
ep93xx_i2s_release();
}
return ret;
}
static int __devexit edb93xx_remove(struct platform_device *pdev)
{
struct snd_soc_card *card = platform_get_drvdata(pdev);
snd_soc_unregister_card(card);
ep93xx_i2s_release();
return 0;
}
static struct platform_driver edb93xx_driver = {
.driver = {
.name = "edb93xx-audio",
.owner = THIS_MODULE,
},
.probe = edb93xx_probe,
.remove = __devexit_p(edb93xx_remove),
};
module_platform_driver(edb93xx_driver);
MODULE_AUTHOR("Alexander Sverdlin <subaparts@yandex.ru>");
MODULE_DESCRIPTION("ALSA SoC EDB93xx");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:edb93xx-audio");
| gpl-2.0 |
StuntRR/StuntRR-kernel | drivers/video/via/lcd.c | 4989 | 31781 | /*
* Copyright 1998-2008 VIA Technologies, Inc. All Rights Reserved.
* Copyright 2001-2008 S3 Graphics, Inc. All Rights Reserved.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation;
* either version 2, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTIES OR REPRESENTATIONS; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE.See the GNU General Public License
* for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/via-core.h>
#include <linux/via_i2c.h>
#include "global.h"
#define viafb_compact_res(x, y) (((x)<<16)|(y))
/* CLE266 Software Power Sequence */
/* {Mask}, {Data}, {Delay} */
static const int PowerSequenceOn[3][3] = {
{0x10, 0x08, 0x06}, {0x10, 0x08, 0x06}, {0x19, 0x1FE, 0x01}
};
static const int PowerSequenceOff[3][3] = {
{0x06, 0x08, 0x10}, {0x00, 0x00, 0x00}, {0xD2, 0x19, 0x01}
};
static struct _lcd_scaling_factor lcd_scaling_factor = {
/* LCD Horizontal Scaling Factor Register */
{LCD_HOR_SCALING_FACTOR_REG_NUM,
{{CR9F, 0, 1}, {CR77, 0, 7}, {CR79, 4, 5} } },
/* LCD Vertical Scaling Factor Register */
{LCD_VER_SCALING_FACTOR_REG_NUM,
{{CR79, 3, 3}, {CR78, 0, 7}, {CR79, 6, 7} } }
};
static struct _lcd_scaling_factor lcd_scaling_factor_CLE = {
/* LCD Horizontal Scaling Factor Register */
{LCD_HOR_SCALING_FACTOR_REG_NUM_CLE, {{CR77, 0, 7}, {CR79, 4, 5} } },
/* LCD Vertical Scaling Factor Register */
{LCD_VER_SCALING_FACTOR_REG_NUM_CLE, {{CR78, 0, 7}, {CR79, 6, 7} } }
};
static bool lvds_identify_integratedlvds(void);
static void __devinit fp_id_to_vindex(int panel_id);
static int lvds_register_read(int index);
static void load_lcd_scaling(int set_hres, int set_vres, int panel_hres,
int panel_vres);
static void lcd_patch_skew_dvp0(struct lvds_setting_information
*plvds_setting_info,
struct lvds_chip_information *plvds_chip_info);
static void lcd_patch_skew_dvp1(struct lvds_setting_information
*plvds_setting_info,
struct lvds_chip_information *plvds_chip_info);
static void lcd_patch_skew(struct lvds_setting_information
*plvds_setting_info, struct lvds_chip_information *plvds_chip_info);
static void integrated_lvds_disable(struct lvds_setting_information
*plvds_setting_info,
struct lvds_chip_information *plvds_chip_info);
static void integrated_lvds_enable(struct lvds_setting_information
*plvds_setting_info,
struct lvds_chip_information *plvds_chip_info);
static void lcd_powersequence_off(void);
static void lcd_powersequence_on(void);
static void fill_lcd_format(void);
static void check_diport_of_integrated_lvds(
struct lvds_chip_information *plvds_chip_info,
struct lvds_setting_information
*plvds_setting_info);
static inline bool check_lvds_chip(int device_id_subaddr, int device_id)
{
return lvds_register_read(device_id_subaddr) == device_id;
}
void __devinit viafb_init_lcd_size(void)
{
DEBUG_MSG(KERN_INFO "viafb_init_lcd_size()\n");
fp_id_to_vindex(viafb_lcd_panel_id);
viaparinfo->lvds_setting_info2->lcd_panel_hres =
viaparinfo->lvds_setting_info->lcd_panel_hres;
viaparinfo->lvds_setting_info2->lcd_panel_vres =
viaparinfo->lvds_setting_info->lcd_panel_vres;
viaparinfo->lvds_setting_info2->device_lcd_dualedge =
viaparinfo->lvds_setting_info->device_lcd_dualedge;
viaparinfo->lvds_setting_info2->LCDDithering =
viaparinfo->lvds_setting_info->LCDDithering;
}
static bool lvds_identify_integratedlvds(void)
{
if (viafb_display_hardware_layout == HW_LAYOUT_LCD_EXTERNAL_LCD2) {
/* Two dual channel LCD (Internal LVDS + External LVDS): */
/* If we have an external LVDS, such as VT1636, we should
have its chip ID already. */
if (viaparinfo->chip_info->lvds_chip_info.lvds_chip_name) {
viaparinfo->chip_info->lvds_chip_info2.lvds_chip_name =
INTEGRATED_LVDS;
DEBUG_MSG(KERN_INFO "Support two dual channel LVDS! "
"(Internal LVDS + External LVDS)\n");
} else {
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name =
INTEGRATED_LVDS;
DEBUG_MSG(KERN_INFO "Not found external LVDS, "
"so can't support two dual channel LVDS!\n");
}
} else if (viafb_display_hardware_layout == HW_LAYOUT_LCD1_LCD2) {
/* Two single channel LCD (Internal LVDS + Internal LVDS): */
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name =
INTEGRATED_LVDS;
viaparinfo->chip_info->lvds_chip_info2.lvds_chip_name =
INTEGRATED_LVDS;
DEBUG_MSG(KERN_INFO "Support two single channel LVDS! "
"(Internal LVDS + Internal LVDS)\n");
} else if (viafb_display_hardware_layout != HW_LAYOUT_DVI_ONLY) {
/* If we have found external LVDS, just use it,
otherwise, we will use internal LVDS as default. */
if (!viaparinfo->chip_info->lvds_chip_info.lvds_chip_name) {
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name =
INTEGRATED_LVDS;
DEBUG_MSG(KERN_INFO "Found Integrated LVDS!\n");
}
} else {
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name =
NON_LVDS_TRANSMITTER;
DEBUG_MSG(KERN_INFO "Do not support LVDS!\n");
return false;
}
return true;
}
bool __devinit viafb_lvds_trasmitter_identify(void)
{
if (viafb_lvds_identify_vt1636(VIA_PORT_31)) {
viaparinfo->chip_info->lvds_chip_info.i2c_port = VIA_PORT_31;
DEBUG_MSG(KERN_INFO
"Found VIA VT1636 LVDS on port i2c 0x31\n");
} else {
if (viafb_lvds_identify_vt1636(VIA_PORT_2C)) {
viaparinfo->chip_info->lvds_chip_info.i2c_port =
VIA_PORT_2C;
DEBUG_MSG(KERN_INFO
"Found VIA VT1636 LVDS on port gpio 0x2c\n");
}
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700)
lvds_identify_integratedlvds();
if (viaparinfo->chip_info->lvds_chip_info.lvds_chip_name)
return true;
/* Check for VT1631: */
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name = VT1631_LVDS;
viaparinfo->chip_info->lvds_chip_info.lvds_chip_slave_addr =
VT1631_LVDS_I2C_ADDR;
if (check_lvds_chip(VT1631_DEVICE_ID_REG, VT1631_DEVICE_ID)) {
DEBUG_MSG(KERN_INFO "\n VT1631 LVDS ! \n");
DEBUG_MSG(KERN_INFO "\n %2d",
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name);
DEBUG_MSG(KERN_INFO "\n %2d",
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name);
return true;
}
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name =
NON_LVDS_TRANSMITTER;
viaparinfo->chip_info->lvds_chip_info.lvds_chip_slave_addr =
VT1631_LVDS_I2C_ADDR;
return false;
}
static void __devinit fp_id_to_vindex(int panel_id)
{
DEBUG_MSG(KERN_INFO "fp_get_panel_id()\n");
if (panel_id > LCD_PANEL_ID_MAXIMUM)
viafb_lcd_panel_id = panel_id =
viafb_read_reg(VIACR, CR3F) & 0x0F;
switch (panel_id) {
case 0x0:
viaparinfo->lvds_setting_info->lcd_panel_hres = 640;
viaparinfo->lvds_setting_info->lcd_panel_vres = 480;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x1:
viaparinfo->lvds_setting_info->lcd_panel_hres = 800;
viaparinfo->lvds_setting_info->lcd_panel_vres = 600;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x2:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1024;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x3:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1280;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x4:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1280;
viaparinfo->lvds_setting_info->lcd_panel_vres = 1024;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x5:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1400;
viaparinfo->lvds_setting_info->lcd_panel_vres = 1050;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x6:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1600;
viaparinfo->lvds_setting_info->lcd_panel_vres = 1200;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x8:
viaparinfo->lvds_setting_info->lcd_panel_hres = 800;
viaparinfo->lvds_setting_info->lcd_panel_vres = 480;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x9:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1024;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0xA:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1024;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
case 0xB:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1024;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
case 0xC:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1280;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
case 0xD:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1280;
viaparinfo->lvds_setting_info->lcd_panel_vres = 1024;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
case 0xE:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1400;
viaparinfo->lvds_setting_info->lcd_panel_vres = 1050;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
case 0xF:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1600;
viaparinfo->lvds_setting_info->lcd_panel_vres = 1200;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
case 0x10:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1366;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
case 0x11:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1024;
viaparinfo->lvds_setting_info->lcd_panel_vres = 600;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x12:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1280;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x13:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1280;
viaparinfo->lvds_setting_info->lcd_panel_vres = 800;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x14:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1360;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
case 0x15:
viaparinfo->lvds_setting_info->lcd_panel_hres = 1280;
viaparinfo->lvds_setting_info->lcd_panel_vres = 768;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 1;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
case 0x16:
viaparinfo->lvds_setting_info->lcd_panel_hres = 480;
viaparinfo->lvds_setting_info->lcd_panel_vres = 640;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 1;
break;
case 0x17:
/* OLPC XO-1.5 panel */
viaparinfo->lvds_setting_info->lcd_panel_hres = 1200;
viaparinfo->lvds_setting_info->lcd_panel_vres = 900;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 0;
break;
default:
viaparinfo->lvds_setting_info->lcd_panel_hres = 800;
viaparinfo->lvds_setting_info->lcd_panel_vres = 600;
viaparinfo->lvds_setting_info->device_lcd_dualedge = 0;
viaparinfo->lvds_setting_info->LCDDithering = 1;
}
}
static int lvds_register_read(int index)
{
u8 data;
viafb_i2c_readbyte(VIA_PORT_2C,
(u8) viaparinfo->chip_info->lvds_chip_info.lvds_chip_slave_addr,
(u8) index, &data);
return data;
}
static void load_lcd_scaling(int set_hres, int set_vres, int panel_hres,
int panel_vres)
{
int reg_value = 0;
int viafb_load_reg_num;
struct io_register *reg = NULL;
DEBUG_MSG(KERN_INFO "load_lcd_scaling()!!\n");
/* LCD Scaling Enable */
viafb_write_reg_mask(CR79, VIACR, 0x07, BIT0 + BIT1 + BIT2);
/* Check if expansion for horizontal */
if (set_hres < panel_hres) {
/* Load Horizontal Scaling Factor */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
case UNICHROME_K400:
reg_value =
CLE266_LCD_HOR_SCF_FORMULA(set_hres, panel_hres);
viafb_load_reg_num =
lcd_scaling_factor_CLE.lcd_hor_scaling_factor.
reg_num;
reg = lcd_scaling_factor_CLE.lcd_hor_scaling_factor.reg;
viafb_load_reg(reg_value,
viafb_load_reg_num, reg, VIACR);
break;
case UNICHROME_K800:
case UNICHROME_PM800:
case UNICHROME_CN700:
case UNICHROME_CX700:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
case UNICHROME_CN750:
case UNICHROME_VX800:
case UNICHROME_VX855:
case UNICHROME_VX900:
reg_value =
K800_LCD_HOR_SCF_FORMULA(set_hres, panel_hres);
/* Horizontal scaling enabled */
viafb_write_reg_mask(CRA2, VIACR, 0xC0, BIT7 + BIT6);
viafb_load_reg_num =
lcd_scaling_factor.lcd_hor_scaling_factor.reg_num;
reg = lcd_scaling_factor.lcd_hor_scaling_factor.reg;
viafb_load_reg(reg_value,
viafb_load_reg_num, reg, VIACR);
break;
}
DEBUG_MSG(KERN_INFO "Horizontal Scaling value = %d", reg_value);
} else {
/* Horizontal scaling disabled */
viafb_write_reg_mask(CRA2, VIACR, 0x00, BIT7);
}
/* Check if expansion for vertical */
if (set_vres < panel_vres) {
/* Load Vertical Scaling Factor */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
case UNICHROME_K400:
reg_value =
CLE266_LCD_VER_SCF_FORMULA(set_vres, panel_vres);
viafb_load_reg_num =
lcd_scaling_factor_CLE.lcd_ver_scaling_factor.
reg_num;
reg = lcd_scaling_factor_CLE.lcd_ver_scaling_factor.reg;
viafb_load_reg(reg_value,
viafb_load_reg_num, reg, VIACR);
break;
case UNICHROME_K800:
case UNICHROME_PM800:
case UNICHROME_CN700:
case UNICHROME_CX700:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
case UNICHROME_CN750:
case UNICHROME_VX800:
case UNICHROME_VX855:
case UNICHROME_VX900:
reg_value =
K800_LCD_VER_SCF_FORMULA(set_vres, panel_vres);
/* Vertical scaling enabled */
viafb_write_reg_mask(CRA2, VIACR, 0x08, BIT3);
viafb_load_reg_num =
lcd_scaling_factor.lcd_ver_scaling_factor.reg_num;
reg = lcd_scaling_factor.lcd_ver_scaling_factor.reg;
viafb_load_reg(reg_value,
viafb_load_reg_num, reg, VIACR);
break;
}
DEBUG_MSG(KERN_INFO "Vertical Scaling value = %d", reg_value);
} else {
/* Vertical scaling disabled */
viafb_write_reg_mask(CRA2, VIACR, 0x00, BIT3);
}
}
static void via_pitch_alignment_patch_lcd(int iga_path, int hres, int bpp)
{
unsigned char cr13, cr35, cr65, cr66, cr67;
unsigned long dwScreenPitch = 0;
unsigned long dwPitch;
dwPitch = hres * (bpp >> 3);
if (dwPitch & 0x1F) {
dwScreenPitch = ((dwPitch + 31) & ~31) >> 3;
if (iga_path == IGA2) {
if (bpp > 8) {
cr66 = (unsigned char)(dwScreenPitch & 0xFF);
viafb_write_reg(CR66, VIACR, cr66);
cr67 = viafb_read_reg(VIACR, CR67) & 0xFC;
cr67 |=
(unsigned
char)((dwScreenPitch & 0x300) >> 8);
viafb_write_reg(CR67, VIACR, cr67);
}
/* Fetch Count */
cr67 = viafb_read_reg(VIACR, CR67) & 0xF3;
cr67 |= (unsigned char)((dwScreenPitch & 0x600) >> 7);
viafb_write_reg(CR67, VIACR, cr67);
cr65 = (unsigned char)((dwScreenPitch >> 1) & 0xFF);
cr65 += 2;
viafb_write_reg(CR65, VIACR, cr65);
} else {
if (bpp > 8) {
cr13 = (unsigned char)(dwScreenPitch & 0xFF);
viafb_write_reg(CR13, VIACR, cr13);
cr35 = viafb_read_reg(VIACR, CR35) & 0x1F;
cr35 |=
(unsigned
char)((dwScreenPitch & 0x700) >> 3);
viafb_write_reg(CR35, VIACR, cr35);
}
}
}
}
static void lcd_patch_skew_dvp0(struct lvds_setting_information
*plvds_setting_info,
struct lvds_chip_information *plvds_chip_info)
{
if (VT1636_LVDS == plvds_chip_info->lvds_chip_name) {
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_P4M900:
viafb_vt1636_patch_skew_on_vt3364(plvds_setting_info,
plvds_chip_info);
break;
case UNICHROME_P4M890:
viafb_vt1636_patch_skew_on_vt3327(plvds_setting_info,
plvds_chip_info);
break;
}
}
}
static void lcd_patch_skew_dvp1(struct lvds_setting_information
*plvds_setting_info,
struct lvds_chip_information *plvds_chip_info)
{
if (VT1636_LVDS == plvds_chip_info->lvds_chip_name) {
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CX700:
viafb_vt1636_patch_skew_on_vt3324(plvds_setting_info,
plvds_chip_info);
break;
}
}
}
static void lcd_patch_skew(struct lvds_setting_information
*plvds_setting_info, struct lvds_chip_information *plvds_chip_info)
{
DEBUG_MSG(KERN_INFO "lcd_patch_skew\n");
switch (plvds_chip_info->output_interface) {
case INTERFACE_DVP0:
lcd_patch_skew_dvp0(plvds_setting_info, plvds_chip_info);
break;
case INTERFACE_DVP1:
lcd_patch_skew_dvp1(plvds_setting_info, plvds_chip_info);
break;
case INTERFACE_DFP_LOW:
if (UNICHROME_P4M900 == viaparinfo->chip_info->gfx_chip_name) {
viafb_write_reg_mask(CR99, VIACR, 0x08,
BIT0 + BIT1 + BIT2 + BIT3);
}
break;
}
}
/* LCD Set Mode */
void viafb_lcd_set_mode(const struct fb_var_screeninfo *var, u16 cxres,
u16 cyres, struct lvds_setting_information *plvds_setting_info,
struct lvds_chip_information *plvds_chip_info)
{
int set_iga = plvds_setting_info->iga_path;
int mode_bpp = var->bits_per_pixel;
int set_hres = cxres ? cxres : var->xres;
int set_vres = cyres ? cyres : var->yres;
int panel_hres = plvds_setting_info->lcd_panel_hres;
int panel_vres = plvds_setting_info->lcd_panel_vres;
u32 clock;
struct display_timing timing;
struct fb_var_screeninfo panel_var;
const struct fb_videomode *mode_crt_table, *panel_crt_table;
DEBUG_MSG(KERN_INFO "viafb_lcd_set_mode!!\n");
/* Get mode table */
mode_crt_table = viafb_get_best_mode(set_hres, set_vres, 60);
/* Get panel table Pointer */
panel_crt_table = viafb_get_best_mode(panel_hres, panel_vres, 60);
viafb_fill_var_timing_info(&panel_var, panel_crt_table);
DEBUG_MSG(KERN_INFO "bellow viafb_lcd_set_mode!!\n");
if (VT1636_LVDS == plvds_chip_info->lvds_chip_name)
viafb_init_lvds_vt1636(plvds_setting_info, plvds_chip_info);
clock = PICOS2KHZ(panel_crt_table->pixclock) * 1000;
plvds_setting_info->vclk = clock;
if (set_iga == IGA2 && (set_hres < panel_hres || set_vres < panel_vres)
&& plvds_setting_info->display_method == LCD_EXPANDSION) {
timing = var_to_timing(&panel_var, panel_hres, panel_vres);
load_lcd_scaling(set_hres, set_vres, panel_hres, panel_vres);
} else {
timing = var_to_timing(&panel_var, set_hres, set_vres);
if (set_iga == IGA2)
/* disable scaling */
via_write_reg_mask(VIACR, 0x79, 0x00,
BIT0 + BIT1 + BIT2);
}
if (set_iga == IGA1)
via_set_primary_timing(&timing);
else if (set_iga == IGA2)
via_set_secondary_timing(&timing);
/* Fetch count for IGA2 only */
viafb_load_fetch_count_reg(set_hres, mode_bpp / 8, set_iga);
if ((viaparinfo->chip_info->gfx_chip_name != UNICHROME_CLE266)
&& (viaparinfo->chip_info->gfx_chip_name != UNICHROME_K400))
viafb_load_FIFO_reg(set_iga, set_hres, set_vres);
fill_lcd_format();
viafb_set_vclock(clock, set_iga);
lcd_patch_skew(plvds_setting_info, plvds_chip_info);
/* If K8M800, enable LCD Prefetch Mode. */
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800)
|| (UNICHROME_K8M890 == viaparinfo->chip_info->gfx_chip_name))
viafb_write_reg_mask(CR6A, VIACR, 0x01, BIT0);
/* Patch for non 32bit alignment mode */
via_pitch_alignment_patch_lcd(plvds_setting_info->iga_path, set_hres,
var->bits_per_pixel);
}
static void integrated_lvds_disable(struct lvds_setting_information
*plvds_setting_info,
struct lvds_chip_information *plvds_chip_info)
{
bool turn_off_first_powersequence = false;
bool turn_off_second_powersequence = false;
if (INTERFACE_LVDS0LVDS1 == plvds_chip_info->output_interface)
turn_off_first_powersequence = true;
if (INTERFACE_LVDS0 == plvds_chip_info->output_interface)
turn_off_first_powersequence = true;
if (INTERFACE_LVDS1 == plvds_chip_info->output_interface)
turn_off_second_powersequence = true;
if (turn_off_second_powersequence) {
/* Use second power sequence control: */
/* Turn off power sequence. */
viafb_write_reg_mask(CRD4, VIACR, 0, BIT1);
/* Turn off back light. */
viafb_write_reg_mask(CRD3, VIACR, 0xC0, BIT6 + BIT7);
}
if (turn_off_first_powersequence) {
/* Use first power sequence control: */
/* Turn off power sequence. */
viafb_write_reg_mask(CR6A, VIACR, 0, BIT3);
/* Turn off back light. */
viafb_write_reg_mask(CR91, VIACR, 0xC0, BIT6 + BIT7);
}
/* Power off LVDS channel. */
switch (plvds_chip_info->output_interface) {
case INTERFACE_LVDS0:
{
viafb_write_reg_mask(CRD2, VIACR, 0x80, BIT7);
break;
}
case INTERFACE_LVDS1:
{
viafb_write_reg_mask(CRD2, VIACR, 0x40, BIT6);
break;
}
case INTERFACE_LVDS0LVDS1:
{
viafb_write_reg_mask(CRD2, VIACR, 0xC0, BIT6 + BIT7);
break;
}
}
}
static void integrated_lvds_enable(struct lvds_setting_information
*plvds_setting_info,
struct lvds_chip_information *plvds_chip_info)
{
DEBUG_MSG(KERN_INFO "integrated_lvds_enable, out_interface:%d\n",
plvds_chip_info->output_interface);
if (plvds_setting_info->lcd_mode == LCD_SPWG)
viafb_write_reg_mask(CRD2, VIACR, 0x00, BIT0 + BIT1);
else
viafb_write_reg_mask(CRD2, VIACR, 0x03, BIT0 + BIT1);
switch (plvds_chip_info->output_interface) {
case INTERFACE_LVDS0LVDS1:
case INTERFACE_LVDS0:
/* Use first power sequence control: */
/* Use hardware control power sequence. */
viafb_write_reg_mask(CR91, VIACR, 0, BIT0);
/* Turn on back light. */
viafb_write_reg_mask(CR91, VIACR, 0, BIT6 + BIT7);
/* Turn on hardware power sequence. */
viafb_write_reg_mask(CR6A, VIACR, 0x08, BIT3);
break;
case INTERFACE_LVDS1:
/* Use second power sequence control: */
/* Use hardware control power sequence. */
viafb_write_reg_mask(CRD3, VIACR, 0, BIT0);
/* Turn on back light. */
viafb_write_reg_mask(CRD3, VIACR, 0, BIT6 + BIT7);
/* Turn on hardware power sequence. */
viafb_write_reg_mask(CRD4, VIACR, 0x02, BIT1);
break;
}
/* Power on LVDS channel. */
switch (plvds_chip_info->output_interface) {
case INTERFACE_LVDS0:
{
viafb_write_reg_mask(CRD2, VIACR, 0, BIT7);
break;
}
case INTERFACE_LVDS1:
{
viafb_write_reg_mask(CRD2, VIACR, 0, BIT6);
break;
}
case INTERFACE_LVDS0LVDS1:
{
viafb_write_reg_mask(CRD2, VIACR, 0, BIT6 + BIT7);
break;
}
}
}
void viafb_lcd_disable(void)
{
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) {
lcd_powersequence_off();
/* DI1 pad off */
viafb_write_reg_mask(SR1E, VIASR, 0x00, 0x30);
} else if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) {
if (viafb_LCD2_ON
&& (INTEGRATED_LVDS ==
viaparinfo->chip_info->lvds_chip_info2.lvds_chip_name))
integrated_lvds_disable(viaparinfo->lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info2);
if (INTEGRATED_LVDS ==
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name)
integrated_lvds_disable(viaparinfo->lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info);
if (VT1636_LVDS == viaparinfo->chip_info->
lvds_chip_info.lvds_chip_name)
viafb_disable_lvds_vt1636(viaparinfo->lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info);
} else if (VT1636_LVDS ==
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name) {
viafb_disable_lvds_vt1636(viaparinfo->lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info);
} else {
/* Backlight off */
viafb_write_reg_mask(SR3D, VIASR, 0x00, 0x20);
/* 24 bit DI data paht off */
viafb_write_reg_mask(CR91, VIACR, 0x80, 0x80);
}
/* Disable expansion bit */
viafb_write_reg_mask(CR79, VIACR, 0x00, 0x01);
/* Simultaneout disabled */
viafb_write_reg_mask(CR6B, VIACR, 0x00, 0x08);
}
static void set_lcd_output_path(int set_iga, int output_interface)
{
switch (output_interface) {
case INTERFACE_DFP:
if ((UNICHROME_K8M890 == viaparinfo->chip_info->gfx_chip_name)
|| (UNICHROME_P4M890 ==
viaparinfo->chip_info->gfx_chip_name))
viafb_write_reg_mask(CR97, VIACR, 0x84,
BIT7 + BIT2 + BIT1 + BIT0);
case INTERFACE_DVP0:
case INTERFACE_DVP1:
case INTERFACE_DFP_HIGH:
case INTERFACE_DFP_LOW:
if (set_iga == IGA2)
viafb_write_reg(CR91, VIACR, 0x00);
break;
}
}
void viafb_lcd_enable(void)
{
viafb_write_reg_mask(CR6B, VIACR, 0x00, BIT3);
viafb_write_reg_mask(CR6A, VIACR, 0x08, BIT3);
set_lcd_output_path(viaparinfo->lvds_setting_info->iga_path,
viaparinfo->chip_info->lvds_chip_info.output_interface);
if (viafb_LCD2_ON)
set_lcd_output_path(viaparinfo->lvds_setting_info2->iga_path,
viaparinfo->chip_info->
lvds_chip_info2.output_interface);
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) {
/* DI1 pad on */
viafb_write_reg_mask(SR1E, VIASR, 0x30, 0x30);
lcd_powersequence_on();
} else if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) {
if (viafb_LCD2_ON && (INTEGRATED_LVDS ==
viaparinfo->chip_info->lvds_chip_info2.lvds_chip_name))
integrated_lvds_enable(viaparinfo->lvds_setting_info2, \
&viaparinfo->chip_info->lvds_chip_info2);
if (INTEGRATED_LVDS ==
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name)
integrated_lvds_enable(viaparinfo->lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info);
if (VT1636_LVDS == viaparinfo->chip_info->
lvds_chip_info.lvds_chip_name)
viafb_enable_lvds_vt1636(viaparinfo->
lvds_setting_info, &viaparinfo->chip_info->
lvds_chip_info);
} else if (VT1636_LVDS ==
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name) {
viafb_enable_lvds_vt1636(viaparinfo->lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info);
} else {
/* Backlight on */
viafb_write_reg_mask(SR3D, VIASR, 0x20, 0x20);
/* 24 bit DI data paht on */
viafb_write_reg_mask(CR91, VIACR, 0x00, 0x80);
/* LCD enabled */
viafb_write_reg_mask(CR6A, VIACR, 0x48, 0x48);
}
}
static void lcd_powersequence_off(void)
{
int i, mask, data;
/* Software control power sequence */
viafb_write_reg_mask(CR91, VIACR, 0x11, 0x11);
for (i = 0; i < 3; i++) {
mask = PowerSequenceOff[0][i];
data = PowerSequenceOff[1][i] & mask;
viafb_write_reg_mask(CR91, VIACR, (u8) data, (u8) mask);
udelay(PowerSequenceOff[2][i]);
}
/* Disable LCD */
viafb_write_reg_mask(CR6A, VIACR, 0x00, 0x08);
}
static void lcd_powersequence_on(void)
{
int i, mask, data;
/* Software control power sequence */
viafb_write_reg_mask(CR91, VIACR, 0x11, 0x11);
/* Enable LCD */
viafb_write_reg_mask(CR6A, VIACR, 0x08, 0x08);
for (i = 0; i < 3; i++) {
mask = PowerSequenceOn[0][i];
data = PowerSequenceOn[1][i] & mask;
viafb_write_reg_mask(CR91, VIACR, (u8) data, (u8) mask);
udelay(PowerSequenceOn[2][i]);
}
udelay(1);
}
static void fill_lcd_format(void)
{
u8 bdithering = 0, bdual = 0;
if (viaparinfo->lvds_setting_info->device_lcd_dualedge)
bdual = BIT4;
if (viaparinfo->lvds_setting_info->LCDDithering)
bdithering = BIT0;
/* Dual & Dithering */
viafb_write_reg_mask(CR88, VIACR, (bdithering | bdual), BIT4 + BIT0);
}
static void check_diport_of_integrated_lvds(
struct lvds_chip_information *plvds_chip_info,
struct lvds_setting_information
*plvds_setting_info)
{
/* Determine LCD DI Port by hardware layout. */
switch (viafb_display_hardware_layout) {
case HW_LAYOUT_LCD_ONLY:
{
if (plvds_setting_info->device_lcd_dualedge) {
plvds_chip_info->output_interface =
INTERFACE_LVDS0LVDS1;
} else {
plvds_chip_info->output_interface =
INTERFACE_LVDS0;
}
break;
}
case HW_LAYOUT_DVI_ONLY:
{
plvds_chip_info->output_interface = INTERFACE_NONE;
break;
}
case HW_LAYOUT_LCD1_LCD2:
case HW_LAYOUT_LCD_EXTERNAL_LCD2:
{
plvds_chip_info->output_interface =
INTERFACE_LVDS0LVDS1;
break;
}
case HW_LAYOUT_LCD_DVI:
{
plvds_chip_info->output_interface = INTERFACE_LVDS1;
break;
}
default:
{
plvds_chip_info->output_interface = INTERFACE_LVDS1;
break;
}
}
DEBUG_MSG(KERN_INFO
"Display Hardware Layout: 0x%x, LCD DI Port: 0x%x\n",
viafb_display_hardware_layout,
plvds_chip_info->output_interface);
}
void __devinit viafb_init_lvds_output_interface(struct lvds_chip_information
*plvds_chip_info,
struct lvds_setting_information
*plvds_setting_info)
{
if (INTERFACE_NONE != plvds_chip_info->output_interface) {
/*Do nothing, lcd port is specified by module parameter */
return;
}
switch (plvds_chip_info->lvds_chip_name) {
case VT1636_LVDS:
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CX700:
plvds_chip_info->output_interface = INTERFACE_DVP1;
break;
case UNICHROME_CN700:
plvds_chip_info->output_interface = INTERFACE_DFP_LOW;
break;
default:
plvds_chip_info->output_interface = INTERFACE_DVP0;
break;
}
break;
case INTEGRATED_LVDS:
check_diport_of_integrated_lvds(plvds_chip_info,
plvds_setting_info);
break;
default:
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_K8M890:
case UNICHROME_P4M900:
case UNICHROME_P4M890:
plvds_chip_info->output_interface = INTERFACE_DFP_LOW;
break;
default:
plvds_chip_info->output_interface = INTERFACE_DFP;
break;
}
break;
}
}
bool viafb_lcd_get_mobile_state(bool *mobile)
{
unsigned char __iomem *romptr, *tableptr, *biosptr;
u8 core_base;
/* Rom address */
const u32 romaddr = 0x000C0000;
u16 start_pattern;
biosptr = ioremap(romaddr, 0x10000);
start_pattern = readw(biosptr);
/* Compare pattern */
if (start_pattern == 0xAA55) {
/* Get the start of Table */
/* 0x1B means BIOS offset position */
romptr = biosptr + 0x1B;
tableptr = biosptr + readw(romptr);
/* Get the start of biosver structure */
/* 18 means BIOS version position. */
romptr = tableptr + 18;
romptr = biosptr + readw(romptr);
/* The offset should be 44, but the
actual image is less three char. */
/* pRom += 44; */
romptr += 41;
core_base = readb(romptr);
if (core_base & 0x8)
*mobile = false;
else
*mobile = true;
/* release memory */
iounmap(biosptr);
return true;
} else {
iounmap(biosptr);
return false;
}
}
| gpl-2.0 |
TheNotOnly/android_kernel_lge_jagnm_kk | sound/soc/samsung/smdk_wm9713.c | 4989 | 2675 | /*
* smdk_wm9713.c -- SoC audio for SMDK
*
* Copyright 2010 Samsung Electronics Co. Ltd.
* Author: Jaswinder Singh Brar <jassisinghbrar@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
*/
#include <linux/module.h>
#include <sound/soc.h>
static struct snd_soc_card smdk;
/*
* Default CFG switch settings to use this driver:
*
* SMDK6410: Set CFG1 1-3 On, CFG2 1-4 Off
* SMDKC100: Set CFG6 1-3 On, CFG7 1 On
* SMDKC110: Set CFGB10 1-2 Off, CFGB12 1-3 On
* SMDKV210: Set CFGB10 1-2 Off, CFGB12 1-3 On
* SMDKV310: Set CFG2 1-2 Off, CFG4 All On, CFG7 All Off, CFG8 1-On
*/
/*
Playback (HeadPhone):-
$ amixer sset 'Headphone' unmute
$ amixer sset 'Right Headphone Out Mux' 'Headphone'
$ amixer sset 'Left Headphone Out Mux' 'Headphone'
$ amixer sset 'Right HP Mixer PCM' unmute
$ amixer sset 'Left HP Mixer PCM' unmute
Capture (LineIn):-
$ amixer sset 'Right Capture Source' 'Line'
$ amixer sset 'Left Capture Source' 'Line'
*/
static struct snd_soc_dai_link smdk_dai = {
.name = "AC97",
.stream_name = "AC97 PCM",
.platform_name = "samsung-audio",
.cpu_dai_name = "samsung-ac97",
.codec_dai_name = "wm9713-hifi",
.codec_name = "wm9713-codec",
};
static struct snd_soc_card smdk = {
.name = "SMDK WM9713",
.owner = THIS_MODULE,
.dai_link = &smdk_dai,
.num_links = 1,
};
static struct platform_device *smdk_snd_wm9713_device;
static struct platform_device *smdk_snd_ac97_device;
static int __init smdk_init(void)
{
int ret;
smdk_snd_wm9713_device = platform_device_alloc("wm9713-codec", -1);
if (!smdk_snd_wm9713_device)
return -ENOMEM;
ret = platform_device_add(smdk_snd_wm9713_device);
if (ret)
goto err1;
smdk_snd_ac97_device = platform_device_alloc("soc-audio", -1);
if (!smdk_snd_ac97_device) {
ret = -ENOMEM;
goto err2;
}
platform_set_drvdata(smdk_snd_ac97_device, &smdk);
ret = platform_device_add(smdk_snd_ac97_device);
if (ret)
goto err3;
return 0;
err3:
platform_device_put(smdk_snd_ac97_device);
err2:
platform_device_del(smdk_snd_wm9713_device);
err1:
platform_device_put(smdk_snd_wm9713_device);
return ret;
}
static void __exit smdk_exit(void)
{
platform_device_unregister(smdk_snd_ac97_device);
platform_device_unregister(smdk_snd_wm9713_device);
}
module_init(smdk_init);
module_exit(smdk_exit);
/* Module information */
MODULE_AUTHOR("Jaswinder Singh Brar, jassisinghbrar@gmail.com");
MODULE_DESCRIPTION("ALSA SoC SMDK+WM9713");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Phoenix-Silver/ZTE-Blade-2.6.35.10 | drivers/pcmcia/vrc4171_card.c | 7037 | 18198 | /*
* vrc4171_card.c, NEC VRC4171 Card Controller driver for Socket Services.
*
* Copyright (C) 2003-2005 Yoichi Yuasa <yuasa@linux-mips.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/types.h>
#include <linux/platform_device.h>
#include <asm/io.h>
#include <pcmcia/ss.h>
#include "i82365.h"
MODULE_DESCRIPTION("NEC VRC4171 Card Controllers driver for Socket Services");
MODULE_AUTHOR("Yoichi Yuasa <yuasa@linux-mips.org>");
MODULE_LICENSE("GPL");
#define CARD_MAX_SLOTS 2
#define CARD_SLOTA 0
#define CARD_SLOTB 1
#define CARD_SLOTB_OFFSET 0x40
#define CARD_MEM_START 0x10000000
#define CARD_MEM_END 0x13ffffff
#define CARD_MAX_MEM_OFFSET 0x3ffffff
#define CARD_MAX_MEM_SPEED 1000
#define CARD_CONTROLLER_INDEX 0x03e0
#define CARD_CONTROLLER_DATA 0x03e1
/* Power register */
#define VPP_GET_VCC 0x01
#define POWER_ENABLE 0x10
#define CARD_VOLTAGE_SENSE 0x1f
#define VCC_3VORXV_CAPABLE 0x00
#define VCC_XV_ONLY 0x01
#define VCC_3V_CAPABLE 0x02
#define VCC_5V_ONLY 0x03
#define CARD_VOLTAGE_SELECT 0x2f
#define VCC_3V 0x01
#define VCC_5V 0x00
#define VCC_XV 0x02
#define VCC_STATUS_3V 0x02
#define VCC_STATUS_5V 0x01
#define VCC_STATUS_XV 0x03
#define GLOBAL_CONTROL 0x1e
#define EXWRBK 0x04
#define IRQPM_EN 0x08
#define CLRPMIRQ 0x10
#define INTERRUPT_STATUS 0x05fa
#define IRQ_A 0x02
#define IRQ_B 0x04
#define CONFIGURATION1 0x05fe
#define SLOTB_CONFIG 0xc000
#define SLOTB_NONE 0x0000
#define SLOTB_PCCARD 0x4000
#define SLOTB_CF 0x8000
#define SLOTB_FLASHROM 0xc000
#define CARD_CONTROLLER_START CARD_CONTROLLER_INDEX
#define CARD_CONTROLLER_END CARD_CONTROLLER_DATA
#define IO_MAX_MAPS 2
#define MEM_MAX_MAPS 5
typedef enum {
SLOT_PROBE = 0,
SLOT_NOPROBE_IO,
SLOT_NOPROBE_MEM,
SLOT_NOPROBE_ALL,
SLOT_INITIALIZED,
} vrc4171_slot_t;
typedef enum {
SLOTB_IS_NONE,
SLOTB_IS_PCCARD,
SLOTB_IS_CF,
SLOTB_IS_FLASHROM,
} vrc4171_slotb_t;
typedef struct vrc4171_socket {
vrc4171_slot_t slot;
struct pcmcia_socket pcmcia_socket;
char name[24];
int csc_irq;
int io_irq;
spinlock_t lock;
} vrc4171_socket_t;
static vrc4171_socket_t vrc4171_sockets[CARD_MAX_SLOTS];
static vrc4171_slotb_t vrc4171_slotb = SLOTB_IS_NONE;
static char vrc4171_card_name[] = "NEC VRC4171 Card Controller";
static unsigned int vrc4171_irq;
static uint16_t vrc4171_irq_mask = 0xdeb8;
static struct resource vrc4171_card_resource[3] = {
{ .name = vrc4171_card_name,
.start = CARD_CONTROLLER_START,
.end = CARD_CONTROLLER_END,
.flags = IORESOURCE_IO, },
{ .name = vrc4171_card_name,
.start = INTERRUPT_STATUS,
.end = INTERRUPT_STATUS,
.flags = IORESOURCE_IO, },
{ .name = vrc4171_card_name,
.start = CONFIGURATION1,
.end = CONFIGURATION1,
.flags = IORESOURCE_IO, },
};
static struct platform_device vrc4171_card_device = {
.name = vrc4171_card_name,
.id = 0,
.num_resources = 3,
.resource = vrc4171_card_resource,
};
static inline uint16_t vrc4171_get_irq_status(void)
{
return inw(INTERRUPT_STATUS);
}
static inline void vrc4171_set_multifunction_pin(vrc4171_slotb_t config)
{
uint16_t config1;
config1 = inw(CONFIGURATION1);
config1 &= ~SLOTB_CONFIG;
switch (config) {
case SLOTB_IS_NONE:
config1 |= SLOTB_NONE;
break;
case SLOTB_IS_PCCARD:
config1 |= SLOTB_PCCARD;
break;
case SLOTB_IS_CF:
config1 |= SLOTB_CF;
break;
case SLOTB_IS_FLASHROM:
config1 |= SLOTB_FLASHROM;
break;
default:
break;
}
outw(config1, CONFIGURATION1);
}
static inline uint8_t exca_read_byte(int slot, uint8_t index)
{
if (slot == CARD_SLOTB)
index += CARD_SLOTB_OFFSET;
outb(index, CARD_CONTROLLER_INDEX);
return inb(CARD_CONTROLLER_DATA);
}
static inline uint16_t exca_read_word(int slot, uint8_t index)
{
uint16_t data;
if (slot == CARD_SLOTB)
index += CARD_SLOTB_OFFSET;
outb(index++, CARD_CONTROLLER_INDEX);
data = inb(CARD_CONTROLLER_DATA);
outb(index, CARD_CONTROLLER_INDEX);
data |= ((uint16_t)inb(CARD_CONTROLLER_DATA)) << 8;
return data;
}
static inline uint8_t exca_write_byte(int slot, uint8_t index, uint8_t data)
{
if (slot == CARD_SLOTB)
index += CARD_SLOTB_OFFSET;
outb(index, CARD_CONTROLLER_INDEX);
outb(data, CARD_CONTROLLER_DATA);
return data;
}
static inline uint16_t exca_write_word(int slot, uint8_t index, uint16_t data)
{
if (slot == CARD_SLOTB)
index += CARD_SLOTB_OFFSET;
outb(index++, CARD_CONTROLLER_INDEX);
outb(data, CARD_CONTROLLER_DATA);
outb(index, CARD_CONTROLLER_INDEX);
outb((uint8_t)(data >> 8), CARD_CONTROLLER_DATA);
return data;
}
static inline int search_nonuse_irq(void)
{
int i;
for (i = 0; i < 16; i++) {
if (vrc4171_irq_mask & (1 << i)) {
vrc4171_irq_mask &= ~(1 << i);
return i;
}
}
return -1;
}
static int pccard_init(struct pcmcia_socket *sock)
{
vrc4171_socket_t *socket;
unsigned int slot;
sock->features |= SS_CAP_PCCARD | SS_CAP_PAGE_REGS;
sock->irq_mask = 0;
sock->map_size = 0x1000;
sock->pci_irq = vrc4171_irq;
slot = sock->sock;
socket = &vrc4171_sockets[slot];
socket->csc_irq = search_nonuse_irq();
socket->io_irq = search_nonuse_irq();
return 0;
}
static int pccard_get_status(struct pcmcia_socket *sock, u_int *value)
{
unsigned int slot;
uint8_t status, sense;
u_int val = 0;
if (sock == NULL || sock->sock >= CARD_MAX_SLOTS || value == NULL)
return -EINVAL;
slot = sock->sock;
status = exca_read_byte(slot, I365_STATUS);
if (exca_read_byte(slot, I365_INTCTL) & I365_PC_IOCARD) {
if (status & I365_CS_STSCHG)
val |= SS_STSCHG;
} else {
if (!(status & I365_CS_BVD1))
val |= SS_BATDEAD;
else if ((status & (I365_CS_BVD1 | I365_CS_BVD2)) == I365_CS_BVD1)
val |= SS_BATWARN;
}
if ((status & I365_CS_DETECT) == I365_CS_DETECT)
val |= SS_DETECT;
if (status & I365_CS_WRPROT)
val |= SS_WRPROT;
if (status & I365_CS_READY)
val |= SS_READY;
if (status & I365_CS_POWERON)
val |= SS_POWERON;
sense = exca_read_byte(slot, CARD_VOLTAGE_SENSE);
switch (sense) {
case VCC_3VORXV_CAPABLE:
val |= SS_3VCARD | SS_XVCARD;
break;
case VCC_XV_ONLY:
val |= SS_XVCARD;
break;
case VCC_3V_CAPABLE:
val |= SS_3VCARD;
break;
default:
/* 5V only */
break;
}
*value = val;
return 0;
}
static inline uint8_t set_Vcc_value(u_char Vcc)
{
switch (Vcc) {
case 33:
return VCC_3V;
case 50:
return VCC_5V;
}
/* Small voltage is chosen for safety. */
return VCC_3V;
}
static int pccard_set_socket(struct pcmcia_socket *sock, socket_state_t *state)
{
vrc4171_socket_t *socket;
unsigned int slot;
uint8_t voltage, power, control, cscint;
if (sock == NULL || sock->sock >= CARD_MAX_SLOTS ||
(state->Vpp != state->Vcc && state->Vpp != 0) ||
(state->Vcc != 50 && state->Vcc != 33 && state->Vcc != 0))
return -EINVAL;
slot = sock->sock;
socket = &vrc4171_sockets[slot];
spin_lock_irq(&socket->lock);
voltage = set_Vcc_value(state->Vcc);
exca_write_byte(slot, CARD_VOLTAGE_SELECT, voltage);
power = POWER_ENABLE;
if (state->Vpp == state->Vcc)
power |= VPP_GET_VCC;
if (state->flags & SS_OUTPUT_ENA)
power |= I365_PWR_OUT;
exca_write_byte(slot, I365_POWER, power);
control = 0;
if (state->io_irq != 0)
control |= socket->io_irq;
if (state->flags & SS_IOCARD)
control |= I365_PC_IOCARD;
if (state->flags & SS_RESET)
control &= ~I365_PC_RESET;
else
control |= I365_PC_RESET;
exca_write_byte(slot, I365_INTCTL, control);
cscint = 0;
exca_write_byte(slot, I365_CSCINT, cscint);
exca_read_byte(slot, I365_CSC); /* clear CardStatus change */
if (state->csc_mask != 0)
cscint |= socket->csc_irq << 8;
if (state->flags & SS_IOCARD) {
if (state->csc_mask & SS_STSCHG)
cscint |= I365_CSC_STSCHG;
} else {
if (state->csc_mask & SS_BATDEAD)
cscint |= I365_CSC_BVD1;
if (state->csc_mask & SS_BATWARN)
cscint |= I365_CSC_BVD2;
}
if (state->csc_mask & SS_READY)
cscint |= I365_CSC_READY;
if (state->csc_mask & SS_DETECT)
cscint |= I365_CSC_DETECT;
exca_write_byte(slot, I365_CSCINT, cscint);
spin_unlock_irq(&socket->lock);
return 0;
}
static int pccard_set_io_map(struct pcmcia_socket *sock, struct pccard_io_map *io)
{
unsigned int slot;
uint8_t ioctl, addrwin;
u_char map;
if (sock == NULL || sock->sock >= CARD_MAX_SLOTS ||
io == NULL || io->map >= IO_MAX_MAPS ||
io->start > 0xffff || io->stop > 0xffff || io->start > io->stop)
return -EINVAL;
slot = sock->sock;
map = io->map;
addrwin = exca_read_byte(slot, I365_ADDRWIN);
if (addrwin & I365_ENA_IO(map)) {
addrwin &= ~I365_ENA_IO(map);
exca_write_byte(slot, I365_ADDRWIN, addrwin);
}
exca_write_word(slot, I365_IO(map)+I365_W_START, io->start);
exca_write_word(slot, I365_IO(map)+I365_W_STOP, io->stop);
ioctl = 0;
if (io->speed > 0)
ioctl |= I365_IOCTL_WAIT(map);
if (io->flags & MAP_16BIT)
ioctl |= I365_IOCTL_16BIT(map);
if (io->flags & MAP_AUTOSZ)
ioctl |= I365_IOCTL_IOCS16(map);
if (io->flags & MAP_0WS)
ioctl |= I365_IOCTL_0WS(map);
exca_write_byte(slot, I365_IOCTL, ioctl);
if (io->flags & MAP_ACTIVE) {
addrwin |= I365_ENA_IO(map);
exca_write_byte(slot, I365_ADDRWIN, addrwin);
}
return 0;
}
static int pccard_set_mem_map(struct pcmcia_socket *sock, struct pccard_mem_map *mem)
{
unsigned int slot;
uint16_t start, stop, offset;
uint8_t addrwin;
u_char map;
if (sock == NULL || sock->sock >= CARD_MAX_SLOTS ||
mem == NULL || mem->map >= MEM_MAX_MAPS ||
mem->res->start < CARD_MEM_START || mem->res->start > CARD_MEM_END ||
mem->res->end < CARD_MEM_START || mem->res->end > CARD_MEM_END ||
mem->res->start > mem->res->end ||
mem->card_start > CARD_MAX_MEM_OFFSET ||
mem->speed > CARD_MAX_MEM_SPEED)
return -EINVAL;
slot = sock->sock;
map = mem->map;
addrwin = exca_read_byte(slot, I365_ADDRWIN);
if (addrwin & I365_ENA_MEM(map)) {
addrwin &= ~I365_ENA_MEM(map);
exca_write_byte(slot, I365_ADDRWIN, addrwin);
}
start = (mem->res->start >> 12) & 0x3fff;
if (mem->flags & MAP_16BIT)
start |= I365_MEM_16BIT;
exca_write_word(slot, I365_MEM(map)+I365_W_START, start);
stop = (mem->res->end >> 12) & 0x3fff;
switch (mem->speed) {
case 0:
break;
case 1:
stop |= I365_MEM_WS0;
break;
case 2:
stop |= I365_MEM_WS1;
break;
default:
stop |= I365_MEM_WS0 | I365_MEM_WS1;
break;
}
exca_write_word(slot, I365_MEM(map)+I365_W_STOP, stop);
offset = (mem->card_start >> 12) & 0x3fff;
if (mem->flags & MAP_ATTRIB)
offset |= I365_MEM_REG;
if (mem->flags & MAP_WRPROT)
offset |= I365_MEM_WRPROT;
exca_write_word(slot, I365_MEM(map)+I365_W_OFF, offset);
if (mem->flags & MAP_ACTIVE) {
addrwin |= I365_ENA_MEM(map);
exca_write_byte(slot, I365_ADDRWIN, addrwin);
}
return 0;
}
static struct pccard_operations vrc4171_pccard_operations = {
.init = pccard_init,
.get_status = pccard_get_status,
.set_socket = pccard_set_socket,
.set_io_map = pccard_set_io_map,
.set_mem_map = pccard_set_mem_map,
};
static inline unsigned int get_events(int slot)
{
unsigned int events = 0;
uint8_t status, csc;
status = exca_read_byte(slot, I365_STATUS);
csc = exca_read_byte(slot, I365_CSC);
if (exca_read_byte(slot, I365_INTCTL) & I365_PC_IOCARD) {
if ((csc & I365_CSC_STSCHG) && (status & I365_CS_STSCHG))
events |= SS_STSCHG;
} else {
if (csc & (I365_CSC_BVD1 | I365_CSC_BVD2)) {
if (!(status & I365_CS_BVD1))
events |= SS_BATDEAD;
else if ((status & (I365_CS_BVD1 | I365_CS_BVD2)) == I365_CS_BVD1)
events |= SS_BATWARN;
}
}
if ((csc & I365_CSC_READY) && (status & I365_CS_READY))
events |= SS_READY;
if ((csc & I365_CSC_DETECT) && ((status & I365_CS_DETECT) == I365_CS_DETECT))
events |= SS_DETECT;
return events;
}
static irqreturn_t pccard_interrupt(int irq, void *dev_id)
{
vrc4171_socket_t *socket;
unsigned int events;
irqreturn_t retval = IRQ_NONE;
uint16_t status;
status = vrc4171_get_irq_status();
if (status & IRQ_A) {
socket = &vrc4171_sockets[CARD_SLOTA];
if (socket->slot == SLOT_INITIALIZED) {
if (status & (1 << socket->csc_irq)) {
events = get_events(CARD_SLOTA);
if (events != 0) {
pcmcia_parse_events(&socket->pcmcia_socket, events);
retval = IRQ_HANDLED;
}
}
}
}
if (status & IRQ_B) {
socket = &vrc4171_sockets[CARD_SLOTB];
if (socket->slot == SLOT_INITIALIZED) {
if (status & (1 << socket->csc_irq)) {
events = get_events(CARD_SLOTB);
if (events != 0) {
pcmcia_parse_events(&socket->pcmcia_socket, events);
retval = IRQ_HANDLED;
}
}
}
}
return retval;
}
static inline void reserve_using_irq(int slot)
{
unsigned int irq;
irq = exca_read_byte(slot, I365_INTCTL);
irq &= 0x0f;
vrc4171_irq_mask &= ~(1 << irq);
irq = exca_read_byte(slot, I365_CSCINT);
irq = (irq & 0xf0) >> 4;
vrc4171_irq_mask &= ~(1 << irq);
}
static int __devinit vrc4171_add_sockets(void)
{
vrc4171_socket_t *socket;
int slot, retval;
for (slot = 0; slot < CARD_MAX_SLOTS; slot++) {
if (slot == CARD_SLOTB && vrc4171_slotb == SLOTB_IS_NONE)
continue;
socket = &vrc4171_sockets[slot];
if (socket->slot != SLOT_PROBE) {
uint8_t addrwin;
switch (socket->slot) {
case SLOT_NOPROBE_MEM:
addrwin = exca_read_byte(slot, I365_ADDRWIN);
addrwin &= 0x1f;
exca_write_byte(slot, I365_ADDRWIN, addrwin);
break;
case SLOT_NOPROBE_IO:
addrwin = exca_read_byte(slot, I365_ADDRWIN);
addrwin &= 0xc0;
exca_write_byte(slot, I365_ADDRWIN, addrwin);
break;
default:
break;
}
reserve_using_irq(slot);
continue;
}
sprintf(socket->name, "NEC VRC4171 Card Slot %1c", 'A' + slot);
socket->pcmcia_socket.dev.parent = &vrc4171_card_device.dev;
socket->pcmcia_socket.ops = &vrc4171_pccard_operations;
socket->pcmcia_socket.owner = THIS_MODULE;
retval = pcmcia_register_socket(&socket->pcmcia_socket);
if (retval < 0)
return retval;
exca_write_byte(slot, I365_ADDRWIN, 0);
exca_write_byte(slot, GLOBAL_CONTROL, 0);
socket->slot = SLOT_INITIALIZED;
}
return 0;
}
static void vrc4171_remove_sockets(void)
{
vrc4171_socket_t *socket;
int slot;
for (slot = 0; slot < CARD_MAX_SLOTS; slot++) {
if (slot == CARD_SLOTB && vrc4171_slotb == SLOTB_IS_NONE)
continue;
socket = &vrc4171_sockets[slot];
if (socket->slot == SLOT_INITIALIZED)
pcmcia_unregister_socket(&socket->pcmcia_socket);
socket->slot = SLOT_PROBE;
}
}
static int __devinit vrc4171_card_setup(char *options)
{
if (options == NULL || *options == '\0')
return 1;
if (strncmp(options, "irq:", 4) == 0) {
int irq;
options += 4;
irq = simple_strtoul(options, &options, 0);
if (irq >= 0 && irq < nr_irqs)
vrc4171_irq = irq;
if (*options != ',')
return 1;
options++;
}
if (strncmp(options, "slota:", 6) == 0) {
options += 6;
if (*options != '\0') {
if (strncmp(options, "memnoprobe", 10) == 0) {
vrc4171_sockets[CARD_SLOTA].slot = SLOT_NOPROBE_MEM;
options += 10;
} else if (strncmp(options, "ionoprobe", 9) == 0) {
vrc4171_sockets[CARD_SLOTA].slot = SLOT_NOPROBE_IO;
options += 9;
} else if ( strncmp(options, "noprobe", 7) == 0) {
vrc4171_sockets[CARD_SLOTA].slot = SLOT_NOPROBE_ALL;
options += 7;
}
if (*options != ',')
return 1;
options++;
} else
return 1;
}
if (strncmp(options, "slotb:", 6) == 0) {
options += 6;
if (*options != '\0') {
if (strncmp(options, "pccard", 6) == 0) {
vrc4171_slotb = SLOTB_IS_PCCARD;
options += 6;
} else if (strncmp(options, "cf", 2) == 0) {
vrc4171_slotb = SLOTB_IS_CF;
options += 2;
} else if (strncmp(options, "flashrom", 8) == 0) {
vrc4171_slotb = SLOTB_IS_FLASHROM;
options += 8;
} else if (strncmp(options, "none", 4) == 0) {
vrc4171_slotb = SLOTB_IS_NONE;
options += 4;
}
if (*options != ',')
return 1;
options++;
if (strncmp(options, "memnoprobe", 10) == 0)
vrc4171_sockets[CARD_SLOTB].slot = SLOT_NOPROBE_MEM;
if (strncmp(options, "ionoprobe", 9) == 0)
vrc4171_sockets[CARD_SLOTB].slot = SLOT_NOPROBE_IO;
if (strncmp(options, "noprobe", 7) == 0)
vrc4171_sockets[CARD_SLOTB].slot = SLOT_NOPROBE_ALL;
}
}
return 1;
}
__setup("vrc4171_card=", vrc4171_card_setup);
static struct platform_driver vrc4171_card_driver = {
.driver = {
.name = vrc4171_card_name,
.owner = THIS_MODULE,
},
};
static int __devinit vrc4171_card_init(void)
{
int retval;
retval = platform_driver_register(&vrc4171_card_driver);
if (retval < 0)
return retval;
retval = platform_device_register(&vrc4171_card_device);
if (retval < 0) {
platform_driver_unregister(&vrc4171_card_driver);
return retval;
}
vrc4171_set_multifunction_pin(vrc4171_slotb);
retval = vrc4171_add_sockets();
if (retval == 0)
retval = request_irq(vrc4171_irq, pccard_interrupt, IRQF_SHARED,
vrc4171_card_name, vrc4171_sockets);
if (retval < 0) {
vrc4171_remove_sockets();
platform_device_unregister(&vrc4171_card_device);
platform_driver_unregister(&vrc4171_card_driver);
return retval;
}
printk(KERN_INFO "%s, connected to IRQ %d\n",
vrc4171_card_driver.driver.name, vrc4171_irq);
return 0;
}
static void __devexit vrc4171_card_exit(void)
{
free_irq(vrc4171_irq, vrc4171_sockets);
vrc4171_remove_sockets();
platform_device_unregister(&vrc4171_card_device);
platform_driver_unregister(&vrc4171_card_driver);
}
module_init(vrc4171_card_init);
module_exit(vrc4171_card_exit);
| gpl-2.0 |
paulocastro31/android_kernel_motorola_msm8226 | arch/mips/ath79/dev-gpio-buttons.c | 7549 | 1328 | /*
* Atheros AR71XX/AR724X/AR913X GPIO button support
*
* Copyright (C) 2008-2010 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2008 Imre Kaloz <kaloz@openwrt.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "linux/init.h"
#include "linux/slab.h"
#include <linux/platform_device.h>
#include "dev-gpio-buttons.h"
void __init ath79_register_gpio_keys_polled(int id,
unsigned poll_interval,
unsigned nbuttons,
struct gpio_keys_button *buttons)
{
struct platform_device *pdev;
struct gpio_keys_platform_data pdata;
struct gpio_keys_button *p;
int err;
p = kmalloc(nbuttons * sizeof(*p), GFP_KERNEL);
if (!p)
return;
memcpy(p, buttons, nbuttons * sizeof(*p));
pdev = platform_device_alloc("gpio-keys-polled", id);
if (!pdev)
goto err_free_buttons;
memset(&pdata, 0, sizeof(pdata));
pdata.poll_interval = poll_interval;
pdata.nbuttons = nbuttons;
pdata.buttons = p;
err = platform_device_add_data(pdev, &pdata, sizeof(pdata));
if (err)
goto err_put_pdev;
err = platform_device_add(pdev);
if (err)
goto err_put_pdev;
return;
err_put_pdev:
platform_device_put(pdev);
err_free_buttons:
kfree(p);
}
| gpl-2.0 |
Dm47021/Holo-a200 | arch/mips/alchemy/devboards/pm.c | 7805 | 6120 | /*
* Alchemy Development Board example suspend userspace interface.
*
* (c) 2008 Manuel Lauss <mano@roarinelk.homelinux.net>
*/
#include <linux/init.h>
#include <linux/kobject.h>
#include <linux/suspend.h>
#include <linux/sysfs.h>
#include <asm/mach-au1x00/au1000.h>
#include <asm/mach-au1x00/gpio.h>
#include <asm/mach-db1x00/bcsr.h>
/*
* Generic suspend userspace interface for Alchemy development boards.
* This code exports a few sysfs nodes under /sys/power/db1x/ which
* can be used by userspace to en/disable all au1x-provided wakeup
* sources and configure the timeout after which the the TOYMATCH2 irq
* is to trigger a wakeup.
*/
static unsigned long db1x_pm_sleep_secs;
static unsigned long db1x_pm_wakemsk;
static unsigned long db1x_pm_last_wakesrc;
static int db1x_pm_enter(suspend_state_t state)
{
unsigned short bcsrs[16];
int i, j, hasint;
/* save CPLD regs */
hasint = bcsr_read(BCSR_WHOAMI);
hasint = BCSR_WHOAMI_BOARD(hasint) >= BCSR_WHOAMI_DB1200;
j = (hasint) ? BCSR_MASKSET : BCSR_SYSTEM;
for (i = BCSR_STATUS; i <= j; i++)
bcsrs[i] = bcsr_read(i);
/* shut off hexleds */
bcsr_write(BCSR_HEXCLEAR, 3);
/* enable GPIO based wakeup */
alchemy_gpio1_input_enable();
/* clear and setup wake cause and source */
au_writel(0, SYS_WAKEMSK);
au_sync();
au_writel(0, SYS_WAKESRC);
au_sync();
au_writel(db1x_pm_wakemsk, SYS_WAKEMSK);
au_sync();
/* setup 1Hz-timer-based wakeup: wait for reg access */
while (au_readl(SYS_COUNTER_CNTRL) & SYS_CNTRL_M20)
asm volatile ("nop");
au_writel(au_readl(SYS_TOYREAD) + db1x_pm_sleep_secs, SYS_TOYMATCH2);
au_sync();
/* wait for value to really hit the register */
while (au_readl(SYS_COUNTER_CNTRL) & SYS_CNTRL_M20)
asm volatile ("nop");
/* ...and now the sandman can come! */
au_sleep();
/* restore CPLD regs */
for (i = BCSR_STATUS; i <= BCSR_SYSTEM; i++)
bcsr_write(i, bcsrs[i]);
/* restore CPLD int registers */
if (hasint) {
bcsr_write(BCSR_INTCLR, 0xffff);
bcsr_write(BCSR_MASKCLR, 0xffff);
bcsr_write(BCSR_INTSTAT, 0xffff);
bcsr_write(BCSR_INTSET, bcsrs[BCSR_INTSET]);
bcsr_write(BCSR_MASKSET, bcsrs[BCSR_MASKSET]);
}
/* light up hexleds */
bcsr_write(BCSR_HEXCLEAR, 0);
return 0;
}
static int db1x_pm_begin(suspend_state_t state)
{
if (!db1x_pm_wakemsk) {
printk(KERN_ERR "db1x: no wakeup source activated!\n");
return -EINVAL;
}
return 0;
}
static void db1x_pm_end(void)
{
/* read and store wakeup source, the clear the register. To
* be able to clear it, WAKEMSK must be cleared first.
*/
db1x_pm_last_wakesrc = au_readl(SYS_WAKESRC);
au_writel(0, SYS_WAKEMSK);
au_writel(0, SYS_WAKESRC);
au_sync();
}
static const struct platform_suspend_ops db1x_pm_ops = {
.valid = suspend_valid_only_mem,
.begin = db1x_pm_begin,
.enter = db1x_pm_enter,
.end = db1x_pm_end,
};
#define ATTRCMP(x) (0 == strcmp(attr->attr.name, #x))
static ssize_t db1x_pmattr_show(struct kobject *kobj,
struct kobj_attribute *attr,
char *buf)
{
int idx;
if (ATTRCMP(timer_timeout))
return sprintf(buf, "%lu\n", db1x_pm_sleep_secs);
else if (ATTRCMP(timer))
return sprintf(buf, "%u\n",
!!(db1x_pm_wakemsk & SYS_WAKEMSK_M2));
else if (ATTRCMP(wakesrc))
return sprintf(buf, "%lu\n", db1x_pm_last_wakesrc);
else if (ATTRCMP(gpio0) || ATTRCMP(gpio1) || ATTRCMP(gpio2) ||
ATTRCMP(gpio3) || ATTRCMP(gpio4) || ATTRCMP(gpio5) ||
ATTRCMP(gpio6) || ATTRCMP(gpio7)) {
idx = (attr->attr.name)[4] - '0';
return sprintf(buf, "%d\n",
!!(db1x_pm_wakemsk & SYS_WAKEMSK_GPIO(idx)));
} else if (ATTRCMP(wakemsk)) {
return sprintf(buf, "%08lx\n", db1x_pm_wakemsk);
}
return -ENOENT;
}
static ssize_t db1x_pmattr_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *instr,
size_t bytes)
{
unsigned long l;
int tmp;
if (ATTRCMP(timer_timeout)) {
tmp = strict_strtoul(instr, 0, &l);
if (tmp)
return tmp;
db1x_pm_sleep_secs = l;
} else if (ATTRCMP(timer)) {
if (instr[0] != '0')
db1x_pm_wakemsk |= SYS_WAKEMSK_M2;
else
db1x_pm_wakemsk &= ~SYS_WAKEMSK_M2;
} else if (ATTRCMP(gpio0) || ATTRCMP(gpio1) || ATTRCMP(gpio2) ||
ATTRCMP(gpio3) || ATTRCMP(gpio4) || ATTRCMP(gpio5) ||
ATTRCMP(gpio6) || ATTRCMP(gpio7)) {
tmp = (attr->attr.name)[4] - '0';
if (instr[0] != '0') {
db1x_pm_wakemsk |= SYS_WAKEMSK_GPIO(tmp);
} else {
db1x_pm_wakemsk &= ~SYS_WAKEMSK_GPIO(tmp);
}
} else if (ATTRCMP(wakemsk)) {
tmp = strict_strtoul(instr, 0, &l);
if (tmp)
return tmp;
db1x_pm_wakemsk = l & 0x0000003f;
} else
bytes = -ENOENT;
return bytes;
}
#define ATTR(x) \
static struct kobj_attribute x##_attribute = \
__ATTR(x, 0664, db1x_pmattr_show, \
db1x_pmattr_store);
ATTR(gpio0) /* GPIO-based wakeup enable */
ATTR(gpio1)
ATTR(gpio2)
ATTR(gpio3)
ATTR(gpio4)
ATTR(gpio5)
ATTR(gpio6)
ATTR(gpio7)
ATTR(timer) /* TOYMATCH2-based wakeup enable */
ATTR(timer_timeout) /* timer-based wakeup timeout value, in seconds */
ATTR(wakesrc) /* contents of SYS_WAKESRC after last wakeup */
ATTR(wakemsk) /* direct access to SYS_WAKEMSK */
#define ATTR_LIST(x) & x ## _attribute.attr
static struct attribute *db1x_pmattrs[] = {
ATTR_LIST(gpio0),
ATTR_LIST(gpio1),
ATTR_LIST(gpio2),
ATTR_LIST(gpio3),
ATTR_LIST(gpio4),
ATTR_LIST(gpio5),
ATTR_LIST(gpio6),
ATTR_LIST(gpio7),
ATTR_LIST(timer),
ATTR_LIST(timer_timeout),
ATTR_LIST(wakesrc),
ATTR_LIST(wakemsk),
NULL, /* terminator */
};
static struct attribute_group db1x_pmattr_group = {
.name = "db1x",
.attrs = db1x_pmattrs,
};
/*
* Initialize suspend interface
*/
static int __init pm_init(void)
{
/* init TOY to tick at 1Hz if not already done. No need to wait
* for confirmation since there's plenty of time from here to
* the next suspend cycle.
*/
if (au_readl(SYS_TOYTRIM) != 32767) {
au_writel(32767, SYS_TOYTRIM);
au_sync();
}
db1x_pm_last_wakesrc = au_readl(SYS_WAKESRC);
au_writel(0, SYS_WAKESRC);
au_sync();
au_writel(0, SYS_WAKEMSK);
au_sync();
suspend_set_ops(&db1x_pm_ops);
return sysfs_create_group(power_kobj, &db1x_pmattr_group);
}
late_initcall(pm_init);
| gpl-2.0 |
Radium-Devices/Radium_ghost | drivers/video/backlight/ili9320.c | 9085 | 7152 | /* drivers/video/backlight/ili9320.c
*
* ILI9320 LCD controller driver core.
*
* Copyright 2007 Simtec Electronics
* http://armlinux.simtec.co.uk/
* Ben Dooks <ben@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/lcd.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/spi/spi.h>
#include <video/ili9320.h>
#include "ili9320.h"
static inline int ili9320_write_spi(struct ili9320 *ili,
unsigned int reg,
unsigned int value)
{
struct ili9320_spi *spi = &ili->access.spi;
unsigned char *addr = spi->buffer_addr;
unsigned char *data = spi->buffer_data;
/* spi message consits of:
* first byte: ID and operation
*/
addr[0] = spi->id | ILI9320_SPI_INDEX | ILI9320_SPI_WRITE;
addr[1] = reg >> 8;
addr[2] = reg;
/* second message is the data to transfer */
data[0] = spi->id | ILI9320_SPI_DATA | ILI9320_SPI_WRITE;
data[1] = value >> 8;
data[2] = value;
return spi_sync(spi->dev, &spi->message);
}
int ili9320_write(struct ili9320 *ili, unsigned int reg, unsigned int value)
{
dev_dbg(ili->dev, "write: reg=%02x, val=%04x\n", reg, value);
return ili->write(ili, reg, value);
}
EXPORT_SYMBOL_GPL(ili9320_write);
int ili9320_write_regs(struct ili9320 *ili,
struct ili9320_reg *values,
int nr_values)
{
int index;
int ret;
for (index = 0; index < nr_values; index++, values++) {
ret = ili9320_write(ili, values->address, values->value);
if (ret != 0)
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(ili9320_write_regs);
static void ili9320_reset(struct ili9320 *lcd)
{
struct ili9320_platdata *cfg = lcd->platdata;
cfg->reset(1);
mdelay(50);
cfg->reset(0);
mdelay(50);
cfg->reset(1);
mdelay(100);
}
static inline int ili9320_init_chip(struct ili9320 *lcd)
{
int ret;
ili9320_reset(lcd);
ret = lcd->client->init(lcd, lcd->platdata);
if (ret != 0) {
dev_err(lcd->dev, "failed to initialise display\n");
return ret;
}
lcd->initialised = 1;
return 0;
}
static inline int ili9320_power_on(struct ili9320 *lcd)
{
if (!lcd->initialised)
ili9320_init_chip(lcd);
lcd->display1 |= (ILI9320_DISPLAY1_D(3) | ILI9320_DISPLAY1_BASEE);
ili9320_write(lcd, ILI9320_DISPLAY1, lcd->display1);
return 0;
}
static inline int ili9320_power_off(struct ili9320 *lcd)
{
lcd->display1 &= ~(ILI9320_DISPLAY1_D(3) | ILI9320_DISPLAY1_BASEE);
ili9320_write(lcd, ILI9320_DISPLAY1, lcd->display1);
return 0;
}
#define POWER_IS_ON(pwr) ((pwr) <= FB_BLANK_NORMAL)
static int ili9320_power(struct ili9320 *lcd, int power)
{
int ret = 0;
dev_dbg(lcd->dev, "power %d => %d\n", lcd->power, power);
if (POWER_IS_ON(power) && !POWER_IS_ON(lcd->power))
ret = ili9320_power_on(lcd);
else if (!POWER_IS_ON(power) && POWER_IS_ON(lcd->power))
ret = ili9320_power_off(lcd);
if (ret == 0)
lcd->power = power;
else
dev_warn(lcd->dev, "failed to set power mode %d\n", power);
return ret;
}
static inline struct ili9320 *to_our_lcd(struct lcd_device *lcd)
{
return lcd_get_data(lcd);
}
static int ili9320_set_power(struct lcd_device *ld, int power)
{
struct ili9320 *lcd = to_our_lcd(ld);
return ili9320_power(lcd, power);
}
static int ili9320_get_power(struct lcd_device *ld)
{
struct ili9320 *lcd = to_our_lcd(ld);
return lcd->power;
}
static struct lcd_ops ili9320_ops = {
.get_power = ili9320_get_power,
.set_power = ili9320_set_power,
};
static void __devinit ili9320_setup_spi(struct ili9320 *ili,
struct spi_device *dev)
{
struct ili9320_spi *spi = &ili->access.spi;
ili->write = ili9320_write_spi;
spi->dev = dev;
/* fill the two messages we are going to use to send the data
* with, the first the address followed by the data. The datasheet
* says they should be done as two distinct cycles of the SPI CS line.
*/
spi->xfer[0].tx_buf = spi->buffer_addr;
spi->xfer[1].tx_buf = spi->buffer_data;
spi->xfer[0].len = 3;
spi->xfer[1].len = 3;
spi->xfer[0].bits_per_word = 8;
spi->xfer[1].bits_per_word = 8;
spi->xfer[0].cs_change = 1;
spi_message_init(&spi->message);
spi_message_add_tail(&spi->xfer[0], &spi->message);
spi_message_add_tail(&spi->xfer[1], &spi->message);
}
int __devinit ili9320_probe_spi(struct spi_device *spi,
struct ili9320_client *client)
{
struct ili9320_platdata *cfg = spi->dev.platform_data;
struct device *dev = &spi->dev;
struct ili9320 *ili;
struct lcd_device *lcd;
int ret = 0;
/* verify we where given some information */
if (cfg == NULL) {
dev_err(dev, "no platform data supplied\n");
return -EINVAL;
}
if (cfg->hsize <= 0 || cfg->vsize <= 0 || cfg->reset == NULL) {
dev_err(dev, "invalid platform data supplied\n");
return -EINVAL;
}
/* allocate and initialse our state */
ili = kzalloc(sizeof(struct ili9320), GFP_KERNEL);
if (ili == NULL) {
dev_err(dev, "no memory for device\n");
return -ENOMEM;
}
ili->access.spi.id = ILI9320_SPI_IDCODE | ILI9320_SPI_ID(1);
ili->dev = dev;
ili->client = client;
ili->power = FB_BLANK_POWERDOWN;
ili->platdata = cfg;
dev_set_drvdata(&spi->dev, ili);
ili9320_setup_spi(ili, spi);
lcd = lcd_device_register("ili9320", dev, ili, &ili9320_ops);
if (IS_ERR(lcd)) {
dev_err(dev, "failed to register lcd device\n");
ret = PTR_ERR(lcd);
goto err_free;
}
ili->lcd = lcd;
dev_info(dev, "initialising %s\n", client->name);
ret = ili9320_power(ili, FB_BLANK_UNBLANK);
if (ret != 0) {
dev_err(dev, "failed to set lcd power state\n");
goto err_unregister;
}
return 0;
err_unregister:
lcd_device_unregister(lcd);
err_free:
kfree(ili);
return ret;
}
EXPORT_SYMBOL_GPL(ili9320_probe_spi);
int __devexit ili9320_remove(struct ili9320 *ili)
{
ili9320_power(ili, FB_BLANK_POWERDOWN);
lcd_device_unregister(ili->lcd);
kfree(ili);
return 0;
}
EXPORT_SYMBOL_GPL(ili9320_remove);
#ifdef CONFIG_PM
int ili9320_suspend(struct ili9320 *lcd, pm_message_t state)
{
int ret;
dev_dbg(lcd->dev, "%s: event %d\n", __func__, state.event);
if (state.event == PM_EVENT_SUSPEND) {
ret = ili9320_power(lcd, FB_BLANK_POWERDOWN);
if (lcd->platdata->suspend == ILI9320_SUSPEND_DEEP) {
ili9320_write(lcd, ILI9320_POWER1, lcd->power1 |
ILI9320_POWER1_SLP |
ILI9320_POWER1_DSTB);
lcd->initialised = 0;
}
return ret;
}
return 0;
}
EXPORT_SYMBOL_GPL(ili9320_suspend);
int ili9320_resume(struct ili9320 *lcd)
{
dev_info(lcd->dev, "resuming from power state %d\n", lcd->power);
if (lcd->platdata->suspend == ILI9320_SUSPEND_DEEP) {
ili9320_write(lcd, ILI9320_POWER1, 0x00);
}
return ili9320_power(lcd, FB_BLANK_UNBLANK);
}
EXPORT_SYMBOL_GPL(ili9320_resume);
#endif
/* Power down all displays on reboot, poweroff or halt */
void ili9320_shutdown(struct ili9320 *lcd)
{
ili9320_power(lcd, FB_BLANK_POWERDOWN);
}
EXPORT_SYMBOL_GPL(ili9320_shutdown);
MODULE_AUTHOR("Ben Dooks <ben-linux@fluff.org>");
MODULE_DESCRIPTION("ILI9320 LCD Driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
dinh-linux/linux-socfpga | arch/powerpc/platforms/cell/cbe_regs.c | 9085 | 6678 | /*
* cbe_regs.c
*
* Accessor routines for the various MMIO register blocks of the CBE
*
* (c) 2006 Benjamin Herrenschmidt <benh@kernel.crashing.org>, IBM Corp.
*/
#include <linux/percpu.h>
#include <linux/types.h>
#include <linux/export.h>
#include <linux/of_device.h>
#include <linux/of_platform.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include <asm/prom.h>
#include <asm/ptrace.h>
#include <asm/cell-regs.h>
/*
* Current implementation uses "cpu" nodes. We build our own mapping
* array of cpu numbers to cpu nodes locally for now to allow interrupt
* time code to have a fast path rather than call of_get_cpu_node(). If
* we implement cpu hotplug, we'll have to install an appropriate norifier
* in order to release references to the cpu going away
*/
static struct cbe_regs_map
{
struct device_node *cpu_node;
struct device_node *be_node;
struct cbe_pmd_regs __iomem *pmd_regs;
struct cbe_iic_regs __iomem *iic_regs;
struct cbe_mic_tm_regs __iomem *mic_tm_regs;
struct cbe_pmd_shadow_regs pmd_shadow_regs;
} cbe_regs_maps[MAX_CBE];
static int cbe_regs_map_count;
static struct cbe_thread_map
{
struct device_node *cpu_node;
struct device_node *be_node;
struct cbe_regs_map *regs;
unsigned int thread_id;
unsigned int cbe_id;
} cbe_thread_map[NR_CPUS];
static cpumask_t cbe_local_mask[MAX_CBE] = { [0 ... MAX_CBE-1] = {CPU_BITS_NONE} };
static cpumask_t cbe_first_online_cpu = { CPU_BITS_NONE };
static struct cbe_regs_map *cbe_find_map(struct device_node *np)
{
int i;
struct device_node *tmp_np;
if (strcasecmp(np->type, "spe")) {
for (i = 0; i < cbe_regs_map_count; i++)
if (cbe_regs_maps[i].cpu_node == np ||
cbe_regs_maps[i].be_node == np)
return &cbe_regs_maps[i];
return NULL;
}
if (np->data)
return np->data;
/* walk up path until cpu or be node was found */
tmp_np = np;
do {
tmp_np = tmp_np->parent;
/* on a correct devicetree we wont get up to root */
BUG_ON(!tmp_np);
} while (strcasecmp(tmp_np->type, "cpu") &&
strcasecmp(tmp_np->type, "be"));
np->data = cbe_find_map(tmp_np);
return np->data;
}
struct cbe_pmd_regs __iomem *cbe_get_pmd_regs(struct device_node *np)
{
struct cbe_regs_map *map = cbe_find_map(np);
if (map == NULL)
return NULL;
return map->pmd_regs;
}
EXPORT_SYMBOL_GPL(cbe_get_pmd_regs);
struct cbe_pmd_regs __iomem *cbe_get_cpu_pmd_regs(int cpu)
{
struct cbe_regs_map *map = cbe_thread_map[cpu].regs;
if (map == NULL)
return NULL;
return map->pmd_regs;
}
EXPORT_SYMBOL_GPL(cbe_get_cpu_pmd_regs);
struct cbe_pmd_shadow_regs *cbe_get_pmd_shadow_regs(struct device_node *np)
{
struct cbe_regs_map *map = cbe_find_map(np);
if (map == NULL)
return NULL;
return &map->pmd_shadow_regs;
}
struct cbe_pmd_shadow_regs *cbe_get_cpu_pmd_shadow_regs(int cpu)
{
struct cbe_regs_map *map = cbe_thread_map[cpu].regs;
if (map == NULL)
return NULL;
return &map->pmd_shadow_regs;
}
struct cbe_iic_regs __iomem *cbe_get_iic_regs(struct device_node *np)
{
struct cbe_regs_map *map = cbe_find_map(np);
if (map == NULL)
return NULL;
return map->iic_regs;
}
struct cbe_iic_regs __iomem *cbe_get_cpu_iic_regs(int cpu)
{
struct cbe_regs_map *map = cbe_thread_map[cpu].regs;
if (map == NULL)
return NULL;
return map->iic_regs;
}
struct cbe_mic_tm_regs __iomem *cbe_get_mic_tm_regs(struct device_node *np)
{
struct cbe_regs_map *map = cbe_find_map(np);
if (map == NULL)
return NULL;
return map->mic_tm_regs;
}
struct cbe_mic_tm_regs __iomem *cbe_get_cpu_mic_tm_regs(int cpu)
{
struct cbe_regs_map *map = cbe_thread_map[cpu].regs;
if (map == NULL)
return NULL;
return map->mic_tm_regs;
}
EXPORT_SYMBOL_GPL(cbe_get_cpu_mic_tm_regs);
u32 cbe_get_hw_thread_id(int cpu)
{
return cbe_thread_map[cpu].thread_id;
}
EXPORT_SYMBOL_GPL(cbe_get_hw_thread_id);
u32 cbe_cpu_to_node(int cpu)
{
return cbe_thread_map[cpu].cbe_id;
}
EXPORT_SYMBOL_GPL(cbe_cpu_to_node);
u32 cbe_node_to_cpu(int node)
{
return cpumask_first(&cbe_local_mask[node]);
}
EXPORT_SYMBOL_GPL(cbe_node_to_cpu);
static struct device_node *cbe_get_be_node(int cpu_id)
{
struct device_node *np;
for_each_node_by_type (np, "be") {
int len,i;
const phandle *cpu_handle;
cpu_handle = of_get_property(np, "cpus", &len);
/*
* the CAB SLOF tree is non compliant, so we just assume
* there is only one node
*/
if (WARN_ON_ONCE(!cpu_handle))
return np;
for (i=0; i<len; i++)
if (of_find_node_by_phandle(cpu_handle[i]) == of_get_cpu_node(cpu_id, NULL))
return np;
}
return NULL;
}
void __init cbe_fill_regs_map(struct cbe_regs_map *map)
{
if(map->be_node) {
struct device_node *be, *np;
be = map->be_node;
for_each_node_by_type(np, "pervasive")
if (of_get_parent(np) == be)
map->pmd_regs = of_iomap(np, 0);
for_each_node_by_type(np, "CBEA-Internal-Interrupt-Controller")
if (of_get_parent(np) == be)
map->iic_regs = of_iomap(np, 2);
for_each_node_by_type(np, "mic-tm")
if (of_get_parent(np) == be)
map->mic_tm_regs = of_iomap(np, 0);
} else {
struct device_node *cpu;
/* That hack must die die die ! */
const struct address_prop {
unsigned long address;
unsigned int len;
} __attribute__((packed)) *prop;
cpu = map->cpu_node;
prop = of_get_property(cpu, "pervasive", NULL);
if (prop != NULL)
map->pmd_regs = ioremap(prop->address, prop->len);
prop = of_get_property(cpu, "iic", NULL);
if (prop != NULL)
map->iic_regs = ioremap(prop->address, prop->len);
prop = of_get_property(cpu, "mic-tm", NULL);
if (prop != NULL)
map->mic_tm_regs = ioremap(prop->address, prop->len);
}
}
void __init cbe_regs_init(void)
{
int i;
unsigned int thread_id;
struct device_node *cpu;
/* Build local fast map of CPUs */
for_each_possible_cpu(i) {
cbe_thread_map[i].cpu_node = of_get_cpu_node(i, &thread_id);
cbe_thread_map[i].be_node = cbe_get_be_node(i);
cbe_thread_map[i].thread_id = thread_id;
}
/* Find maps for each device tree CPU */
for_each_node_by_type(cpu, "cpu") {
struct cbe_regs_map *map;
unsigned int cbe_id;
cbe_id = cbe_regs_map_count++;
map = &cbe_regs_maps[cbe_id];
if (cbe_regs_map_count > MAX_CBE) {
printk(KERN_ERR "cbe_regs: More BE chips than supported"
"!\n");
cbe_regs_map_count--;
of_node_put(cpu);
return;
}
map->cpu_node = cpu;
for_each_possible_cpu(i) {
struct cbe_thread_map *thread = &cbe_thread_map[i];
if (thread->cpu_node == cpu) {
thread->regs = map;
thread->cbe_id = cbe_id;
map->be_node = thread->be_node;
cpumask_set_cpu(i, &cbe_local_mask[cbe_id]);
if(thread->thread_id == 0)
cpumask_set_cpu(i, &cbe_first_online_cpu);
}
}
cbe_fill_regs_map(map);
}
}
| gpl-2.0 |
AOSPA/android_kernel_samsung_tuna | arch/arm/mach-omap2/lpddr2_elpida_data.c | 126 | 2077 | /*
* LPDDR2 data as per JESD209-2
*
* Copyright (C) 2010 Texas Instruments, Inc.
*
* Aneesh V <aneesh@ti.com>
* Santosh Shilimkar <santosh.shilimkar@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <mach/emif.h>
#include <mach/lpddr2-elpida.h>
const struct lpddr2_timings lpddr2_elpida_timings_400_mhz = {
.max_freq = 400000000,
.RL = 6,
.tRPab = 21,
.tRCD = 18,
.tWR = 15,
.tRASmin = 42,
.tRRD = 10,
.tWTRx2 = 15,
.tXSR = 140,
.tXPx2 = 15,
.tRFCab = 130,
.tRTPx2 = 15,
.tCKE = 3,
.tCKESR = 15,
.tZQCS = 90,
.tZQCL = 360,
.tZQINIT = 1000,
.tDQSCKMAXx2 = 11,
.tRASmax = 70,
.tFAW = 50
};
const struct lpddr2_timings lpddr2_elpida_timings_333_mhz = {
.max_freq = 333000000,
.RL = 5,
.tRPab = 21,
.tRCD = 18,
.tWR = 15,
.tRASmin = 42,
.tRRD = 10,
.tWTRx2 = 15,
.tXSR = 140,
.tXPx2 = 15,
.tRFCab = 130,
.tRTPx2 = 15,
.tCKE = 3,
.tCKESR = 15,
.tZQCS = 90,
.tZQCL = 360,
.tZQINIT = 1000,
.tDQSCKMAXx2 = 11,
.tRASmax = 70,
.tFAW = 50
};
const struct lpddr2_timings lpddr2_elpida_timings_200_mhz = {
.max_freq = 200000000,
.RL = 3,
.tRPab = 21,
.tRCD = 18,
.tWR = 15,
.tRASmin = 42,
.tRRD = 10,
.tWTRx2 = 20,
.tXSR = 140,
.tXPx2 = 15,
.tRFCab = 130,
.tRTPx2 = 15,
.tCKE = 3,
.tCKESR = 15,
.tZQCS = 90,
.tZQCL = 360,
.tZQINIT = 1000,
.tDQSCKMAXx2 = 11,
.tRASmax = 70,
.tFAW = 50
};
const struct lpddr2_min_tck lpddr2_elpida_min_tck = {
.tRL = 3,
.tRP_AB = 3,
.tRCD = 3,
.tWR = 3,
.tRAS_MIN = 3,
.tRRD = 2,
.tWTR = 2,
.tXP = 2,
.tRTP = 2,
.tCKE = 3,
.tCKESR = 3,
.tFAW = 8
};
struct lpddr2_device_info lpddr2_elpida_2G_S4_dev = {
.device_timings = {
&lpddr2_elpida_timings_200_mhz,
&lpddr2_elpida_timings_333_mhz,
&lpddr2_elpida_timings_400_mhz
},
.min_tck = &lpddr2_elpida_min_tck,
.type = LPDDR2_TYPE_S4,
.density = LPDDR2_DENSITY_2Gb,
.io_width = LPDDR2_IO_WIDTH_32
};
| gpl-2.0 |
Alberto96/android_kernel_ulefone_k11ta_a | net/mac80211/mlme.c | 126 | 135134 | /*
* BSS client mode implementation
* Copyright 2003-2008, Jouni Malinen <j@w1.fi>
* Copyright 2004, Instant802 Networks, Inc.
* Copyright 2005, Devicescape Software, Inc.
* Copyright 2006-2007 Jiri Benc <jbenc@suse.cz>
* Copyright 2007, Michael Wu <flamingice@sourmilk.net>
* Copyright 2013-2014 Intel Mobile Communications GmbH
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/delay.h>
#include <linux/if_ether.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/etherdevice.h>
#include <linux/moduleparam.h>
#include <linux/rtnetlink.h>
#include <linux/pm_qos.h>
#include <linux/crc32.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <net/mac80211.h>
#include <asm/unaligned.h>
#include "ieee80211_i.h"
#include "driver-ops.h"
#include "rate.h"
#include "led.h"
#define IEEE80211_AUTH_TIMEOUT (HZ / 5)
#define IEEE80211_AUTH_TIMEOUT_LONG (HZ / 2)
#define IEEE80211_AUTH_TIMEOUT_SHORT (HZ / 10)
#define IEEE80211_AUTH_MAX_TRIES 3
#define IEEE80211_AUTH_WAIT_ASSOC (HZ * 5)
#define IEEE80211_ASSOC_TIMEOUT (HZ / 5)
#define IEEE80211_ASSOC_TIMEOUT_LONG (HZ / 2)
#define IEEE80211_ASSOC_TIMEOUT_SHORT (HZ / 10)
#define IEEE80211_ASSOC_MAX_TRIES 3
static int max_nullfunc_tries = 2;
module_param(max_nullfunc_tries, int, 0644);
MODULE_PARM_DESC(max_nullfunc_tries,
"Maximum nullfunc tx tries before disconnecting (reason 4).");
static int max_probe_tries = 5;
module_param(max_probe_tries, int, 0644);
MODULE_PARM_DESC(max_probe_tries,
"Maximum probe tries before disconnecting (reason 4).");
/*
* Beacon loss timeout is calculated as N frames times the
* advertised beacon interval. This may need to be somewhat
* higher than what hardware might detect to account for
* delays in the host processing frames. But since we also
* probe on beacon miss before declaring the connection lost
* default to what we want.
*/
static int beacon_loss_count = 7;
module_param(beacon_loss_count, int, 0644);
MODULE_PARM_DESC(beacon_loss_count,
"Number of beacon intervals before we decide beacon was lost.");
/*
* Time the connection can be idle before we probe
* it to see if we can still talk to the AP.
*/
#define IEEE80211_CONNECTION_IDLE_TIME (30 * HZ)
/*
* Time we wait for a probe response after sending
* a probe request because of beacon loss or for
* checking the connection still works.
*/
static int probe_wait_ms = 500;
module_param(probe_wait_ms, int, 0644);
MODULE_PARM_DESC(probe_wait_ms,
"Maximum time(ms) to wait for probe response"
" before disconnecting (reason 4).");
/*
* Weight given to the latest Beacon frame when calculating average signal
* strength for Beacon frames received in the current BSS. This must be
* between 1 and 15.
*/
#define IEEE80211_SIGNAL_AVE_WEIGHT 3
/*
* How many Beacon frames need to have been used in average signal strength
* before starting to indicate signal change events.
*/
#define IEEE80211_SIGNAL_AVE_MIN_COUNT 4
/*
* We can have multiple work items (and connection probing)
* scheduling this timer, but we need to take care to only
* reschedule it when it should fire _earlier_ than it was
* asked for before, or if it's not pending right now. This
* function ensures that. Note that it then is required to
* run this function for all timeouts after the first one
* has happened -- the work that runs from this timer will
* do that.
*/
static void run_again(struct ieee80211_sub_if_data *sdata,
unsigned long timeout)
{
sdata_assert_lock(sdata);
if (!timer_pending(&sdata->u.mgd.timer) ||
time_before(timeout, sdata->u.mgd.timer.expires))
mod_timer(&sdata->u.mgd.timer, timeout);
}
void ieee80211_sta_reset_beacon_monitor(struct ieee80211_sub_if_data *sdata)
{
if (sdata->vif.driver_flags & IEEE80211_VIF_BEACON_FILTER)
return;
if (sdata->local->hw.flags & IEEE80211_HW_CONNECTION_MONITOR)
return;
mod_timer(&sdata->u.mgd.bcn_mon_timer,
round_jiffies_up(jiffies + sdata->u.mgd.beacon_timeout));
}
void ieee80211_sta_reset_conn_monitor(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
if (unlikely(!sdata->u.mgd.associated))
return;
ifmgd->probe_send_count = 0;
if (sdata->local->hw.flags & IEEE80211_HW_CONNECTION_MONITOR)
return;
mod_timer(&sdata->u.mgd.conn_mon_timer,
round_jiffies_up(jiffies + IEEE80211_CONNECTION_IDLE_TIME));
}
static int ecw2cw(int ecw)
{
return (1 << ecw) - 1;
}
static u32
ieee80211_determine_chantype(struct ieee80211_sub_if_data *sdata,
struct ieee80211_supported_band *sband,
struct ieee80211_channel *channel,
const struct ieee80211_ht_cap *ht_cap,
const struct ieee80211_ht_operation *ht_oper,
const struct ieee80211_vht_operation *vht_oper,
struct cfg80211_chan_def *chandef, bool tracking)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct cfg80211_chan_def vht_chandef;
u32 ht_cfreq, ret;
chandef->chan = channel;
chandef->width = NL80211_CHAN_WIDTH_20_NOHT;
chandef->center_freq1 = channel->center_freq;
chandef->center_freq2 = 0;
if (!ht_cap || !ht_oper || !sband->ht_cap.ht_supported) {
ret = IEEE80211_STA_DISABLE_HT | IEEE80211_STA_DISABLE_VHT;
goto out;
}
chandef->width = NL80211_CHAN_WIDTH_20;
if (!(ht_cap->cap_info &
cpu_to_le16(IEEE80211_HT_CAP_SUP_WIDTH_20_40))) {
ret = IEEE80211_STA_DISABLE_40MHZ;
vht_chandef = *chandef;
goto out;
}
ht_cfreq = ieee80211_channel_to_frequency(ht_oper->primary_chan,
channel->band);
/* check that channel matches the right operating channel */
if (!tracking && channel->center_freq != ht_cfreq) {
/*
* It's possible that some APs are confused here;
* Netgear WNDR3700 sometimes reports 4 higher than
* the actual channel in association responses, but
* since we look at probe response/beacon data here
* it should be OK.
*/
sdata_info(sdata,
"Wrong control channel: center-freq: %d ht-cfreq: %d ht->primary_chan: %d band: %d - Disabling HT\n",
channel->center_freq, ht_cfreq,
ht_oper->primary_chan, channel->band);
ret = IEEE80211_STA_DISABLE_HT | IEEE80211_STA_DISABLE_VHT;
goto out;
}
/* check 40 MHz support, if we have it */
if (sband->ht_cap.cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40) {
switch (ht_oper->ht_param & IEEE80211_HT_PARAM_CHA_SEC_OFFSET) {
case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
chandef->width = NL80211_CHAN_WIDTH_40;
chandef->center_freq1 += 10;
break;
case IEEE80211_HT_PARAM_CHA_SEC_BELOW:
chandef->width = NL80211_CHAN_WIDTH_40;
chandef->center_freq1 -= 10;
break;
}
} else {
/* 40 MHz (and 80 MHz) must be supported for VHT */
ret = IEEE80211_STA_DISABLE_VHT;
/* also mark 40 MHz disabled */
ret |= IEEE80211_STA_DISABLE_40MHZ;
goto out;
}
if (!vht_oper || !sband->vht_cap.vht_supported) {
ret = IEEE80211_STA_DISABLE_VHT;
goto out;
}
vht_chandef.chan = channel;
vht_chandef.center_freq1 =
ieee80211_channel_to_frequency(vht_oper->center_freq_seg1_idx,
channel->band);
vht_chandef.center_freq2 = 0;
switch (vht_oper->chan_width) {
case IEEE80211_VHT_CHANWIDTH_USE_HT:
vht_chandef.width = chandef->width;
vht_chandef.center_freq1 = chandef->center_freq1;
break;
case IEEE80211_VHT_CHANWIDTH_80MHZ:
vht_chandef.width = NL80211_CHAN_WIDTH_80;
break;
case IEEE80211_VHT_CHANWIDTH_160MHZ:
vht_chandef.width = NL80211_CHAN_WIDTH_160;
break;
case IEEE80211_VHT_CHANWIDTH_80P80MHZ:
vht_chandef.width = NL80211_CHAN_WIDTH_80P80;
vht_chandef.center_freq2 =
ieee80211_channel_to_frequency(
vht_oper->center_freq_seg2_idx,
channel->band);
break;
default:
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT))
sdata_info(sdata,
"AP VHT operation IE has invalid channel width (%d), disable VHT\n",
vht_oper->chan_width);
ret = IEEE80211_STA_DISABLE_VHT;
goto out;
}
if (!cfg80211_chandef_valid(&vht_chandef)) {
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT))
sdata_info(sdata,
"AP VHT information is invalid, disable VHT\n");
ret = IEEE80211_STA_DISABLE_VHT;
goto out;
}
if (cfg80211_chandef_identical(chandef, &vht_chandef)) {
ret = 0;
goto out;
}
if (!cfg80211_chandef_compatible(chandef, &vht_chandef)) {
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT))
sdata_info(sdata,
"AP VHT information doesn't match HT, disable VHT\n");
ret = IEEE80211_STA_DISABLE_VHT;
goto out;
}
*chandef = vht_chandef;
ret = 0;
out:
/*
* When tracking the current AP, don't do any further checks if the
* new chandef is identical to the one we're currently using for the
* connection. This keeps us from playing ping-pong with regulatory,
* without it the following can happen (for example):
* - connect to an AP with 80 MHz, world regdom allows 80 MHz
* - AP advertises regdom US
* - CRDA loads regdom US with 80 MHz prohibited (old database)
* - the code below detects an unsupported channel, downgrades, and
* we disconnect from the AP in the caller
* - disconnect causes CRDA to reload world regdomain and the game
* starts anew.
* (see https://bugzilla.kernel.org/show_bug.cgi?id=70881)
*
* It seems possible that there are still scenarios with CSA or real
* bandwidth changes where a this could happen, but those cases are
* less common and wouldn't completely prevent using the AP.
*/
if (tracking &&
cfg80211_chandef_identical(chandef, &sdata->vif.bss_conf.chandef))
return ret;
/* don't print the message below for VHT mismatch if VHT is disabled */
if (ret & IEEE80211_STA_DISABLE_VHT)
vht_chandef = *chandef;
/*
* Ignore the DISABLED flag when we're already connected and only
* tracking the APs beacon for bandwidth changes - otherwise we
* might get disconnected here if we connect to an AP, update our
* regulatory information based on the AP's country IE and the
* information we have is wrong/outdated and disables the channel
* that we're actually using for the connection to the AP.
*/
while (!cfg80211_chandef_usable(sdata->local->hw.wiphy, chandef,
tracking ? 0 :
IEEE80211_CHAN_DISABLED)) {
if (WARN_ON(chandef->width == NL80211_CHAN_WIDTH_20_NOHT)) {
ret = IEEE80211_STA_DISABLE_HT |
IEEE80211_STA_DISABLE_VHT;
break;
}
ret |= ieee80211_chandef_downgrade(chandef);
}
if (chandef->width != vht_chandef.width && !tracking)
sdata_info(sdata,
"capabilities/regulatory prevented using AP HT/VHT configuration, downgraded\n");
WARN_ON_ONCE(!cfg80211_chandef_valid(chandef));
return ret;
}
static int ieee80211_config_bw(struct ieee80211_sub_if_data *sdata,
struct sta_info *sta,
const struct ieee80211_ht_cap *ht_cap,
const struct ieee80211_ht_operation *ht_oper,
const struct ieee80211_vht_operation *vht_oper,
const u8 *bssid, u32 *changed)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_supported_band *sband;
struct ieee80211_channel *chan;
struct cfg80211_chan_def chandef;
u16 ht_opmode;
u32 flags;
enum ieee80211_sta_rx_bandwidth new_sta_bw;
int ret;
/* if HT was/is disabled, don't track any bandwidth changes */
if (ifmgd->flags & IEEE80211_STA_DISABLE_HT || !ht_oper)
return 0;
/* don't check VHT if we associated as non-VHT station */
if (ifmgd->flags & IEEE80211_STA_DISABLE_VHT)
vht_oper = NULL;
if (WARN_ON_ONCE(!sta))
return -EINVAL;
/*
* if bss configuration changed store the new one -
* this may be applicable even if channel is identical
*/
ht_opmode = le16_to_cpu(ht_oper->operation_mode);
if (sdata->vif.bss_conf.ht_operation_mode != ht_opmode) {
*changed |= BSS_CHANGED_HT;
sdata->vif.bss_conf.ht_operation_mode = ht_opmode;
}
chan = sdata->vif.bss_conf.chandef.chan;
sband = local->hw.wiphy->bands[chan->band];
/* calculate new channel (type) based on HT/VHT operation IEs */
flags = ieee80211_determine_chantype(sdata, sband, chan,
ht_cap, ht_oper, vht_oper,
&chandef, true);
/*
* Downgrade the new channel if we associated with restricted
* capabilities. For example, if we associated as a 20 MHz STA
* to a 40 MHz AP (due to regulatory, capabilities or config
* reasons) then switching to a 40 MHz channel now won't do us
* any good -- we couldn't use it with the AP.
*/
if (ifmgd->flags & IEEE80211_STA_DISABLE_80P80MHZ &&
chandef.width == NL80211_CHAN_WIDTH_80P80)
flags |= ieee80211_chandef_downgrade(&chandef);
if (ifmgd->flags & IEEE80211_STA_DISABLE_160MHZ &&
chandef.width == NL80211_CHAN_WIDTH_160)
flags |= ieee80211_chandef_downgrade(&chandef);
if (ifmgd->flags & IEEE80211_STA_DISABLE_40MHZ &&
chandef.width > NL80211_CHAN_WIDTH_20)
flags |= ieee80211_chandef_downgrade(&chandef);
if (cfg80211_chandef_identical(&chandef, &sdata->vif.bss_conf.chandef))
return 0;
sdata_info(sdata,
"AP %pM changed bandwidth, new config is %d MHz, width %d (%d/%d MHz)\n",
ifmgd->bssid, chandef.chan->center_freq, chandef.width,
chandef.center_freq1, chandef.center_freq2);
if (flags != (ifmgd->flags & (IEEE80211_STA_DISABLE_HT |
IEEE80211_STA_DISABLE_VHT |
IEEE80211_STA_DISABLE_40MHZ |
IEEE80211_STA_DISABLE_80P80MHZ |
IEEE80211_STA_DISABLE_160MHZ)) ||
!cfg80211_chandef_valid(&chandef)) {
sdata_info(sdata,
"AP %pM changed bandwidth in a way we can't support - disconnect\n",
ifmgd->bssid);
return -EINVAL;
}
switch (chandef.width) {
case NL80211_CHAN_WIDTH_20_NOHT:
case NL80211_CHAN_WIDTH_20:
new_sta_bw = IEEE80211_STA_RX_BW_20;
break;
case NL80211_CHAN_WIDTH_40:
new_sta_bw = IEEE80211_STA_RX_BW_40;
break;
case NL80211_CHAN_WIDTH_80:
new_sta_bw = IEEE80211_STA_RX_BW_80;
break;
case NL80211_CHAN_WIDTH_80P80:
case NL80211_CHAN_WIDTH_160:
new_sta_bw = IEEE80211_STA_RX_BW_160;
break;
default:
return -EINVAL;
}
if (new_sta_bw > sta->cur_max_bandwidth)
new_sta_bw = sta->cur_max_bandwidth;
if (new_sta_bw < sta->sta.bandwidth) {
sta->sta.bandwidth = new_sta_bw;
rate_control_rate_update(local, sband, sta,
IEEE80211_RC_BW_CHANGED);
}
ret = ieee80211_vif_change_bandwidth(sdata, &chandef, changed);
if (ret) {
sdata_info(sdata,
"AP %pM changed bandwidth to incompatible one - disconnect\n",
ifmgd->bssid);
return ret;
}
if (new_sta_bw > sta->sta.bandwidth) {
sta->sta.bandwidth = new_sta_bw;
rate_control_rate_update(local, sband, sta,
IEEE80211_RC_BW_CHANGED);
}
return 0;
}
/* frame sending functions */
static void ieee80211_add_ht_ie(struct ieee80211_sub_if_data *sdata,
struct sk_buff *skb, u8 ap_ht_param,
struct ieee80211_supported_band *sband,
struct ieee80211_channel *channel,
enum ieee80211_smps_mode smps)
{
u8 *pos;
u32 flags = channel->flags;
u16 cap;
struct ieee80211_sta_ht_cap ht_cap;
BUILD_BUG_ON(sizeof(ht_cap) != sizeof(sband->ht_cap));
memcpy(&ht_cap, &sband->ht_cap, sizeof(ht_cap));
ieee80211_apply_htcap_overrides(sdata, &ht_cap);
/* determine capability flags */
cap = ht_cap.cap;
switch (ap_ht_param & IEEE80211_HT_PARAM_CHA_SEC_OFFSET) {
case IEEE80211_HT_PARAM_CHA_SEC_ABOVE:
if (flags & IEEE80211_CHAN_NO_HT40PLUS) {
cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40;
cap &= ~IEEE80211_HT_CAP_SGI_40;
}
break;
case IEEE80211_HT_PARAM_CHA_SEC_BELOW:
if (flags & IEEE80211_CHAN_NO_HT40MINUS) {
cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40;
cap &= ~IEEE80211_HT_CAP_SGI_40;
}
break;
}
/*
* If 40 MHz was disabled associate as though we weren't
* capable of 40 MHz -- some broken APs will never fall
* back to trying to transmit in 20 MHz.
*/
if (sdata->u.mgd.flags & IEEE80211_STA_DISABLE_40MHZ) {
cap &= ~IEEE80211_HT_CAP_SUP_WIDTH_20_40;
cap &= ~IEEE80211_HT_CAP_SGI_40;
}
/* set SM PS mode properly */
cap &= ~IEEE80211_HT_CAP_SM_PS;
switch (smps) {
case IEEE80211_SMPS_AUTOMATIC:
case IEEE80211_SMPS_NUM_MODES:
WARN_ON(1);
case IEEE80211_SMPS_OFF:
cap |= WLAN_HT_CAP_SM_PS_DISABLED <<
IEEE80211_HT_CAP_SM_PS_SHIFT;
break;
case IEEE80211_SMPS_STATIC:
cap |= WLAN_HT_CAP_SM_PS_STATIC <<
IEEE80211_HT_CAP_SM_PS_SHIFT;
break;
case IEEE80211_SMPS_DYNAMIC:
cap |= WLAN_HT_CAP_SM_PS_DYNAMIC <<
IEEE80211_HT_CAP_SM_PS_SHIFT;
break;
}
/* reserve and fill IE */
pos = skb_put(skb, sizeof(struct ieee80211_ht_cap) + 2);
ieee80211_ie_build_ht_cap(pos, &ht_cap, cap);
}
static void ieee80211_add_vht_ie(struct ieee80211_sub_if_data *sdata,
struct sk_buff *skb,
struct ieee80211_supported_band *sband,
struct ieee80211_vht_cap *ap_vht_cap)
{
u8 *pos;
u32 cap;
struct ieee80211_sta_vht_cap vht_cap;
u32 mask, ap_bf_sts, our_bf_sts;
BUILD_BUG_ON(sizeof(vht_cap) != sizeof(sband->vht_cap));
memcpy(&vht_cap, &sband->vht_cap, sizeof(vht_cap));
ieee80211_apply_vhtcap_overrides(sdata, &vht_cap);
/* determine capability flags */
cap = vht_cap.cap;
if (sdata->u.mgd.flags & IEEE80211_STA_DISABLE_80P80MHZ) {
cap &= ~IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160_80PLUS80MHZ;
cap |= IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160MHZ;
}
if (sdata->u.mgd.flags & IEEE80211_STA_DISABLE_160MHZ) {
cap &= ~IEEE80211_VHT_CAP_SHORT_GI_160;
cap &= ~IEEE80211_VHT_CAP_SUPP_CHAN_WIDTH_160MHZ;
}
/*
* Some APs apparently get confused if our capabilities are better
* than theirs, so restrict what we advertise in the assoc request.
*/
if (!(ap_vht_cap->vht_cap_info &
cpu_to_le32(IEEE80211_VHT_CAP_SU_BEAMFORMER_CAPABLE)))
cap &= ~IEEE80211_VHT_CAP_SU_BEAMFORMEE_CAPABLE;
mask = IEEE80211_VHT_CAP_BEAMFORMEE_STS_MASK;
ap_bf_sts = le32_to_cpu(ap_vht_cap->vht_cap_info) & mask;
our_bf_sts = cap & mask;
if (ap_bf_sts < our_bf_sts) {
cap &= ~mask;
cap |= ap_bf_sts;
}
/* reserve and fill IE */
pos = skb_put(skb, sizeof(struct ieee80211_vht_cap) + 2);
ieee80211_ie_build_vht_cap(pos, &vht_cap, cap);
}
static void ieee80211_send_assoc(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_mgd_assoc_data *assoc_data = ifmgd->assoc_data;
struct sk_buff *skb;
struct ieee80211_mgmt *mgmt;
u8 *pos, qos_info;
size_t offset = 0, noffset;
int i, count, rates_len, supp_rates_len, shift;
u16 capab;
struct ieee80211_supported_band *sband;
struct ieee80211_chanctx_conf *chanctx_conf;
struct ieee80211_channel *chan;
u32 rate_flags, rates = 0;
sdata_assert_lock(sdata);
rcu_read_lock();
chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf);
if (WARN_ON(!chanctx_conf)) {
rcu_read_unlock();
return;
}
chan = chanctx_conf->def.chan;
rate_flags = ieee80211_chandef_rate_flags(&chanctx_conf->def);
rcu_read_unlock();
sband = local->hw.wiphy->bands[chan->band];
shift = ieee80211_vif_get_shift(&sdata->vif);
if (assoc_data->supp_rates_len) {
/*
* Get all rates supported by the device and the AP as
* some APs don't like getting a superset of their rates
* in the association request (e.g. D-Link DAP 1353 in
* b-only mode)...
*/
rates_len = ieee80211_parse_bitrates(&chanctx_conf->def, sband,
assoc_data->supp_rates,
assoc_data->supp_rates_len,
&rates);
} else {
/*
* In case AP not provide any supported rates information
* before association, we send information element(s) with
* all rates that we support.
*/
rates_len = 0;
for (i = 0; i < sband->n_bitrates; i++) {
if ((rate_flags & sband->bitrates[i].flags)
!= rate_flags)
continue;
rates |= BIT(i);
rates_len++;
}
}
skb = alloc_skb(local->hw.extra_tx_headroom +
sizeof(*mgmt) + /* bit too much but doesn't matter */
2 + assoc_data->ssid_len + /* SSID */
4 + rates_len + /* (extended) rates */
4 + /* power capability */
2 + 2 * sband->n_channels + /* supported channels */
2 + sizeof(struct ieee80211_ht_cap) + /* HT */
2 + sizeof(struct ieee80211_vht_cap) + /* VHT */
assoc_data->ie_len + /* extra IEs */
9, /* WMM */
GFP_KERNEL);
if (!skb)
return;
skb_reserve(skb, local->hw.extra_tx_headroom);
capab = WLAN_CAPABILITY_ESS;
if (sband->band == IEEE80211_BAND_2GHZ) {
if (!(local->hw.flags & IEEE80211_HW_2GHZ_SHORT_SLOT_INCAPABLE))
capab |= WLAN_CAPABILITY_SHORT_SLOT_TIME;
if (!(local->hw.flags & IEEE80211_HW_2GHZ_SHORT_PREAMBLE_INCAPABLE))
capab |= WLAN_CAPABILITY_SHORT_PREAMBLE;
}
if (assoc_data->capability & WLAN_CAPABILITY_PRIVACY)
capab |= WLAN_CAPABILITY_PRIVACY;
if ((assoc_data->capability & WLAN_CAPABILITY_SPECTRUM_MGMT) &&
(local->hw.flags & IEEE80211_HW_SPECTRUM_MGMT))
capab |= WLAN_CAPABILITY_SPECTRUM_MGMT;
if (ifmgd->flags & IEEE80211_STA_ENABLE_RRM)
capab |= WLAN_CAPABILITY_RADIO_MEASURE;
mgmt = (struct ieee80211_mgmt *) skb_put(skb, 24);
memset(mgmt, 0, 24);
memcpy(mgmt->da, assoc_data->bss->bssid, ETH_ALEN);
memcpy(mgmt->sa, sdata->vif.addr, ETH_ALEN);
memcpy(mgmt->bssid, assoc_data->bss->bssid, ETH_ALEN);
if (!is_zero_ether_addr(assoc_data->prev_bssid)) {
skb_put(skb, 10);
mgmt->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT |
IEEE80211_STYPE_REASSOC_REQ);
mgmt->u.reassoc_req.capab_info = cpu_to_le16(capab);
mgmt->u.reassoc_req.listen_interval =
cpu_to_le16(local->hw.conf.listen_interval);
memcpy(mgmt->u.reassoc_req.current_ap, assoc_data->prev_bssid,
ETH_ALEN);
} else {
skb_put(skb, 4);
mgmt->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT |
IEEE80211_STYPE_ASSOC_REQ);
mgmt->u.assoc_req.capab_info = cpu_to_le16(capab);
mgmt->u.assoc_req.listen_interval =
cpu_to_le16(local->hw.conf.listen_interval);
}
/* SSID */
pos = skb_put(skb, 2 + assoc_data->ssid_len);
*pos++ = WLAN_EID_SSID;
*pos++ = assoc_data->ssid_len;
memcpy(pos, assoc_data->ssid, assoc_data->ssid_len);
/* add all rates which were marked to be used above */
supp_rates_len = rates_len;
if (supp_rates_len > 8)
supp_rates_len = 8;
pos = skb_put(skb, supp_rates_len + 2);
*pos++ = WLAN_EID_SUPP_RATES;
*pos++ = supp_rates_len;
count = 0;
for (i = 0; i < sband->n_bitrates; i++) {
if (BIT(i) & rates) {
int rate = DIV_ROUND_UP(sband->bitrates[i].bitrate,
5 * (1 << shift));
*pos++ = (u8) rate;
if (++count == 8)
break;
}
}
if (rates_len > count) {
pos = skb_put(skb, rates_len - count + 2);
*pos++ = WLAN_EID_EXT_SUPP_RATES;
*pos++ = rates_len - count;
for (i++; i < sband->n_bitrates; i++) {
if (BIT(i) & rates) {
int rate;
rate = DIV_ROUND_UP(sband->bitrates[i].bitrate,
5 * (1 << shift));
*pos++ = (u8) rate;
}
}
}
if (capab & WLAN_CAPABILITY_SPECTRUM_MGMT ||
capab & WLAN_CAPABILITY_RADIO_MEASURE) {
pos = skb_put(skb, 4);
*pos++ = WLAN_EID_PWR_CAPABILITY;
*pos++ = 2;
*pos++ = 0; /* min tx power */
/* max tx power */
*pos++ = ieee80211_chandef_max_power(&chanctx_conf->def);
}
if (capab & WLAN_CAPABILITY_SPECTRUM_MGMT) {
/* TODO: get this in reg domain format */
pos = skb_put(skb, 2 * sband->n_channels + 2);
*pos++ = WLAN_EID_SUPPORTED_CHANNELS;
*pos++ = 2 * sband->n_channels;
for (i = 0; i < sband->n_channels; i++) {
*pos++ = ieee80211_frequency_to_channel(
sband->channels[i].center_freq);
*pos++ = 1; /* one channel in the subband*/
}
}
/* if present, add any custom IEs that go before HT */
if (assoc_data->ie_len) {
static const u8 before_ht[] = {
WLAN_EID_SSID,
WLAN_EID_SUPP_RATES,
WLAN_EID_EXT_SUPP_RATES,
WLAN_EID_PWR_CAPABILITY,
WLAN_EID_SUPPORTED_CHANNELS,
WLAN_EID_RSN,
WLAN_EID_QOS_CAPA,
WLAN_EID_RRM_ENABLED_CAPABILITIES,
WLAN_EID_MOBILITY_DOMAIN,
WLAN_EID_SUPPORTED_REGULATORY_CLASSES,
};
noffset = ieee80211_ie_split(assoc_data->ie, assoc_data->ie_len,
before_ht, ARRAY_SIZE(before_ht),
offset);
pos = skb_put(skb, noffset - offset);
memcpy(pos, assoc_data->ie + offset, noffset - offset);
offset = noffset;
}
if (WARN_ON_ONCE((ifmgd->flags & IEEE80211_STA_DISABLE_HT) &&
!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)))
ifmgd->flags |= IEEE80211_STA_DISABLE_VHT;
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_HT))
ieee80211_add_ht_ie(sdata, skb, assoc_data->ap_ht_param,
sband, chan, sdata->smps_mode);
/* if present, add any custom IEs that go before VHT */
if (assoc_data->ie_len) {
static const u8 before_vht[] = {
WLAN_EID_SSID,
WLAN_EID_SUPP_RATES,
WLAN_EID_EXT_SUPP_RATES,
WLAN_EID_PWR_CAPABILITY,
WLAN_EID_SUPPORTED_CHANNELS,
WLAN_EID_RSN,
WLAN_EID_QOS_CAPA,
WLAN_EID_RRM_ENABLED_CAPABILITIES,
WLAN_EID_MOBILITY_DOMAIN,
WLAN_EID_SUPPORTED_REGULATORY_CLASSES,
WLAN_EID_HT_CAPABILITY,
WLAN_EID_BSS_COEX_2040,
WLAN_EID_EXT_CAPABILITY,
WLAN_EID_QOS_TRAFFIC_CAPA,
WLAN_EID_TIM_BCAST_REQ,
WLAN_EID_INTERWORKING,
};
noffset = ieee80211_ie_split(assoc_data->ie, assoc_data->ie_len,
before_vht, ARRAY_SIZE(before_vht),
offset);
pos = skb_put(skb, noffset - offset);
memcpy(pos, assoc_data->ie + offset, noffset - offset);
offset = noffset;
}
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT))
ieee80211_add_vht_ie(sdata, skb, sband,
&assoc_data->ap_vht_cap);
/* if present, add any custom non-vendor IEs that go after HT */
if (assoc_data->ie_len) {
noffset = ieee80211_ie_split_vendor(assoc_data->ie,
assoc_data->ie_len,
offset);
pos = skb_put(skb, noffset - offset);
memcpy(pos, assoc_data->ie + offset, noffset - offset);
offset = noffset;
}
if (assoc_data->wmm) {
if (assoc_data->uapsd) {
qos_info = ifmgd->uapsd_queues;
qos_info |= (ifmgd->uapsd_max_sp_len <<
IEEE80211_WMM_IE_STA_QOSINFO_SP_SHIFT);
} else {
qos_info = 0;
}
pos = ieee80211_add_wmm_info_ie(skb_put(skb, 9), qos_info);
}
/* add any remaining custom (i.e. vendor specific here) IEs */
if (assoc_data->ie_len) {
noffset = assoc_data->ie_len;
pos = skb_put(skb, noffset - offset);
memcpy(pos, assoc_data->ie + offset, noffset - offset);
}
drv_mgd_prepare_tx(local, sdata);
IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT;
if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS)
IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_CTL_REQ_TX_STATUS |
IEEE80211_TX_INTFL_MLME_CONN_TX;
ieee80211_tx_skb(sdata, skb);
}
void ieee80211_send_pspoll(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_pspoll *pspoll;
struct sk_buff *skb;
skb = ieee80211_pspoll_get(&local->hw, &sdata->vif);
if (!skb)
return;
pspoll = (struct ieee80211_pspoll *) skb->data;
pspoll->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM);
IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT;
ieee80211_tx_skb(sdata, skb);
}
void ieee80211_send_nullfunc(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
int powersave)
{
struct sk_buff *skb;
struct ieee80211_hdr_3addr *nullfunc;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
skb = ieee80211_nullfunc_get(&local->hw, &sdata->vif);
if (!skb)
return;
nullfunc = (struct ieee80211_hdr_3addr *) skb->data;
if (powersave)
nullfunc->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM);
IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT |
IEEE80211_TX_INTFL_OFFCHAN_TX_OK;
if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS)
IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_CTL_REQ_TX_STATUS;
if (ifmgd->flags & IEEE80211_STA_CONNECTION_POLL)
IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_CTL_USE_MINRATE;
ieee80211_tx_skb(sdata, skb);
}
static void ieee80211_send_4addr_nullfunc(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata)
{
struct sk_buff *skb;
struct ieee80211_hdr *nullfunc;
__le16 fc;
if (WARN_ON(sdata->vif.type != NL80211_IFTYPE_STATION))
return;
skb = dev_alloc_skb(local->hw.extra_tx_headroom + 30);
if (!skb)
return;
skb_reserve(skb, local->hw.extra_tx_headroom);
nullfunc = (struct ieee80211_hdr *) skb_put(skb, 30);
memset(nullfunc, 0, 30);
fc = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_NULLFUNC |
IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS);
nullfunc->frame_control = fc;
memcpy(nullfunc->addr1, sdata->u.mgd.bssid, ETH_ALEN);
memcpy(nullfunc->addr2, sdata->vif.addr, ETH_ALEN);
memcpy(nullfunc->addr3, sdata->u.mgd.bssid, ETH_ALEN);
memcpy(nullfunc->addr4, sdata->vif.addr, ETH_ALEN);
IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT;
ieee80211_tx_skb(sdata, skb);
}
/* spectrum management related things */
static void ieee80211_chswitch_work(struct work_struct *work)
{
struct ieee80211_sub_if_data *sdata =
container_of(work, struct ieee80211_sub_if_data, u.mgd.chswitch_work);
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
int ret;
if (!ieee80211_sdata_running(sdata))
return;
sdata_lock(sdata);
mutex_lock(&local->mtx);
mutex_lock(&local->chanctx_mtx);
if (!ifmgd->associated)
goto out;
if (!sdata->vif.csa_active)
goto out;
/*
* using reservation isn't immediate as it may be deferred until later
* with multi-vif. once reservation is complete it will re-schedule the
* work with no reserved_chanctx so verify chandef to check if it
* completed successfully
*/
if (sdata->reserved_chanctx) {
/*
* with multi-vif csa driver may call ieee80211_csa_finish()
* many times while waiting for other interfaces to use their
* reservations
*/
if (sdata->reserved_ready)
goto out;
ret = ieee80211_vif_use_reserved_context(sdata);
if (ret) {
sdata_info(sdata,
"failed to use reserved channel context, disconnecting (err=%d)\n",
ret);
ieee80211_queue_work(&sdata->local->hw,
&ifmgd->csa_connection_drop_work);
goto out;
}
goto out;
}
if (!cfg80211_chandef_identical(&sdata->vif.bss_conf.chandef,
&sdata->csa_chandef)) {
sdata_info(sdata,
"failed to finalize channel switch, disconnecting\n");
ieee80211_queue_work(&sdata->local->hw,
&ifmgd->csa_connection_drop_work);
goto out;
}
/* XXX: shouldn't really modify cfg80211-owned data! */
ifmgd->associated->channel = sdata->csa_chandef.chan;
sdata->vif.csa_active = false;
/* XXX: wait for a beacon first? */
if (sdata->csa_block_tx) {
ieee80211_wake_vif_queues(local, sdata,
IEEE80211_QUEUE_STOP_REASON_CSA);
sdata->csa_block_tx = false;
}
ieee80211_sta_reset_beacon_monitor(sdata);
ieee80211_sta_reset_conn_monitor(sdata);
out:
mutex_unlock(&local->chanctx_mtx);
mutex_unlock(&local->mtx);
sdata_unlock(sdata);
}
void ieee80211_chswitch_done(struct ieee80211_vif *vif, bool success)
{
struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif);
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
trace_api_chswitch_done(sdata, success);
if (!success) {
sdata_info(sdata,
"driver channel switch failed, disconnecting\n");
ieee80211_queue_work(&sdata->local->hw,
&ifmgd->csa_connection_drop_work);
} else {
ieee80211_queue_work(&sdata->local->hw, &ifmgd->chswitch_work);
}
}
EXPORT_SYMBOL(ieee80211_chswitch_done);
static void ieee80211_chswitch_timer(unsigned long data)
{
struct ieee80211_sub_if_data *sdata =
(struct ieee80211_sub_if_data *) data;
ieee80211_queue_work(&sdata->local->hw, &sdata->u.mgd.chswitch_work);
}
static void
ieee80211_sta_process_chanswitch(struct ieee80211_sub_if_data *sdata,
u64 timestamp, struct ieee802_11_elems *elems,
bool beacon)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct cfg80211_bss *cbss = ifmgd->associated;
struct ieee80211_chanctx_conf *conf;
struct ieee80211_chanctx *chanctx;
enum ieee80211_band current_band;
struct ieee80211_csa_ie csa_ie;
int res;
sdata_assert_lock(sdata);
if (!cbss)
return;
if (local->scanning)
return;
/* disregard subsequent announcements if we are already processing */
if (sdata->vif.csa_active)
return;
current_band = cbss->channel->band;
memset(&csa_ie, 0, sizeof(csa_ie));
res = ieee80211_parse_ch_switch_ie(sdata, elems, current_band,
ifmgd->flags,
ifmgd->associated->bssid, &csa_ie);
if (res < 0)
ieee80211_queue_work(&local->hw,
&ifmgd->csa_connection_drop_work);
if (res)
return;
if (!cfg80211_chandef_usable(local->hw.wiphy, &csa_ie.chandef,
IEEE80211_CHAN_DISABLED)) {
sdata_info(sdata,
"AP %pM switches to unsupported channel (%d MHz, width:%d, CF1/2: %d/%d MHz), disconnecting\n",
ifmgd->associated->bssid,
csa_ie.chandef.chan->center_freq,
csa_ie.chandef.width, csa_ie.chandef.center_freq1,
csa_ie.chandef.center_freq2);
ieee80211_queue_work(&local->hw,
&ifmgd->csa_connection_drop_work);
return;
}
mutex_lock(&local->mtx);
mutex_lock(&local->chanctx_mtx);
conf = rcu_dereference_protected(sdata->vif.chanctx_conf,
lockdep_is_held(&local->chanctx_mtx));
if (!conf) {
sdata_info(sdata,
"no channel context assigned to vif?, disconnecting\n");
ieee80211_queue_work(&local->hw,
&ifmgd->csa_connection_drop_work);
mutex_unlock(&local->chanctx_mtx);
mutex_unlock(&local->mtx);
return;
}
chanctx = container_of(conf, struct ieee80211_chanctx, conf);
if (local->use_chanctx) {
u32 num_chanctx = 0;
list_for_each_entry(chanctx, &local->chanctx_list, list)
num_chanctx++;
if (num_chanctx > 1 ||
!(local->hw.flags & IEEE80211_HW_CHANCTX_STA_CSA)) {
sdata_info(sdata,
"not handling chan-switch with channel contexts\n");
ieee80211_queue_work(&local->hw,
&ifmgd->csa_connection_drop_work);
mutex_unlock(&local->chanctx_mtx);
mutex_unlock(&local->mtx);
return;
}
}
res = ieee80211_vif_reserve_chanctx(sdata, &csa_ie.chandef,
chanctx->mode, false);
if (res) {
sdata_info(sdata,
"failed to reserve channel context for channel switch, disconnecting (err=%d)\n",
res);
ieee80211_queue_work(&local->hw,
&ifmgd->csa_connection_drop_work);
mutex_unlock(&local->chanctx_mtx);
mutex_unlock(&local->mtx);
return;
}
mutex_unlock(&local->chanctx_mtx);
sdata->vif.csa_active = true;
sdata->csa_chandef = csa_ie.chandef;
sdata->csa_block_tx = csa_ie.mode;
if (sdata->csa_block_tx)
ieee80211_stop_vif_queues(local, sdata,
IEEE80211_QUEUE_STOP_REASON_CSA);
mutex_unlock(&local->mtx);
if (local->ops->channel_switch) {
/* use driver's channel switch callback */
struct ieee80211_channel_switch ch_switch = {
.timestamp = timestamp,
.block_tx = csa_ie.mode,
.chandef = csa_ie.chandef,
.count = csa_ie.count,
};
drv_channel_switch(local, &ch_switch);
return;
}
/* channel switch handled in software */
if (csa_ie.count <= 1)
ieee80211_queue_work(&local->hw, &ifmgd->chswitch_work);
else
mod_timer(&ifmgd->chswitch_timer,
TU_TO_EXP_TIME((csa_ie.count - 1) *
cbss->beacon_interval));
}
static bool
ieee80211_find_80211h_pwr_constr(struct ieee80211_sub_if_data *sdata,
struct ieee80211_channel *channel,
const u8 *country_ie, u8 country_ie_len,
const u8 *pwr_constr_elem,
int *chan_pwr, int *pwr_reduction)
{
struct ieee80211_country_ie_triplet *triplet;
int chan = ieee80211_frequency_to_channel(channel->center_freq);
int i, chan_increment;
bool have_chan_pwr = false;
/* Invalid IE */
if (country_ie_len % 2 || country_ie_len < IEEE80211_COUNTRY_IE_MIN_LEN)
return false;
triplet = (void *)(country_ie + 3);
country_ie_len -= 3;
switch (channel->band) {
default:
WARN_ON_ONCE(1);
/* fall through */
case IEEE80211_BAND_2GHZ:
case IEEE80211_BAND_60GHZ:
chan_increment = 1;
break;
case IEEE80211_BAND_5GHZ:
chan_increment = 4;
break;
}
/* find channel */
while (country_ie_len >= 3) {
u8 first_channel = triplet->chans.first_channel;
if (first_channel >= IEEE80211_COUNTRY_EXTENSION_ID)
goto next;
for (i = 0; i < triplet->chans.num_channels; i++) {
if (first_channel + i * chan_increment == chan) {
have_chan_pwr = true;
*chan_pwr = triplet->chans.max_power;
break;
}
}
if (have_chan_pwr)
break;
next:
triplet++;
country_ie_len -= 3;
}
if (have_chan_pwr)
*pwr_reduction = *pwr_constr_elem;
return have_chan_pwr;
}
static void ieee80211_find_cisco_dtpc(struct ieee80211_sub_if_data *sdata,
struct ieee80211_channel *channel,
const u8 *cisco_dtpc_ie,
int *pwr_level)
{
/* From practical testing, the first data byte of the DTPC element
* seems to contain the requested dBm level, and the CLI on Cisco
* APs clearly state the range is -127 to 127 dBm, which indicates
* a signed byte, although it seemingly never actually goes negative.
* The other byte seems to always be zero.
*/
*pwr_level = (__s8)cisco_dtpc_ie[4];
}
static u32 ieee80211_handle_pwr_constr(struct ieee80211_sub_if_data *sdata,
struct ieee80211_channel *channel,
struct ieee80211_mgmt *mgmt,
const u8 *country_ie, u8 country_ie_len,
const u8 *pwr_constr_ie,
const u8 *cisco_dtpc_ie)
{
bool has_80211h_pwr = false, has_cisco_pwr = false;
int chan_pwr = 0, pwr_reduction_80211h = 0;
int pwr_level_cisco, pwr_level_80211h;
int new_ap_level;
if (country_ie && pwr_constr_ie &&
mgmt->u.probe_resp.capab_info &
cpu_to_le16(WLAN_CAPABILITY_SPECTRUM_MGMT)) {
has_80211h_pwr = ieee80211_find_80211h_pwr_constr(
sdata, channel, country_ie, country_ie_len,
pwr_constr_ie, &chan_pwr, &pwr_reduction_80211h);
pwr_level_80211h =
max_t(int, 0, chan_pwr - pwr_reduction_80211h);
}
if (cisco_dtpc_ie) {
ieee80211_find_cisco_dtpc(
sdata, channel, cisco_dtpc_ie, &pwr_level_cisco);
has_cisco_pwr = true;
}
if (!has_80211h_pwr && !has_cisco_pwr)
return 0;
/* If we have both 802.11h and Cisco DTPC, apply both limits
* by picking the smallest of the two power levels advertised.
*/
if (has_80211h_pwr &&
(!has_cisco_pwr || pwr_level_80211h <= pwr_level_cisco)) {
sdata_info(sdata,
"Limiting TX power to %d (%d - %d) dBm as advertised by %pM\n",
pwr_level_80211h, chan_pwr, pwr_reduction_80211h,
sdata->u.mgd.bssid);
new_ap_level = pwr_level_80211h;
} else { /* has_cisco_pwr is always true here. */
sdata_info(sdata,
"Limiting TX power to %d dBm as advertised by %pM\n",
pwr_level_cisco, sdata->u.mgd.bssid);
new_ap_level = pwr_level_cisco;
}
if (sdata->ap_power_level == new_ap_level)
return 0;
sdata->ap_power_level = new_ap_level;
if (__ieee80211_recalc_txpower(sdata))
return BSS_CHANGED_TXPOWER;
return 0;
}
/* powersave */
static void ieee80211_enable_ps(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_conf *conf = &local->hw.conf;
/*
* If we are scanning right now then the parameters will
* take effect when scan finishes.
*/
if (local->scanning)
return;
if (conf->dynamic_ps_timeout > 0 &&
!(local->hw.flags & IEEE80211_HW_SUPPORTS_DYNAMIC_PS)) {
mod_timer(&local->dynamic_ps_timer, jiffies +
msecs_to_jiffies(conf->dynamic_ps_timeout));
} else {
if (local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK)
ieee80211_send_nullfunc(local, sdata, 1);
if ((local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK) &&
(local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS))
return;
conf->flags |= IEEE80211_CONF_PS;
ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS);
}
}
static void ieee80211_change_ps(struct ieee80211_local *local)
{
struct ieee80211_conf *conf = &local->hw.conf;
if (local->ps_sdata) {
ieee80211_enable_ps(local, local->ps_sdata);
} else if (conf->flags & IEEE80211_CONF_PS) {
conf->flags &= ~IEEE80211_CONF_PS;
ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS);
del_timer_sync(&local->dynamic_ps_timer);
cancel_work_sync(&local->dynamic_ps_enable_work);
}
}
static bool ieee80211_powersave_allowed(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_if_managed *mgd = &sdata->u.mgd;
struct sta_info *sta = NULL;
bool authorized = false;
if (!mgd->powersave)
return false;
if (mgd->broken_ap)
return false;
if (!mgd->associated)
return false;
if (mgd->flags & IEEE80211_STA_CONNECTION_POLL)
return false;
if (!mgd->have_beacon)
return false;
rcu_read_lock();
sta = sta_info_get(sdata, mgd->bssid);
if (sta)
authorized = test_sta_flag(sta, WLAN_STA_AUTHORIZED);
rcu_read_unlock();
return authorized;
}
/* need to hold RTNL or interface lock */
void ieee80211_recalc_ps(struct ieee80211_local *local, s32 latency)
{
struct ieee80211_sub_if_data *sdata, *found = NULL;
int count = 0;
int timeout;
if (!(local->hw.flags & IEEE80211_HW_SUPPORTS_PS)) {
local->ps_sdata = NULL;
return;
}
list_for_each_entry(sdata, &local->interfaces, list) {
if (!ieee80211_sdata_running(sdata))
continue;
if (sdata->vif.type == NL80211_IFTYPE_AP) {
/* If an AP vif is found, then disable PS
* by setting the count to zero thereby setting
* ps_sdata to NULL.
*/
count = 0;
break;
}
if (sdata->vif.type != NL80211_IFTYPE_STATION)
continue;
found = sdata;
count++;
}
if (count == 1 && ieee80211_powersave_allowed(found)) {
s32 beaconint_us;
if (latency < 0)
latency = pm_qos_request(PM_QOS_NETWORK_LATENCY);
beaconint_us = ieee80211_tu_to_usec(
found->vif.bss_conf.beacon_int);
timeout = local->dynamic_ps_forced_timeout;
if (timeout < 0) {
/*
* Go to full PSM if the user configures a very low
* latency requirement.
* The 2000 second value is there for compatibility
* until the PM_QOS_NETWORK_LATENCY is configured
* with real values.
*/
if (latency > (1900 * USEC_PER_MSEC) &&
latency != (2000 * USEC_PER_SEC))
timeout = 0;
else
timeout = 100;
}
local->hw.conf.dynamic_ps_timeout = timeout;
if (beaconint_us > latency) {
local->ps_sdata = NULL;
} else {
int maxslp = 1;
u8 dtimper = found->u.mgd.dtim_period;
/* If the TIM IE is invalid, pretend the value is 1 */
if (!dtimper)
dtimper = 1;
else if (dtimper > 1)
maxslp = min_t(int, dtimper,
latency / beaconint_us);
local->hw.conf.max_sleep_period = maxslp;
local->hw.conf.ps_dtim_period = dtimper;
local->ps_sdata = found;
}
} else {
local->ps_sdata = NULL;
}
ieee80211_change_ps(local);
}
void ieee80211_recalc_ps_vif(struct ieee80211_sub_if_data *sdata)
{
bool ps_allowed = ieee80211_powersave_allowed(sdata);
if (sdata->vif.bss_conf.ps != ps_allowed) {
sdata->vif.bss_conf.ps = ps_allowed;
ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_PS);
}
}
void ieee80211_dynamic_ps_disable_work(struct work_struct *work)
{
struct ieee80211_local *local =
container_of(work, struct ieee80211_local,
dynamic_ps_disable_work);
if (local->hw.conf.flags & IEEE80211_CONF_PS) {
local->hw.conf.flags &= ~IEEE80211_CONF_PS;
ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS);
}
ieee80211_wake_queues_by_reason(&local->hw,
IEEE80211_MAX_QUEUE_MAP,
IEEE80211_QUEUE_STOP_REASON_PS,
false);
}
void ieee80211_dynamic_ps_enable_work(struct work_struct *work)
{
struct ieee80211_local *local =
container_of(work, struct ieee80211_local,
dynamic_ps_enable_work);
struct ieee80211_sub_if_data *sdata = local->ps_sdata;
struct ieee80211_if_managed *ifmgd;
unsigned long flags;
int q;
/* can only happen when PS was just disabled anyway */
if (!sdata)
return;
ifmgd = &sdata->u.mgd;
if (local->hw.conf.flags & IEEE80211_CONF_PS)
return;
if (local->hw.conf.dynamic_ps_timeout > 0) {
/* don't enter PS if TX frames are pending */
if (drv_tx_frames_pending(local)) {
mod_timer(&local->dynamic_ps_timer, jiffies +
msecs_to_jiffies(
local->hw.conf.dynamic_ps_timeout));
return;
}
/*
* transmission can be stopped by others which leads to
* dynamic_ps_timer expiry. Postpone the ps timer if it
* is not the actual idle state.
*/
spin_lock_irqsave(&local->queue_stop_reason_lock, flags);
for (q = 0; q < local->hw.queues; q++) {
if (local->queue_stop_reasons[q]) {
spin_unlock_irqrestore(&local->queue_stop_reason_lock,
flags);
mod_timer(&local->dynamic_ps_timer, jiffies +
msecs_to_jiffies(
local->hw.conf.dynamic_ps_timeout));
return;
}
}
spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags);
}
if ((local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK) &&
!(ifmgd->flags & IEEE80211_STA_NULLFUNC_ACKED)) {
if (drv_tx_frames_pending(local)) {
mod_timer(&local->dynamic_ps_timer, jiffies +
msecs_to_jiffies(
local->hw.conf.dynamic_ps_timeout));
} else {
ieee80211_send_nullfunc(local, sdata, 1);
/* Flush to get the tx status of nullfunc frame */
ieee80211_flush_queues(local, sdata);
}
}
if (!((local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) &&
(local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK)) ||
(ifmgd->flags & IEEE80211_STA_NULLFUNC_ACKED)) {
ifmgd->flags &= ~IEEE80211_STA_NULLFUNC_ACKED;
local->hw.conf.flags |= IEEE80211_CONF_PS;
ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS);
}
}
void ieee80211_dynamic_ps_timer(unsigned long data)
{
struct ieee80211_local *local = (void *) data;
if (local->quiescing || local->suspended)
return;
ieee80211_queue_work(&local->hw, &local->dynamic_ps_enable_work);
}
void ieee80211_dfs_cac_timer_work(struct work_struct *work)
{
struct delayed_work *delayed_work =
container_of(work, struct delayed_work, work);
struct ieee80211_sub_if_data *sdata =
container_of(delayed_work, struct ieee80211_sub_if_data,
dfs_cac_timer_work);
struct cfg80211_chan_def chandef = sdata->vif.bss_conf.chandef;
mutex_lock(&sdata->local->mtx);
if (sdata->wdev.cac_started) {
ieee80211_vif_release_channel(sdata);
cfg80211_cac_event(sdata->dev, &chandef,
NL80211_RADAR_CAC_FINISHED,
GFP_KERNEL);
}
mutex_unlock(&sdata->local->mtx);
}
/* MLME */
static bool ieee80211_sta_wmm_params(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
const u8 *wmm_param, size_t wmm_param_len)
{
struct ieee80211_tx_queue_params params;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
size_t left;
int count;
const u8 *pos;
u8 uapsd_queues = 0;
if (!local->ops->conf_tx)
return false;
if (local->hw.queues < IEEE80211_NUM_ACS)
return false;
if (!wmm_param)
return false;
if (wmm_param_len < 8 || wmm_param[5] /* version */ != 1)
return false;
if (ifmgd->flags & IEEE80211_STA_UAPSD_ENABLED)
uapsd_queues = ifmgd->uapsd_queues;
count = wmm_param[6] & 0x0f;
if (count == ifmgd->wmm_last_param_set)
return false;
ifmgd->wmm_last_param_set = count;
pos = wmm_param + 8;
left = wmm_param_len - 8;
memset(¶ms, 0, sizeof(params));
sdata->wmm_acm = 0;
for (; left >= 4; left -= 4, pos += 4) {
int aci = (pos[0] >> 5) & 0x03;
int acm = (pos[0] >> 4) & 0x01;
bool uapsd = false;
int queue;
switch (aci) {
case 1: /* AC_BK */
queue = 3;
if (acm)
sdata->wmm_acm |= BIT(1) | BIT(2); /* BK/- */
if (uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_BK)
uapsd = true;
break;
case 2: /* AC_VI */
queue = 1;
if (acm)
sdata->wmm_acm |= BIT(4) | BIT(5); /* CL/VI */
if (uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VI)
uapsd = true;
break;
case 3: /* AC_VO */
queue = 0;
if (acm)
sdata->wmm_acm |= BIT(6) | BIT(7); /* VO/NC */
if (uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VO)
uapsd = true;
break;
case 0: /* AC_BE */
default:
queue = 2;
if (acm)
sdata->wmm_acm |= BIT(0) | BIT(3); /* BE/EE */
if (uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_BE)
uapsd = true;
break;
}
params.aifs = pos[0] & 0x0f;
params.cw_max = ecw2cw((pos[1] & 0xf0) >> 4);
params.cw_min = ecw2cw(pos[1] & 0x0f);
params.txop = get_unaligned_le16(pos + 2);
params.acm = acm;
params.uapsd = uapsd;
mlme_dbg(sdata,
"WMM queue=%d aci=%d acm=%d aifs=%d cWmin=%d cWmax=%d txop=%d uapsd=%d\n",
queue, aci, acm,
params.aifs, params.cw_min, params.cw_max,
params.txop, params.uapsd);
sdata->tx_conf[queue] = params;
if (drv_conf_tx(local, sdata, queue, ¶ms))
sdata_err(sdata,
"failed to set TX queue parameters for queue %d\n",
queue);
}
/* enable WMM or activate new settings */
sdata->vif.bss_conf.qos = true;
return true;
}
static void __ieee80211_stop_poll(struct ieee80211_sub_if_data *sdata)
{
lockdep_assert_held(&sdata->local->mtx);
sdata->u.mgd.flags &= ~IEEE80211_STA_CONNECTION_POLL;
ieee80211_run_deferred_scan(sdata->local);
}
static void ieee80211_stop_poll(struct ieee80211_sub_if_data *sdata)
{
mutex_lock(&sdata->local->mtx);
__ieee80211_stop_poll(sdata);
mutex_unlock(&sdata->local->mtx);
}
static u32 ieee80211_handle_bss_capability(struct ieee80211_sub_if_data *sdata,
u16 capab, bool erp_valid, u8 erp)
{
struct ieee80211_bss_conf *bss_conf = &sdata->vif.bss_conf;
u32 changed = 0;
bool use_protection;
bool use_short_preamble;
bool use_short_slot;
if (erp_valid) {
use_protection = (erp & WLAN_ERP_USE_PROTECTION) != 0;
use_short_preamble = (erp & WLAN_ERP_BARKER_PREAMBLE) == 0;
} else {
use_protection = false;
use_short_preamble = !!(capab & WLAN_CAPABILITY_SHORT_PREAMBLE);
}
use_short_slot = !!(capab & WLAN_CAPABILITY_SHORT_SLOT_TIME);
if (ieee80211_get_sdata_band(sdata) == IEEE80211_BAND_5GHZ)
use_short_slot = true;
if (use_protection != bss_conf->use_cts_prot) {
bss_conf->use_cts_prot = use_protection;
changed |= BSS_CHANGED_ERP_CTS_PROT;
}
if (use_short_preamble != bss_conf->use_short_preamble) {
bss_conf->use_short_preamble = use_short_preamble;
changed |= BSS_CHANGED_ERP_PREAMBLE;
}
if (use_short_slot != bss_conf->use_short_slot) {
bss_conf->use_short_slot = use_short_slot;
changed |= BSS_CHANGED_ERP_SLOT;
}
return changed;
}
static void ieee80211_set_associated(struct ieee80211_sub_if_data *sdata,
struct cfg80211_bss *cbss,
u32 bss_info_changed)
{
struct ieee80211_bss *bss = (void *)cbss->priv;
struct ieee80211_local *local = sdata->local;
struct ieee80211_bss_conf *bss_conf = &sdata->vif.bss_conf;
bss_info_changed |= BSS_CHANGED_ASSOC;
bss_info_changed |= ieee80211_handle_bss_capability(sdata,
bss_conf->assoc_capability, bss->has_erp_value, bss->erp_value);
sdata->u.mgd.beacon_timeout = usecs_to_jiffies(ieee80211_tu_to_usec(
beacon_loss_count * bss_conf->beacon_int));
sdata->u.mgd.associated = cbss;
memcpy(sdata->u.mgd.bssid, cbss->bssid, ETH_ALEN);
sdata->u.mgd.flags |= IEEE80211_STA_RESET_SIGNAL_AVE;
if (sdata->vif.p2p) {
const struct cfg80211_bss_ies *ies;
rcu_read_lock();
ies = rcu_dereference(cbss->ies);
if (ies) {
int ret;
ret = cfg80211_get_p2p_attr(
ies->data, ies->len,
IEEE80211_P2P_ATTR_ABSENCE_NOTICE,
(u8 *) &bss_conf->p2p_noa_attr,
sizeof(bss_conf->p2p_noa_attr));
if (ret >= 2) {
sdata->u.mgd.p2p_noa_index =
bss_conf->p2p_noa_attr.index;
bss_info_changed |= BSS_CHANGED_P2P_PS;
}
}
rcu_read_unlock();
}
/* just to be sure */
ieee80211_stop_poll(sdata);
ieee80211_led_assoc(local, 1);
if (sdata->u.mgd.have_beacon) {
/*
* If the AP is buggy we may get here with no DTIM period
* known, so assume it's 1 which is the only safe assumption
* in that case, although if the TIM IE is broken powersave
* probably just won't work at all.
*/
bss_conf->dtim_period = sdata->u.mgd.dtim_period ?: 1;
bss_conf->beacon_rate = bss->beacon_rate;
bss_info_changed |= BSS_CHANGED_BEACON_INFO;
} else {
bss_conf->beacon_rate = NULL;
bss_conf->dtim_period = 0;
}
bss_conf->assoc = 1;
/* Tell the driver to monitor connection quality (if supported) */
if (sdata->vif.driver_flags & IEEE80211_VIF_SUPPORTS_CQM_RSSI &&
bss_conf->cqm_rssi_thold)
bss_info_changed |= BSS_CHANGED_CQM;
/* Enable ARP filtering */
if (bss_conf->arp_addr_cnt)
bss_info_changed |= BSS_CHANGED_ARP_FILTER;
ieee80211_bss_info_change_notify(sdata, bss_info_changed);
mutex_lock(&local->iflist_mtx);
ieee80211_recalc_ps(local, -1);
mutex_unlock(&local->iflist_mtx);
ieee80211_recalc_smps(sdata);
ieee80211_recalc_ps_vif(sdata);
netif_carrier_on(sdata->dev);
}
static void ieee80211_set_disassoc(struct ieee80211_sub_if_data *sdata,
u16 stype, u16 reason, bool tx,
u8 *frame_buf)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_local *local = sdata->local;
u32 changed = 0;
sdata_assert_lock(sdata);
if (WARN_ON_ONCE(tx && !frame_buf))
return;
if (WARN_ON(!ifmgd->associated))
return;
ieee80211_stop_poll(sdata);
ifmgd->associated = NULL;
netif_carrier_off(sdata->dev);
/*
* if we want to get out of ps before disassoc (why?) we have
* to do it before sending disassoc, as otherwise the null-packet
* won't be valid.
*/
if (local->hw.conf.flags & IEEE80211_CONF_PS) {
local->hw.conf.flags &= ~IEEE80211_CONF_PS;
ieee80211_hw_config(local, IEEE80211_CONF_CHANGE_PS);
}
local->ps_sdata = NULL;
/* disable per-vif ps */
ieee80211_recalc_ps_vif(sdata);
/* flush out any pending frame (e.g. DELBA) before deauth/disassoc */
if (tx)
ieee80211_flush_queues(local, sdata);
/* deauthenticate/disassociate now */
if (tx || frame_buf)
ieee80211_send_deauth_disassoc(sdata, ifmgd->bssid, stype,
reason, tx, frame_buf);
/* flush out frame */
if (tx)
ieee80211_flush_queues(local, sdata);
/* clear bssid only after building the needed mgmt frames */
memset(ifmgd->bssid, 0, ETH_ALEN);
/* remove AP and TDLS peers */
sta_info_flush(sdata);
/* finally reset all BSS / config parameters */
changed |= ieee80211_reset_erp_info(sdata);
ieee80211_led_assoc(local, 0);
changed |= BSS_CHANGED_ASSOC;
sdata->vif.bss_conf.assoc = false;
ifmgd->p2p_noa_index = -1;
memset(&sdata->vif.bss_conf.p2p_noa_attr, 0,
sizeof(sdata->vif.bss_conf.p2p_noa_attr));
/* on the next assoc, re-program HT/VHT parameters */
memset(&ifmgd->ht_capa, 0, sizeof(ifmgd->ht_capa));
memset(&ifmgd->ht_capa_mask, 0, sizeof(ifmgd->ht_capa_mask));
memset(&ifmgd->vht_capa, 0, sizeof(ifmgd->vht_capa));
memset(&ifmgd->vht_capa_mask, 0, sizeof(ifmgd->vht_capa_mask));
sdata->ap_power_level = IEEE80211_UNSET_POWER_LEVEL;
del_timer_sync(&local->dynamic_ps_timer);
cancel_work_sync(&local->dynamic_ps_enable_work);
/* Disable ARP filtering */
if (sdata->vif.bss_conf.arp_addr_cnt)
changed |= BSS_CHANGED_ARP_FILTER;
sdata->vif.bss_conf.qos = false;
changed |= BSS_CHANGED_QOS;
/* The BSSID (not really interesting) and HT changed */
changed |= BSS_CHANGED_BSSID | BSS_CHANGED_HT;
ieee80211_bss_info_change_notify(sdata, changed);
/* disassociated - set to defaults now */
ieee80211_set_wmm_default(sdata, false);
del_timer_sync(&sdata->u.mgd.conn_mon_timer);
del_timer_sync(&sdata->u.mgd.bcn_mon_timer);
del_timer_sync(&sdata->u.mgd.timer);
del_timer_sync(&sdata->u.mgd.chswitch_timer);
sdata->vif.bss_conf.dtim_period = 0;
sdata->vif.bss_conf.beacon_rate = NULL;
ifmgd->have_beacon = false;
ifmgd->flags = 0;
mutex_lock(&local->mtx);
ieee80211_vif_release_channel(sdata);
sdata->vif.csa_active = false;
if (sdata->csa_block_tx) {
ieee80211_wake_vif_queues(local, sdata,
IEEE80211_QUEUE_STOP_REASON_CSA);
sdata->csa_block_tx = false;
}
mutex_unlock(&local->mtx);
sdata->encrypt_headroom = IEEE80211_ENCRYPT_HEADROOM;
}
void ieee80211_sta_rx_notify(struct ieee80211_sub_if_data *sdata,
struct ieee80211_hdr *hdr)
{
/*
* We can postpone the mgd.timer whenever receiving unicast frames
* from AP because we know that the connection is working both ways
* at that time. But multicast frames (and hence also beacons) must
* be ignored here, because we need to trigger the timer during
* data idle periods for sending the periodic probe request to the
* AP we're connected to.
*/
if (is_multicast_ether_addr(hdr->addr1))
return;
ieee80211_sta_reset_conn_monitor(sdata);
}
static void ieee80211_reset_ap_probe(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_local *local = sdata->local;
mutex_lock(&local->mtx);
if (!(ifmgd->flags & IEEE80211_STA_CONNECTION_POLL))
goto out;
__ieee80211_stop_poll(sdata);
mutex_lock(&local->iflist_mtx);
ieee80211_recalc_ps(local, -1);
mutex_unlock(&local->iflist_mtx);
if (sdata->local->hw.flags & IEEE80211_HW_CONNECTION_MONITOR)
goto out;
/*
* We've received a probe response, but are not sure whether
* we have or will be receiving any beacons or data, so let's
* schedule the timers again, just in case.
*/
ieee80211_sta_reset_beacon_monitor(sdata);
mod_timer(&ifmgd->conn_mon_timer,
round_jiffies_up(jiffies +
IEEE80211_CONNECTION_IDLE_TIME));
out:
mutex_unlock(&local->mtx);
}
void ieee80211_sta_tx_notify(struct ieee80211_sub_if_data *sdata,
struct ieee80211_hdr *hdr, bool ack)
{
if (!ieee80211_is_data(hdr->frame_control))
return;
if (ieee80211_is_nullfunc(hdr->frame_control) &&
sdata->u.mgd.probe_send_count > 0) {
if (ack)
ieee80211_sta_reset_conn_monitor(sdata);
else
sdata->u.mgd.nullfunc_failed = true;
ieee80211_queue_work(&sdata->local->hw, &sdata->work);
return;
}
if (ack)
ieee80211_sta_reset_conn_monitor(sdata);
}
static void ieee80211_mgd_probe_ap_send(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
const u8 *ssid;
u8 *dst = ifmgd->associated->bssid;
u8 unicast_limit = max(1, max_probe_tries - 3);
/*
* Try sending broadcast probe requests for the last three
* probe requests after the first ones failed since some
* buggy APs only support broadcast probe requests.
*/
if (ifmgd->probe_send_count >= unicast_limit)
dst = NULL;
/*
* When the hardware reports an accurate Tx ACK status, it's
* better to send a nullfunc frame instead of a probe request,
* as it will kick us off the AP quickly if we aren't associated
* anymore. The timeout will be reset if the frame is ACKed by
* the AP.
*/
ifmgd->probe_send_count++;
if (sdata->local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) {
ifmgd->nullfunc_failed = false;
ieee80211_send_nullfunc(sdata->local, sdata, 0);
} else {
int ssid_len;
rcu_read_lock();
ssid = ieee80211_bss_get_ie(ifmgd->associated, WLAN_EID_SSID);
if (WARN_ON_ONCE(ssid == NULL))
ssid_len = 0;
else
ssid_len = ssid[1];
ieee80211_send_probe_req(sdata, dst, ssid + 2, ssid_len, NULL,
0, (u32) -1, true, 0,
ifmgd->associated->channel, false);
rcu_read_unlock();
}
ifmgd->probe_timeout = jiffies + msecs_to_jiffies(probe_wait_ms);
run_again(sdata, ifmgd->probe_timeout);
if (sdata->local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS)
ieee80211_flush_queues(sdata->local, sdata);
}
static void ieee80211_mgd_probe_ap(struct ieee80211_sub_if_data *sdata,
bool beacon)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
bool already = false;
if (!ieee80211_sdata_running(sdata))
return;
sdata_lock(sdata);
if (!ifmgd->associated)
goto out;
mutex_lock(&sdata->local->mtx);
if (sdata->local->tmp_channel || sdata->local->scanning) {
mutex_unlock(&sdata->local->mtx);
goto out;
}
if (beacon) {
mlme_dbg_ratelimited(sdata,
"detected beacon loss from AP (missed %d beacons) - probing\n",
beacon_loss_count);
ieee80211_cqm_rssi_notify(&sdata->vif,
NL80211_CQM_RSSI_BEACON_LOSS_EVENT,
GFP_KERNEL);
}
/*
* The driver/our work has already reported this event or the
* connection monitoring has kicked in and we have already sent
* a probe request. Or maybe the AP died and the driver keeps
* reporting until we disassociate...
*
* In either case we have to ignore the current call to this
* function (except for setting the correct probe reason bit)
* because otherwise we would reset the timer every time and
* never check whether we received a probe response!
*/
if (ifmgd->flags & IEEE80211_STA_CONNECTION_POLL)
already = true;
ifmgd->flags |= IEEE80211_STA_CONNECTION_POLL;
mutex_unlock(&sdata->local->mtx);
if (already)
goto out;
mutex_lock(&sdata->local->iflist_mtx);
ieee80211_recalc_ps(sdata->local, -1);
mutex_unlock(&sdata->local->iflist_mtx);
ifmgd->probe_send_count = 0;
ieee80211_mgd_probe_ap_send(sdata);
out:
sdata_unlock(sdata);
}
struct sk_buff *ieee80211_ap_probereq_get(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif);
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct cfg80211_bss *cbss;
struct sk_buff *skb;
const u8 *ssid;
int ssid_len;
if (WARN_ON(sdata->vif.type != NL80211_IFTYPE_STATION))
return NULL;
sdata_assert_lock(sdata);
if (ifmgd->associated)
cbss = ifmgd->associated;
else if (ifmgd->auth_data)
cbss = ifmgd->auth_data->bss;
else if (ifmgd->assoc_data)
cbss = ifmgd->assoc_data->bss;
else
return NULL;
rcu_read_lock();
ssid = ieee80211_bss_get_ie(cbss, WLAN_EID_SSID);
if (WARN_ON_ONCE(ssid == NULL))
ssid_len = 0;
else
ssid_len = ssid[1];
skb = ieee80211_build_probe_req(sdata, cbss->bssid,
(u32) -1, cbss->channel,
ssid + 2, ssid_len,
NULL, 0, true);
rcu_read_unlock();
return skb;
}
EXPORT_SYMBOL(ieee80211_ap_probereq_get);
static void __ieee80211_disconnect(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN];
sdata_lock(sdata);
if (!ifmgd->associated) {
sdata_unlock(sdata);
return;
}
ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH,
WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY,
true, frame_buf);
mutex_lock(&local->mtx);
sdata->vif.csa_active = false;
if (sdata->csa_block_tx) {
ieee80211_wake_vif_queues(local, sdata,
IEEE80211_QUEUE_STOP_REASON_CSA);
sdata->csa_block_tx = false;
}
mutex_unlock(&local->mtx);
cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf,
IEEE80211_DEAUTH_FRAME_LEN);
sdata_unlock(sdata);
}
static void ieee80211_beacon_connection_loss_work(struct work_struct *work)
{
struct ieee80211_sub_if_data *sdata =
container_of(work, struct ieee80211_sub_if_data,
u.mgd.beacon_connection_loss_work);
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct sta_info *sta;
if (ifmgd->associated) {
rcu_read_lock();
sta = sta_info_get(sdata, ifmgd->bssid);
if (sta)
sta->beacon_loss_count++;
rcu_read_unlock();
}
if (ifmgd->connection_loss) {
sdata_info(sdata, "Connection to AP %pM lost\n",
ifmgd->bssid);
__ieee80211_disconnect(sdata);
} else {
ieee80211_mgd_probe_ap(sdata, true);
}
}
static void ieee80211_csa_connection_drop_work(struct work_struct *work)
{
struct ieee80211_sub_if_data *sdata =
container_of(work, struct ieee80211_sub_if_data,
u.mgd.csa_connection_drop_work);
__ieee80211_disconnect(sdata);
}
void ieee80211_beacon_loss(struct ieee80211_vif *vif)
{
struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif);
struct ieee80211_hw *hw = &sdata->local->hw;
trace_api_beacon_loss(sdata);
sdata->u.mgd.connection_loss = false;
ieee80211_queue_work(hw, &sdata->u.mgd.beacon_connection_loss_work);
}
EXPORT_SYMBOL(ieee80211_beacon_loss);
void ieee80211_connection_loss(struct ieee80211_vif *vif)
{
struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif);
struct ieee80211_hw *hw = &sdata->local->hw;
trace_api_connection_loss(sdata);
sdata->u.mgd.connection_loss = true;
ieee80211_queue_work(hw, &sdata->u.mgd.beacon_connection_loss_work);
}
EXPORT_SYMBOL(ieee80211_connection_loss);
static void ieee80211_destroy_auth_data(struct ieee80211_sub_if_data *sdata,
bool assoc)
{
struct ieee80211_mgd_auth_data *auth_data = sdata->u.mgd.auth_data;
sdata_assert_lock(sdata);
if (!assoc) {
sta_info_destroy_addr(sdata, auth_data->bss->bssid);
memset(sdata->u.mgd.bssid, 0, ETH_ALEN);
ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_BSSID);
sdata->u.mgd.flags = 0;
mutex_lock(&sdata->local->mtx);
ieee80211_vif_release_channel(sdata);
mutex_unlock(&sdata->local->mtx);
}
cfg80211_put_bss(sdata->local->hw.wiphy, auth_data->bss);
kfree(auth_data);
sdata->u.mgd.auth_data = NULL;
}
static void ieee80211_auth_challenge(struct ieee80211_sub_if_data *sdata,
struct ieee80211_mgmt *mgmt, size_t len)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_mgd_auth_data *auth_data = sdata->u.mgd.auth_data;
u8 *pos;
struct ieee802_11_elems elems;
u32 tx_flags = 0;
pos = mgmt->u.auth.variable;
ieee802_11_parse_elems(pos, len - (pos - (u8 *) mgmt), false, &elems);
if (!elems.challenge)
return;
auth_data->expected_transaction = 4;
drv_mgd_prepare_tx(sdata->local, sdata);
if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS)
tx_flags = IEEE80211_TX_CTL_REQ_TX_STATUS |
IEEE80211_TX_INTFL_MLME_CONN_TX;
ieee80211_send_auth(sdata, 3, auth_data->algorithm, 0,
elems.challenge - 2, elems.challenge_len + 2,
auth_data->bss->bssid, auth_data->bss->bssid,
auth_data->key, auth_data->key_len,
auth_data->key_idx, tx_flags);
}
static void ieee80211_rx_mgmt_auth(struct ieee80211_sub_if_data *sdata,
struct ieee80211_mgmt *mgmt, size_t len)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
u8 bssid[ETH_ALEN];
u16 auth_alg, auth_transaction, status_code;
struct sta_info *sta;
sdata_assert_lock(sdata);
if (len < 24 + 6)
return;
if (!ifmgd->auth_data || ifmgd->auth_data->done)
return;
memcpy(bssid, ifmgd->auth_data->bss->bssid, ETH_ALEN);
if (!ether_addr_equal(bssid, mgmt->bssid))
return;
auth_alg = le16_to_cpu(mgmt->u.auth.auth_alg);
auth_transaction = le16_to_cpu(mgmt->u.auth.auth_transaction);
status_code = le16_to_cpu(mgmt->u.auth.status_code);
if (auth_alg != ifmgd->auth_data->algorithm ||
auth_transaction != ifmgd->auth_data->expected_transaction) {
sdata_info(sdata, "%pM unexpected authentication state: alg %d (expected %d) transact %d (expected %d)\n",
mgmt->sa, auth_alg, ifmgd->auth_data->algorithm,
auth_transaction,
ifmgd->auth_data->expected_transaction);
return;
}
if (status_code != WLAN_STATUS_SUCCESS) {
sdata_info(sdata, "%pM denied authentication (status %d)\n",
mgmt->sa, status_code);
ieee80211_destroy_auth_data(sdata, false);
cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len);
return;
}
switch (ifmgd->auth_data->algorithm) {
case WLAN_AUTH_OPEN:
case WLAN_AUTH_LEAP:
case WLAN_AUTH_FT:
case WLAN_AUTH_SAE:
break;
case WLAN_AUTH_SHARED_KEY:
if (ifmgd->auth_data->expected_transaction != 4) {
ieee80211_auth_challenge(sdata, mgmt, len);
/* need another frame */
return;
}
break;
default:
WARN_ONCE(1, "invalid auth alg %d",
ifmgd->auth_data->algorithm);
return;
}
sdata_info(sdata, "authenticated\n");
ifmgd->auth_data->done = true;
ifmgd->auth_data->timeout = jiffies + IEEE80211_AUTH_WAIT_ASSOC;
ifmgd->auth_data->timeout_started = true;
run_again(sdata, ifmgd->auth_data->timeout);
if (ifmgd->auth_data->algorithm == WLAN_AUTH_SAE &&
ifmgd->auth_data->expected_transaction != 2) {
/*
* Report auth frame to user space for processing since another
* round of Authentication frames is still needed.
*/
cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len);
return;
}
/* move station state to auth */
mutex_lock(&sdata->local->sta_mtx);
sta = sta_info_get(sdata, bssid);
if (!sta) {
WARN_ONCE(1, "%s: STA %pM not found", sdata->name, bssid);
goto out_err;
}
if (sta_info_move_state(sta, IEEE80211_STA_AUTH)) {
sdata_info(sdata, "failed moving %pM to auth\n", bssid);
goto out_err;
}
mutex_unlock(&sdata->local->sta_mtx);
cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len);
return;
out_err:
mutex_unlock(&sdata->local->sta_mtx);
/* ignore frame -- wait for timeout */
}
#define case_WLAN(type) \
case WLAN_REASON_##type: return #type
static const char *ieee80211_get_reason_code_string(u16 reason_code)
{
switch (reason_code) {
case_WLAN(UNSPECIFIED);
case_WLAN(PREV_AUTH_NOT_VALID);
case_WLAN(DEAUTH_LEAVING);
case_WLAN(DISASSOC_DUE_TO_INACTIVITY);
case_WLAN(DISASSOC_AP_BUSY);
case_WLAN(CLASS2_FRAME_FROM_NONAUTH_STA);
case_WLAN(CLASS3_FRAME_FROM_NONASSOC_STA);
case_WLAN(DISASSOC_STA_HAS_LEFT);
case_WLAN(STA_REQ_ASSOC_WITHOUT_AUTH);
case_WLAN(DISASSOC_BAD_POWER);
case_WLAN(DISASSOC_BAD_SUPP_CHAN);
case_WLAN(INVALID_IE);
case_WLAN(MIC_FAILURE);
case_WLAN(4WAY_HANDSHAKE_TIMEOUT);
case_WLAN(GROUP_KEY_HANDSHAKE_TIMEOUT);
case_WLAN(IE_DIFFERENT);
case_WLAN(INVALID_GROUP_CIPHER);
case_WLAN(INVALID_PAIRWISE_CIPHER);
case_WLAN(INVALID_AKMP);
case_WLAN(UNSUPP_RSN_VERSION);
case_WLAN(INVALID_RSN_IE_CAP);
case_WLAN(IEEE8021X_FAILED);
case_WLAN(CIPHER_SUITE_REJECTED);
case_WLAN(DISASSOC_UNSPECIFIED_QOS);
case_WLAN(DISASSOC_QAP_NO_BANDWIDTH);
case_WLAN(DISASSOC_LOW_ACK);
case_WLAN(DISASSOC_QAP_EXCEED_TXOP);
case_WLAN(QSTA_LEAVE_QBSS);
case_WLAN(QSTA_NOT_USE);
case_WLAN(QSTA_REQUIRE_SETUP);
case_WLAN(QSTA_TIMEOUT);
case_WLAN(QSTA_CIPHER_NOT_SUPP);
case_WLAN(MESH_PEER_CANCELED);
case_WLAN(MESH_MAX_PEERS);
case_WLAN(MESH_CONFIG);
case_WLAN(MESH_CLOSE);
case_WLAN(MESH_MAX_RETRIES);
case_WLAN(MESH_CONFIRM_TIMEOUT);
case_WLAN(MESH_INVALID_GTK);
case_WLAN(MESH_INCONSISTENT_PARAM);
case_WLAN(MESH_INVALID_SECURITY);
case_WLAN(MESH_PATH_ERROR);
case_WLAN(MESH_PATH_NOFORWARD);
case_WLAN(MESH_PATH_DEST_UNREACHABLE);
case_WLAN(MAC_EXISTS_IN_MBSS);
case_WLAN(MESH_CHAN_REGULATORY);
case_WLAN(MESH_CHAN);
default: return "<unknown>";
}
}
static void ieee80211_rx_mgmt_deauth(struct ieee80211_sub_if_data *sdata,
struct ieee80211_mgmt *mgmt, size_t len)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
const u8 *bssid = NULL;
u16 reason_code;
sdata_assert_lock(sdata);
if (len < 24 + 2)
return;
if (!ifmgd->associated ||
!ether_addr_equal(mgmt->bssid, ifmgd->associated->bssid))
return;
bssid = ifmgd->associated->bssid;
reason_code = le16_to_cpu(mgmt->u.deauth.reason_code);
sdata_info(sdata, "deauthenticated from %pM (Reason: %u=%s)\n",
bssid, reason_code, ieee80211_get_reason_code_string(reason_code));
ieee80211_set_disassoc(sdata, 0, 0, false, NULL);
cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len);
}
static void ieee80211_rx_mgmt_disassoc(struct ieee80211_sub_if_data *sdata,
struct ieee80211_mgmt *mgmt, size_t len)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
u16 reason_code;
sdata_assert_lock(sdata);
if (len < 24 + 2)
return;
if (!ifmgd->associated ||
!ether_addr_equal(mgmt->bssid, ifmgd->associated->bssid))
return;
reason_code = le16_to_cpu(mgmt->u.disassoc.reason_code);
sdata_info(sdata, "disassociated from %pM (Reason: %u)\n",
mgmt->sa, reason_code);
ieee80211_set_disassoc(sdata, 0, 0, false, NULL);
cfg80211_rx_mlme_mgmt(sdata->dev, (u8 *)mgmt, len);
}
static void ieee80211_get_rates(struct ieee80211_supported_band *sband,
u8 *supp_rates, unsigned int supp_rates_len,
u32 *rates, u32 *basic_rates,
bool *have_higher_than_11mbit,
int *min_rate, int *min_rate_index,
int shift, u32 rate_flags)
{
int i, j;
for (i = 0; i < supp_rates_len; i++) {
int rate = supp_rates[i] & 0x7f;
bool is_basic = !!(supp_rates[i] & 0x80);
if ((rate * 5 * (1 << shift)) > 110)
*have_higher_than_11mbit = true;
/*
* BSS_MEMBERSHIP_SELECTOR_HT_PHY is defined in 802.11n-2009
* 7.3.2.2 as a magic value instead of a rate. Hence, skip it.
*
* Note: Even through the membership selector and the basic
* rate flag share the same bit, they are not exactly
* the same.
*/
if (!!(supp_rates[i] & 0x80) &&
(supp_rates[i] & 0x7f) == BSS_MEMBERSHIP_SELECTOR_HT_PHY)
continue;
for (j = 0; j < sband->n_bitrates; j++) {
struct ieee80211_rate *br;
int brate;
br = &sband->bitrates[j];
if ((rate_flags & br->flags) != rate_flags)
continue;
brate = DIV_ROUND_UP(br->bitrate, (1 << shift) * 5);
if (brate == rate) {
*rates |= BIT(j);
if (is_basic)
*basic_rates |= BIT(j);
if ((rate * 5) < *min_rate) {
*min_rate = rate * 5;
*min_rate_index = j;
}
break;
}
}
}
}
static void ieee80211_destroy_assoc_data(struct ieee80211_sub_if_data *sdata,
bool assoc)
{
struct ieee80211_mgd_assoc_data *assoc_data = sdata->u.mgd.assoc_data;
sdata_assert_lock(sdata);
if (!assoc) {
sta_info_destroy_addr(sdata, assoc_data->bss->bssid);
memset(sdata->u.mgd.bssid, 0, ETH_ALEN);
ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_BSSID);
sdata->u.mgd.flags = 0;
mutex_lock(&sdata->local->mtx);
ieee80211_vif_release_channel(sdata);
mutex_unlock(&sdata->local->mtx);
}
kfree(assoc_data);
sdata->u.mgd.assoc_data = NULL;
}
static bool ieee80211_assoc_success(struct ieee80211_sub_if_data *sdata,
struct cfg80211_bss *cbss,
struct ieee80211_mgmt *mgmt, size_t len)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_local *local = sdata->local;
struct ieee80211_supported_band *sband;
struct sta_info *sta;
u8 *pos;
u16 capab_info, aid;
struct ieee802_11_elems elems;
struct ieee80211_bss_conf *bss_conf = &sdata->vif.bss_conf;
const struct cfg80211_bss_ies *bss_ies = NULL;
struct ieee80211_mgd_assoc_data *assoc_data = ifmgd->assoc_data;
u32 changed = 0;
int err;
bool ret;
/* AssocResp and ReassocResp have identical structure */
aid = le16_to_cpu(mgmt->u.assoc_resp.aid);
capab_info = le16_to_cpu(mgmt->u.assoc_resp.capab_info);
if ((aid & (BIT(15) | BIT(14))) != (BIT(15) | BIT(14)))
sdata_info(sdata, "invalid AID value 0x%x; bits 15:14 not set\n",
aid);
aid &= ~(BIT(15) | BIT(14));
ifmgd->broken_ap = false;
if (aid == 0 || aid > IEEE80211_MAX_AID) {
sdata_info(sdata, "invalid AID value %d (out of range), turn off PS\n",
aid);
aid = 0;
ifmgd->broken_ap = true;
}
pos = mgmt->u.assoc_resp.variable;
ieee802_11_parse_elems(pos, len - (pos - (u8 *) mgmt), false, &elems);
if (!elems.supp_rates) {
sdata_info(sdata, "no SuppRates element in AssocResp\n");
return false;
}
ifmgd->aid = aid;
/*
* Some APs are erroneously not including some information in their
* (re)association response frames. Try to recover by using the data
* from the beacon or probe response. This seems to afflict mobile
* 2G/3G/4G wifi routers, reported models include the "Onda PN51T",
* "Vodafone PocketWiFi 2", "ZTE MF60" and a similar T-Mobile device.
*/
if ((assoc_data->wmm && !elems.wmm_param) ||
(!(ifmgd->flags & IEEE80211_STA_DISABLE_HT) &&
(!elems.ht_cap_elem || !elems.ht_operation)) ||
(!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT) &&
(!elems.vht_cap_elem || !elems.vht_operation))) {
const struct cfg80211_bss_ies *ies;
struct ieee802_11_elems bss_elems;
rcu_read_lock();
ies = rcu_dereference(cbss->ies);
if (ies)
bss_ies = kmemdup(ies, sizeof(*ies) + ies->len,
GFP_ATOMIC);
rcu_read_unlock();
if (!bss_ies)
return false;
ieee802_11_parse_elems(bss_ies->data, bss_ies->len,
false, &bss_elems);
if (assoc_data->wmm &&
!elems.wmm_param && bss_elems.wmm_param) {
elems.wmm_param = bss_elems.wmm_param;
sdata_info(sdata,
"AP bug: WMM param missing from AssocResp\n");
}
/*
* Also check if we requested HT/VHT, otherwise the AP doesn't
* have to include the IEs in the (re)association response.
*/
if (!elems.ht_cap_elem && bss_elems.ht_cap_elem &&
!(ifmgd->flags & IEEE80211_STA_DISABLE_HT)) {
elems.ht_cap_elem = bss_elems.ht_cap_elem;
sdata_info(sdata,
"AP bug: HT capability missing from AssocResp\n");
}
if (!elems.ht_operation && bss_elems.ht_operation &&
!(ifmgd->flags & IEEE80211_STA_DISABLE_HT)) {
elems.ht_operation = bss_elems.ht_operation;
sdata_info(sdata,
"AP bug: HT operation missing from AssocResp\n");
}
if (!elems.vht_cap_elem && bss_elems.vht_cap_elem &&
!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)) {
elems.vht_cap_elem = bss_elems.vht_cap_elem;
sdata_info(sdata,
"AP bug: VHT capa missing from AssocResp\n");
}
if (!elems.vht_operation && bss_elems.vht_operation &&
!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT)) {
elems.vht_operation = bss_elems.vht_operation;
sdata_info(sdata,
"AP bug: VHT operation missing from AssocResp\n");
}
}
/*
* We previously checked these in the beacon/probe response, so
* they should be present here. This is just a safety net.
*/
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_HT) &&
(!elems.wmm_param || !elems.ht_cap_elem || !elems.ht_operation)) {
sdata_info(sdata,
"HT AP is missing WMM params or HT capability/operation\n");
ret = false;
goto out;
}
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT) &&
(!elems.vht_cap_elem || !elems.vht_operation)) {
sdata_info(sdata,
"VHT AP is missing VHT capability/operation\n");
ret = false;
goto out;
}
mutex_lock(&sdata->local->sta_mtx);
/*
* station info was already allocated and inserted before
* the association and should be available to us
*/
sta = sta_info_get(sdata, cbss->bssid);
if (WARN_ON(!sta)) {
mutex_unlock(&sdata->local->sta_mtx);
ret = false;
goto out;
}
sband = local->hw.wiphy->bands[ieee80211_get_sdata_band(sdata)];
/* Set up internal HT/VHT capabilities */
if (elems.ht_cap_elem && !(ifmgd->flags & IEEE80211_STA_DISABLE_HT))
ieee80211_ht_cap_ie_to_sta_ht_cap(sdata, sband,
elems.ht_cap_elem, sta);
if (elems.vht_cap_elem && !(ifmgd->flags & IEEE80211_STA_DISABLE_VHT))
ieee80211_vht_cap_ie_to_sta_vht_cap(sdata, sband,
elems.vht_cap_elem, sta);
/*
* Some APs, e.g. Netgear WNDR3700, report invalid HT operation data
* in their association response, so ignore that data for our own
* configuration. If it changed since the last beacon, we'll get the
* next beacon and update then.
*/
/*
* If an operating mode notification IE is present, override the
* NSS calculation (that would be done in rate_control_rate_init())
* and use the # of streams from that element.
*/
if (elems.opmode_notif &&
!(*elems.opmode_notif & IEEE80211_OPMODE_NOTIF_RX_NSS_TYPE_BF)) {
u8 nss;
nss = *elems.opmode_notif & IEEE80211_OPMODE_NOTIF_RX_NSS_MASK;
nss >>= IEEE80211_OPMODE_NOTIF_RX_NSS_SHIFT;
nss += 1;
sta->sta.rx_nss = nss;
}
rate_control_rate_init(sta);
if (ifmgd->flags & IEEE80211_STA_MFP_ENABLED)
set_sta_flag(sta, WLAN_STA_MFP);
sta->sta.wme = elems.wmm_param;
err = sta_info_move_state(sta, IEEE80211_STA_ASSOC);
if (!err && !(ifmgd->flags & IEEE80211_STA_CONTROL_PORT))
err = sta_info_move_state(sta, IEEE80211_STA_AUTHORIZED);
if (err) {
sdata_info(sdata,
"failed to move station %pM to desired state\n",
sta->sta.addr);
WARN_ON(__sta_info_destroy(sta));
mutex_unlock(&sdata->local->sta_mtx);
ret = false;
goto out;
}
mutex_unlock(&sdata->local->sta_mtx);
/*
* Always handle WMM once after association regardless
* of the first value the AP uses. Setting -1 here has
* that effect because the AP values is an unsigned
* 4-bit value.
*/
ifmgd->wmm_last_param_set = -1;
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_WMM) && elems.wmm_param)
ieee80211_sta_wmm_params(local, sdata, elems.wmm_param,
elems.wmm_param_len);
else
ieee80211_set_wmm_default(sdata, false);
changed |= BSS_CHANGED_QOS;
/* set AID and assoc capability,
* ieee80211_set_associated() will tell the driver */
bss_conf->aid = aid;
bss_conf->assoc_capability = capab_info;
ieee80211_set_associated(sdata, cbss, changed);
/*
* If we're using 4-addr mode, let the AP know that we're
* doing so, so that it can create the STA VLAN on its side
*/
if (ifmgd->use_4addr)
ieee80211_send_4addr_nullfunc(local, sdata);
/*
* Start timer to probe the connection to the AP now.
* Also start the timer that will detect beacon loss.
*/
ieee80211_sta_rx_notify(sdata, (struct ieee80211_hdr *)mgmt);
ieee80211_sta_reset_beacon_monitor(sdata);
ret = true;
out:
kfree(bss_ies);
return ret;
}
static void ieee80211_rx_mgmt_assoc_resp(struct ieee80211_sub_if_data *sdata,
struct ieee80211_mgmt *mgmt,
size_t len)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_mgd_assoc_data *assoc_data = ifmgd->assoc_data;
u16 capab_info, status_code, aid;
struct ieee802_11_elems elems;
int ac, uapsd_queues = -1;
u8 *pos;
bool reassoc;
struct cfg80211_bss *bss;
sdata_assert_lock(sdata);
if (!assoc_data)
return;
if (!ether_addr_equal(assoc_data->bss->bssid, mgmt->bssid))
return;
/*
* AssocResp and ReassocResp have identical structure, so process both
* of them in this function.
*/
if (len < 24 + 6)
return;
reassoc = ieee80211_is_reassoc_req(mgmt->frame_control);
capab_info = le16_to_cpu(mgmt->u.assoc_resp.capab_info);
status_code = le16_to_cpu(mgmt->u.assoc_resp.status_code);
aid = le16_to_cpu(mgmt->u.assoc_resp.aid);
sdata_info(sdata,
"RX %sssocResp from %pM (capab=0x%x status=%d aid=%d)\n",
reassoc ? "Rea" : "A", mgmt->sa,
capab_info, status_code, (u16)(aid & ~(BIT(15) | BIT(14))));
pos = mgmt->u.assoc_resp.variable;
ieee802_11_parse_elems(pos, len - (pos - (u8 *) mgmt), false, &elems);
if (status_code == WLAN_STATUS_ASSOC_REJECTED_TEMPORARILY &&
elems.timeout_int &&
elems.timeout_int->type == WLAN_TIMEOUT_ASSOC_COMEBACK) {
u32 tu, ms;
tu = le32_to_cpu(elems.timeout_int->value);
ms = tu * 1024 / 1000;
sdata_info(sdata,
"%pM rejected association temporarily; comeback duration %u TU (%u ms)\n",
mgmt->sa, tu, ms);
assoc_data->timeout = jiffies + msecs_to_jiffies(ms);
assoc_data->timeout_started = true;
if (ms > IEEE80211_ASSOC_TIMEOUT)
run_again(sdata, assoc_data->timeout);
return;
}
bss = assoc_data->bss;
if (status_code != WLAN_STATUS_SUCCESS) {
sdata_info(sdata, "%pM denied association (code=%d)\n",
mgmt->sa, status_code);
ieee80211_destroy_assoc_data(sdata, false);
} else {
if (!ieee80211_assoc_success(sdata, bss, mgmt, len)) {
/* oops -- internal error -- send timeout for now */
ieee80211_destroy_assoc_data(sdata, false);
cfg80211_assoc_timeout(sdata->dev, bss);
return;
}
sdata_info(sdata, "associated\n");
/*
* destroy assoc_data afterwards, as otherwise an idle
* recalc after assoc_data is NULL but before associated
* is set can cause the interface to go idle
*/
ieee80211_destroy_assoc_data(sdata, true);
/* get uapsd queues configuration */
uapsd_queues = 0;
for (ac = 0; ac < IEEE80211_NUM_ACS; ac++)
if (sdata->tx_conf[ac].uapsd)
uapsd_queues |= BIT(ac);
}
cfg80211_rx_assoc_resp(sdata->dev, bss, (u8 *)mgmt, len, uapsd_queues);
}
static void ieee80211_rx_bss_info(struct ieee80211_sub_if_data *sdata,
struct ieee80211_mgmt *mgmt, size_t len,
struct ieee80211_rx_status *rx_status,
struct ieee802_11_elems *elems)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_bss *bss;
struct ieee80211_channel *channel;
sdata_assert_lock(sdata);
channel = ieee80211_get_channel(local->hw.wiphy, rx_status->freq);
if (!channel)
return;
bss = ieee80211_bss_info_update(local, rx_status, mgmt, len, elems,
channel);
if (bss) {
sdata->vif.bss_conf.beacon_rate = bss->beacon_rate;
ieee80211_rx_bss_put(local, bss);
}
}
static void ieee80211_rx_mgmt_probe_resp(struct ieee80211_sub_if_data *sdata,
struct sk_buff *skb)
{
struct ieee80211_mgmt *mgmt = (void *)skb->data;
struct ieee80211_if_managed *ifmgd;
struct ieee80211_rx_status *rx_status = (void *) skb->cb;
size_t baselen, len = skb->len;
struct ieee802_11_elems elems;
ifmgd = &sdata->u.mgd;
sdata_assert_lock(sdata);
if (!ether_addr_equal(mgmt->da, sdata->vif.addr))
return; /* ignore ProbeResp to foreign address */
baselen = (u8 *) mgmt->u.probe_resp.variable - (u8 *) mgmt;
if (baselen > len)
return;
ieee802_11_parse_elems(mgmt->u.probe_resp.variable, len - baselen,
false, &elems);
ieee80211_rx_bss_info(sdata, mgmt, len, rx_status, &elems);
if (ifmgd->associated &&
ether_addr_equal(mgmt->bssid, ifmgd->associated->bssid))
ieee80211_reset_ap_probe(sdata);
if (ifmgd->auth_data && !ifmgd->auth_data->bss->proberesp_ies &&
ether_addr_equal(mgmt->bssid, ifmgd->auth_data->bss->bssid)) {
/* got probe response, continue with auth */
sdata_info(sdata, "direct probe responded\n");
ifmgd->auth_data->tries = 0;
ifmgd->auth_data->timeout = jiffies;
ifmgd->auth_data->timeout_started = true;
run_again(sdata, ifmgd->auth_data->timeout);
}
}
/*
* This is the canonical list of information elements we care about,
* the filter code also gives us all changes to the Microsoft OUI
* (00:50:F2) vendor IE which is used for WMM which we need to track,
* as well as the DTPC IE (part of the Cisco OUI) used for signaling
* changes to requested client power.
*
* We implement beacon filtering in software since that means we can
* avoid processing the frame here and in cfg80211, and userspace
* will not be able to tell whether the hardware supports it or not.
*
* XXX: This list needs to be dynamic -- userspace needs to be able to
* add items it requires. It also needs to be able to tell us to
* look out for other vendor IEs.
*/
static const u64 care_about_ies =
(1ULL << WLAN_EID_COUNTRY) |
(1ULL << WLAN_EID_ERP_INFO) |
(1ULL << WLAN_EID_CHANNEL_SWITCH) |
(1ULL << WLAN_EID_PWR_CONSTRAINT) |
(1ULL << WLAN_EID_HT_CAPABILITY) |
(1ULL << WLAN_EID_HT_OPERATION);
static void ieee80211_rx_mgmt_beacon(struct ieee80211_sub_if_data *sdata,
struct ieee80211_mgmt *mgmt, size_t len,
struct ieee80211_rx_status *rx_status)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_bss_conf *bss_conf = &sdata->vif.bss_conf;
size_t baselen;
struct ieee802_11_elems elems;
struct ieee80211_local *local = sdata->local;
struct ieee80211_chanctx_conf *chanctx_conf;
struct ieee80211_channel *chan;
struct sta_info *sta;
u32 changed = 0;
bool erp_valid;
u8 erp_value = 0;
u32 ncrc;
u8 *bssid;
u8 deauth_buf[IEEE80211_DEAUTH_FRAME_LEN];
sdata_assert_lock(sdata);
/* Process beacon from the current BSS */
baselen = (u8 *) mgmt->u.beacon.variable - (u8 *) mgmt;
if (baselen > len)
return;
rcu_read_lock();
chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf);
if (!chanctx_conf) {
rcu_read_unlock();
return;
}
if (rx_status->freq != chanctx_conf->def.chan->center_freq) {
rcu_read_unlock();
return;
}
chan = chanctx_conf->def.chan;
rcu_read_unlock();
if (ifmgd->assoc_data && ifmgd->assoc_data->need_beacon &&
ether_addr_equal(mgmt->bssid, ifmgd->assoc_data->bss->bssid)) {
ieee802_11_parse_elems(mgmt->u.beacon.variable,
len - baselen, false, &elems);
ieee80211_rx_bss_info(sdata, mgmt, len, rx_status, &elems);
if (elems.tim && !elems.parse_error) {
const struct ieee80211_tim_ie *tim_ie = elems.tim;
ifmgd->dtim_period = tim_ie->dtim_period;
}
ifmgd->have_beacon = true;
ifmgd->assoc_data->need_beacon = false;
if (local->hw.flags & IEEE80211_HW_TIMING_BEACON_ONLY) {
sdata->vif.bss_conf.sync_tsf =
le64_to_cpu(mgmt->u.beacon.timestamp);
sdata->vif.bss_conf.sync_device_ts =
rx_status->device_timestamp;
if (elems.tim)
sdata->vif.bss_conf.sync_dtim_count =
elems.tim->dtim_count;
else
sdata->vif.bss_conf.sync_dtim_count = 0;
}
/* continue assoc process */
ifmgd->assoc_data->timeout = jiffies;
ifmgd->assoc_data->timeout_started = true;
run_again(sdata, ifmgd->assoc_data->timeout);
return;
}
if (!ifmgd->associated ||
!ether_addr_equal(mgmt->bssid, ifmgd->associated->bssid))
return;
bssid = ifmgd->associated->bssid;
/* Track average RSSI from the Beacon frames of the current AP */
ifmgd->last_beacon_signal = rx_status->signal;
if (ifmgd->flags & IEEE80211_STA_RESET_SIGNAL_AVE) {
ifmgd->flags &= ~IEEE80211_STA_RESET_SIGNAL_AVE;
ifmgd->ave_beacon_signal = rx_status->signal * 16;
ifmgd->last_cqm_event_signal = 0;
ifmgd->count_beacon_signal = 1;
ifmgd->last_ave_beacon_signal = 0;
} else {
ifmgd->ave_beacon_signal =
(IEEE80211_SIGNAL_AVE_WEIGHT * rx_status->signal * 16 +
(16 - IEEE80211_SIGNAL_AVE_WEIGHT) *
ifmgd->ave_beacon_signal) / 16;
ifmgd->count_beacon_signal++;
}
if (ifmgd->rssi_min_thold != ifmgd->rssi_max_thold &&
ifmgd->count_beacon_signal >= IEEE80211_SIGNAL_AVE_MIN_COUNT) {
int sig = ifmgd->ave_beacon_signal;
int last_sig = ifmgd->last_ave_beacon_signal;
/*
* if signal crosses either of the boundaries, invoke callback
* with appropriate parameters
*/
if (sig > ifmgd->rssi_max_thold &&
(last_sig <= ifmgd->rssi_min_thold || last_sig == 0)) {
ifmgd->last_ave_beacon_signal = sig;
drv_rssi_callback(local, sdata, RSSI_EVENT_HIGH);
} else if (sig < ifmgd->rssi_min_thold &&
(last_sig >= ifmgd->rssi_max_thold ||
last_sig == 0)) {
ifmgd->last_ave_beacon_signal = sig;
drv_rssi_callback(local, sdata, RSSI_EVENT_LOW);
}
}
if (bss_conf->cqm_rssi_thold &&
ifmgd->count_beacon_signal >= IEEE80211_SIGNAL_AVE_MIN_COUNT &&
!(sdata->vif.driver_flags & IEEE80211_VIF_SUPPORTS_CQM_RSSI)) {
int sig = ifmgd->ave_beacon_signal / 16;
int last_event = ifmgd->last_cqm_event_signal;
int thold = bss_conf->cqm_rssi_thold;
int hyst = bss_conf->cqm_rssi_hyst;
if (sig < thold &&
(last_event == 0 || sig < last_event - hyst)) {
ifmgd->last_cqm_event_signal = sig;
ieee80211_cqm_rssi_notify(
&sdata->vif,
NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW,
GFP_KERNEL);
} else if (sig > thold &&
(last_event == 0 || sig > last_event + hyst)) {
ifmgd->last_cqm_event_signal = sig;
ieee80211_cqm_rssi_notify(
&sdata->vif,
NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH,
GFP_KERNEL);
}
}
if (ifmgd->flags & IEEE80211_STA_CONNECTION_POLL) {
mlme_dbg_ratelimited(sdata,
"cancelling AP probe due to a received beacon\n");
ieee80211_reset_ap_probe(sdata);
}
/*
* Push the beacon loss detection into the future since
* we are processing a beacon from the AP just now.
*/
ieee80211_sta_reset_beacon_monitor(sdata);
ncrc = crc32_be(0, (void *)&mgmt->u.beacon.beacon_int, 4);
ncrc = ieee802_11_parse_elems_crc(mgmt->u.beacon.variable,
len - baselen, false, &elems,
care_about_ies, ncrc);
if (local->hw.flags & IEEE80211_HW_PS_NULLFUNC_STACK) {
bool directed_tim = ieee80211_check_tim(elems.tim,
elems.tim_len,
ifmgd->aid);
if (directed_tim) {
if (local->hw.conf.dynamic_ps_timeout > 0) {
if (local->hw.conf.flags & IEEE80211_CONF_PS) {
local->hw.conf.flags &= ~IEEE80211_CONF_PS;
ieee80211_hw_config(local,
IEEE80211_CONF_CHANGE_PS);
}
ieee80211_send_nullfunc(local, sdata, 0);
} else if (!local->pspolling && sdata->u.mgd.powersave) {
local->pspolling = true;
/*
* Here is assumed that the driver will be
* able to send ps-poll frame and receive a
* response even though power save mode is
* enabled, but some drivers might require
* to disable power save here. This needs
* to be investigated.
*/
ieee80211_send_pspoll(local, sdata);
}
}
}
if (sdata->vif.p2p) {
struct ieee80211_p2p_noa_attr noa = {};
int ret;
ret = cfg80211_get_p2p_attr(mgmt->u.beacon.variable,
len - baselen,
IEEE80211_P2P_ATTR_ABSENCE_NOTICE,
(u8 *) &noa, sizeof(noa));
if (ret >= 2) {
if (sdata->u.mgd.p2p_noa_index != noa.index) {
/* valid noa_attr and index changed */
sdata->u.mgd.p2p_noa_index = noa.index;
memcpy(&bss_conf->p2p_noa_attr, &noa, sizeof(noa));
changed |= BSS_CHANGED_P2P_PS;
/*
* make sure we update all information, the CRC
* mechanism doesn't look at P2P attributes.
*/
ifmgd->beacon_crc_valid = false;
}
} else if (sdata->u.mgd.p2p_noa_index != -1) {
/* noa_attr not found and we had valid noa_attr before */
sdata->u.mgd.p2p_noa_index = -1;
memset(&bss_conf->p2p_noa_attr, 0, sizeof(bss_conf->p2p_noa_attr));
changed |= BSS_CHANGED_P2P_PS;
ifmgd->beacon_crc_valid = false;
}
}
if (ncrc == ifmgd->beacon_crc && ifmgd->beacon_crc_valid)
return;
ifmgd->beacon_crc = ncrc;
ifmgd->beacon_crc_valid = true;
ieee80211_rx_bss_info(sdata, mgmt, len, rx_status, &elems);
ieee80211_sta_process_chanswitch(sdata, rx_status->mactime,
&elems, true);
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_WMM) &&
ieee80211_sta_wmm_params(local, sdata, elems.wmm_param,
elems.wmm_param_len))
changed |= BSS_CHANGED_QOS;
/*
* If we haven't had a beacon before, tell the driver about the
* DTIM period (and beacon timing if desired) now.
*/
if (!ifmgd->have_beacon) {
/* a few bogus AP send dtim_period = 0 or no TIM IE */
if (elems.tim)
bss_conf->dtim_period = elems.tim->dtim_period ?: 1;
else
bss_conf->dtim_period = 1;
if (local->hw.flags & IEEE80211_HW_TIMING_BEACON_ONLY) {
sdata->vif.bss_conf.sync_tsf =
le64_to_cpu(mgmt->u.beacon.timestamp);
sdata->vif.bss_conf.sync_device_ts =
rx_status->device_timestamp;
if (elems.tim)
sdata->vif.bss_conf.sync_dtim_count =
elems.tim->dtim_count;
else
sdata->vif.bss_conf.sync_dtim_count = 0;
}
changed |= BSS_CHANGED_BEACON_INFO;
ifmgd->have_beacon = true;
mutex_lock(&local->iflist_mtx);
ieee80211_recalc_ps(local, -1);
mutex_unlock(&local->iflist_mtx);
ieee80211_recalc_ps_vif(sdata);
}
if (elems.erp_info) {
erp_valid = true;
erp_value = elems.erp_info[0];
} else {
erp_valid = false;
}
changed |= ieee80211_handle_bss_capability(sdata,
le16_to_cpu(mgmt->u.beacon.capab_info),
erp_valid, erp_value);
mutex_lock(&local->sta_mtx);
sta = sta_info_get(sdata, bssid);
if (ieee80211_config_bw(sdata, sta,
elems.ht_cap_elem, elems.ht_operation,
elems.vht_operation, bssid, &changed)) {
mutex_unlock(&local->sta_mtx);
ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH,
WLAN_REASON_DEAUTH_LEAVING,
true, deauth_buf);
cfg80211_tx_mlme_mgmt(sdata->dev, deauth_buf,
sizeof(deauth_buf));
return;
}
if (sta && elems.opmode_notif)
ieee80211_vht_handle_opmode(sdata, sta, *elems.opmode_notif,
rx_status->band, true);
mutex_unlock(&local->sta_mtx);
changed |= ieee80211_handle_pwr_constr(sdata, chan, mgmt,
elems.country_elem,
elems.country_elem_len,
elems.pwr_constr_elem,
elems.cisco_dtpc_elem);
ieee80211_bss_info_change_notify(sdata, changed);
}
void ieee80211_sta_rx_queued_mgmt(struct ieee80211_sub_if_data *sdata,
struct sk_buff *skb)
{
struct ieee80211_rx_status *rx_status;
struct ieee80211_mgmt *mgmt;
u16 fc;
struct ieee802_11_elems elems;
int ies_len;
rx_status = (struct ieee80211_rx_status *) skb->cb;
mgmt = (struct ieee80211_mgmt *) skb->data;
fc = le16_to_cpu(mgmt->frame_control);
sdata_lock(sdata);
switch (fc & IEEE80211_FCTL_STYPE) {
case IEEE80211_STYPE_BEACON:
ieee80211_rx_mgmt_beacon(sdata, mgmt, skb->len, rx_status);
break;
case IEEE80211_STYPE_PROBE_RESP:
ieee80211_rx_mgmt_probe_resp(sdata, skb);
break;
case IEEE80211_STYPE_AUTH:
ieee80211_rx_mgmt_auth(sdata, mgmt, skb->len);
break;
case IEEE80211_STYPE_DEAUTH:
ieee80211_rx_mgmt_deauth(sdata, mgmt, skb->len);
break;
case IEEE80211_STYPE_DISASSOC:
ieee80211_rx_mgmt_disassoc(sdata, mgmt, skb->len);
break;
case IEEE80211_STYPE_ASSOC_RESP:
case IEEE80211_STYPE_REASSOC_RESP:
ieee80211_rx_mgmt_assoc_resp(sdata, mgmt, skb->len);
break;
case IEEE80211_STYPE_ACTION:
if (mgmt->u.action.category == WLAN_CATEGORY_SPECTRUM_MGMT) {
ies_len = skb->len -
offsetof(struct ieee80211_mgmt,
u.action.u.chan_switch.variable);
if (ies_len < 0)
break;
ieee802_11_parse_elems(
mgmt->u.action.u.chan_switch.variable,
ies_len, true, &elems);
if (elems.parse_error)
break;
ieee80211_sta_process_chanswitch(sdata,
rx_status->mactime,
&elems, false);
} else if (mgmt->u.action.category == WLAN_CATEGORY_PUBLIC) {
ies_len = skb->len -
offsetof(struct ieee80211_mgmt,
u.action.u.ext_chan_switch.variable);
if (ies_len < 0)
break;
ieee802_11_parse_elems(
mgmt->u.action.u.ext_chan_switch.variable,
ies_len, true, &elems);
if (elems.parse_error)
break;
/* for the handling code pretend this was also an IE */
elems.ext_chansw_ie =
&mgmt->u.action.u.ext_chan_switch.data;
ieee80211_sta_process_chanswitch(sdata,
rx_status->mactime,
&elems, false);
}
break;
}
sdata_unlock(sdata);
}
static void ieee80211_sta_timer(unsigned long data)
{
struct ieee80211_sub_if_data *sdata =
(struct ieee80211_sub_if_data *) data;
ieee80211_queue_work(&sdata->local->hw, &sdata->work);
}
static void ieee80211_sta_connection_lost(struct ieee80211_sub_if_data *sdata,
u8 *bssid, u8 reason, bool tx)
{
u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN];
ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH, reason,
tx, frame_buf);
cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf,
IEEE80211_DEAUTH_FRAME_LEN);
}
static int ieee80211_probe_auth(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_mgd_auth_data *auth_data = ifmgd->auth_data;
u32 tx_flags = 0;
sdata_assert_lock(sdata);
if (WARN_ON_ONCE(!auth_data))
return -EINVAL;
auth_data->tries++;
if (auth_data->tries > IEEE80211_AUTH_MAX_TRIES) {
sdata_info(sdata, "authentication with %pM timed out\n",
auth_data->bss->bssid);
/*
* Most likely AP is not in the range so remove the
* bss struct for that AP.
*/
cfg80211_unlink_bss(local->hw.wiphy, auth_data->bss);
return -ETIMEDOUT;
}
drv_mgd_prepare_tx(local, sdata);
if (auth_data->bss->proberesp_ies) {
u16 trans = 1;
u16 status = 0;
sdata_info(sdata, "send auth to %pM (try %d/%d)\n",
auth_data->bss->bssid, auth_data->tries,
IEEE80211_AUTH_MAX_TRIES);
auth_data->expected_transaction = 2;
if (auth_data->algorithm == WLAN_AUTH_SAE) {
trans = auth_data->sae_trans;
status = auth_data->sae_status;
auth_data->expected_transaction = trans;
}
if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS)
tx_flags = IEEE80211_TX_CTL_REQ_TX_STATUS |
IEEE80211_TX_INTFL_MLME_CONN_TX;
ieee80211_send_auth(sdata, trans, auth_data->algorithm, status,
auth_data->data, auth_data->data_len,
auth_data->bss->bssid,
auth_data->bss->bssid, NULL, 0, 0,
tx_flags);
} else {
const u8 *ssidie;
sdata_info(sdata, "direct probe to %pM (try %d/%i)\n",
auth_data->bss->bssid, auth_data->tries,
IEEE80211_AUTH_MAX_TRIES);
rcu_read_lock();
ssidie = ieee80211_bss_get_ie(auth_data->bss, WLAN_EID_SSID);
if (!ssidie) {
rcu_read_unlock();
return -EINVAL;
}
/*
* Direct probe is sent to broadcast address as some APs
* will not answer to direct packet in unassociated state.
*/
ieee80211_send_probe_req(sdata, NULL, ssidie + 2, ssidie[1],
NULL, 0, (u32) -1, true, 0,
auth_data->bss->channel, false);
rcu_read_unlock();
}
if (tx_flags == 0) {
auth_data->timeout = jiffies + IEEE80211_AUTH_TIMEOUT;
auth_data->timeout_started = true;
run_again(sdata, auth_data->timeout);
} else {
auth_data->timeout =
round_jiffies_up(jiffies + IEEE80211_AUTH_TIMEOUT_LONG);
auth_data->timeout_started = true;
run_again(sdata, auth_data->timeout);
}
return 0;
}
static int ieee80211_do_assoc(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_mgd_assoc_data *assoc_data = sdata->u.mgd.assoc_data;
struct ieee80211_local *local = sdata->local;
sdata_assert_lock(sdata);
assoc_data->tries++;
if (assoc_data->tries > IEEE80211_ASSOC_MAX_TRIES) {
sdata_info(sdata, "association with %pM timed out\n",
assoc_data->bss->bssid);
/*
* Most likely AP is not in the range so remove the
* bss struct for that AP.
*/
cfg80211_unlink_bss(local->hw.wiphy, assoc_data->bss);
return -ETIMEDOUT;
}
sdata_info(sdata, "associate with %pM (try %d/%d)\n",
assoc_data->bss->bssid, assoc_data->tries,
IEEE80211_ASSOC_MAX_TRIES);
ieee80211_send_assoc(sdata);
if (!(local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS)) {
assoc_data->timeout = jiffies + IEEE80211_ASSOC_TIMEOUT;
assoc_data->timeout_started = true;
run_again(sdata, assoc_data->timeout);
} else {
assoc_data->timeout =
round_jiffies_up(jiffies +
IEEE80211_ASSOC_TIMEOUT_LONG);
assoc_data->timeout_started = true;
run_again(sdata, assoc_data->timeout);
}
return 0;
}
void ieee80211_mgd_conn_tx_status(struct ieee80211_sub_if_data *sdata,
__le16 fc, bool acked)
{
struct ieee80211_local *local = sdata->local;
sdata->u.mgd.status_fc = fc;
sdata->u.mgd.status_acked = acked;
sdata->u.mgd.status_received = true;
ieee80211_queue_work(&local->hw, &sdata->work);
}
void ieee80211_sta_work(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
sdata_lock(sdata);
if (ifmgd->status_received) {
__le16 fc = ifmgd->status_fc;
bool status_acked = ifmgd->status_acked;
ifmgd->status_received = false;
if (ifmgd->auth_data &&
(ieee80211_is_probe_req(fc) || ieee80211_is_auth(fc))) {
if (status_acked) {
ifmgd->auth_data->timeout =
jiffies + IEEE80211_AUTH_TIMEOUT_SHORT;
run_again(sdata, ifmgd->auth_data->timeout);
} else {
ifmgd->auth_data->timeout = jiffies - 1;
}
ifmgd->auth_data->timeout_started = true;
} else if (ifmgd->assoc_data &&
(ieee80211_is_assoc_req(fc) ||
ieee80211_is_reassoc_req(fc))) {
if (status_acked) {
ifmgd->assoc_data->timeout =
jiffies + IEEE80211_ASSOC_TIMEOUT_SHORT;
run_again(sdata, ifmgd->assoc_data->timeout);
} else {
ifmgd->assoc_data->timeout = jiffies - 1;
}
ifmgd->assoc_data->timeout_started = true;
}
}
if (ifmgd->auth_data && ifmgd->auth_data->timeout_started &&
time_after(jiffies, ifmgd->auth_data->timeout)) {
if (ifmgd->auth_data->done) {
/*
* ok ... we waited for assoc but userspace didn't,
* so let's just kill the auth data
*/
ieee80211_destroy_auth_data(sdata, false);
} else if (ieee80211_probe_auth(sdata)) {
u8 bssid[ETH_ALEN];
memcpy(bssid, ifmgd->auth_data->bss->bssid, ETH_ALEN);
ieee80211_destroy_auth_data(sdata, false);
cfg80211_auth_timeout(sdata->dev, bssid);
}
} else if (ifmgd->auth_data && ifmgd->auth_data->timeout_started)
run_again(sdata, ifmgd->auth_data->timeout);
if (ifmgd->assoc_data && ifmgd->assoc_data->timeout_started &&
time_after(jiffies, ifmgd->assoc_data->timeout)) {
if ((ifmgd->assoc_data->need_beacon && !ifmgd->have_beacon) ||
ieee80211_do_assoc(sdata)) {
struct cfg80211_bss *bss = ifmgd->assoc_data->bss;
ieee80211_destroy_assoc_data(sdata, false);
cfg80211_assoc_timeout(sdata->dev, bss);
}
} else if (ifmgd->assoc_data && ifmgd->assoc_data->timeout_started)
run_again(sdata, ifmgd->assoc_data->timeout);
if (ifmgd->flags & IEEE80211_STA_CONNECTION_POLL &&
ifmgd->associated) {
u8 bssid[ETH_ALEN];
int max_tries;
memcpy(bssid, ifmgd->associated->bssid, ETH_ALEN);
if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS)
max_tries = max_nullfunc_tries;
else
max_tries = max_probe_tries;
/* ACK received for nullfunc probing frame */
if (!ifmgd->probe_send_count)
ieee80211_reset_ap_probe(sdata);
else if (ifmgd->nullfunc_failed) {
if (ifmgd->probe_send_count < max_tries) {
mlme_dbg(sdata,
"No ack for nullfunc frame to AP %pM, try %d/%i\n",
bssid, ifmgd->probe_send_count,
max_tries);
ieee80211_mgd_probe_ap_send(sdata);
} else {
mlme_dbg(sdata,
"No ack for nullfunc frame to AP %pM, disconnecting.\n",
bssid);
ieee80211_sta_connection_lost(sdata, bssid,
WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY,
false);
}
} else if (time_is_after_jiffies(ifmgd->probe_timeout))
run_again(sdata, ifmgd->probe_timeout);
else if (local->hw.flags & IEEE80211_HW_REPORTS_TX_ACK_STATUS) {
mlme_dbg(sdata,
"Failed to send nullfunc to AP %pM after %dms, disconnecting\n",
bssid, probe_wait_ms);
ieee80211_sta_connection_lost(sdata, bssid,
WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY, false);
} else if (ifmgd->probe_send_count < max_tries) {
mlme_dbg(sdata,
"No probe response from AP %pM after %dms, try %d/%i\n",
bssid, probe_wait_ms,
ifmgd->probe_send_count, max_tries);
ieee80211_mgd_probe_ap_send(sdata);
} else {
/*
* We actually lost the connection ... or did we?
* Let's make sure!
*/
wiphy_debug(local->hw.wiphy,
"%s: No probe response from AP %pM"
" after %dms, disconnecting.\n",
sdata->name,
bssid, probe_wait_ms);
ieee80211_sta_connection_lost(sdata, bssid,
WLAN_REASON_DISASSOC_DUE_TO_INACTIVITY, false);
}
}
sdata_unlock(sdata);
}
static void ieee80211_sta_bcn_mon_timer(unsigned long data)
{
struct ieee80211_sub_if_data *sdata =
(struct ieee80211_sub_if_data *) data;
struct ieee80211_local *local = sdata->local;
if (local->quiescing)
return;
if (sdata->vif.csa_active)
return;
sdata->u.mgd.connection_loss = false;
ieee80211_queue_work(&sdata->local->hw,
&sdata->u.mgd.beacon_connection_loss_work);
}
static void ieee80211_sta_conn_mon_timer(unsigned long data)
{
struct ieee80211_sub_if_data *sdata =
(struct ieee80211_sub_if_data *) data;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_local *local = sdata->local;
if (local->quiescing)
return;
if (sdata->vif.csa_active)
return;
ieee80211_queue_work(&local->hw, &ifmgd->monitor_work);
}
static void ieee80211_sta_monitor_work(struct work_struct *work)
{
struct ieee80211_sub_if_data *sdata =
container_of(work, struct ieee80211_sub_if_data,
u.mgd.monitor_work);
ieee80211_mgd_probe_ap(sdata, false);
}
static void ieee80211_restart_sta_timer(struct ieee80211_sub_if_data *sdata)
{
u32 flags;
if (sdata->vif.type == NL80211_IFTYPE_STATION) {
__ieee80211_stop_poll(sdata);
/* let's probe the connection once */
flags = sdata->local->hw.flags;
if (!(flags & IEEE80211_HW_CONNECTION_MONITOR))
ieee80211_queue_work(&sdata->local->hw,
&sdata->u.mgd.monitor_work);
/* and do all the other regular work too */
ieee80211_queue_work(&sdata->local->hw, &sdata->work);
}
}
#ifdef CONFIG_PM
void ieee80211_mgd_quiesce(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN];
sdata_lock(sdata);
if (ifmgd->auth_data || ifmgd->assoc_data) {
const u8 *bssid = ifmgd->auth_data ?
ifmgd->auth_data->bss->bssid :
ifmgd->assoc_data->bss->bssid;
/*
* If we are trying to authenticate / associate while suspending,
* cfg80211 won't know and won't actually abort those attempts,
* thus we need to do that ourselves.
*/
ieee80211_send_deauth_disassoc(sdata, bssid,
IEEE80211_STYPE_DEAUTH,
WLAN_REASON_DEAUTH_LEAVING,
false, frame_buf);
if (ifmgd->assoc_data)
ieee80211_destroy_assoc_data(sdata, false);
if (ifmgd->auth_data)
ieee80211_destroy_auth_data(sdata, false);
cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf,
IEEE80211_DEAUTH_FRAME_LEN);
}
sdata_unlock(sdata);
}
void ieee80211_sta_restart(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
sdata_lock(sdata);
if (!ifmgd->associated) {
sdata_unlock(sdata);
return;
}
if (sdata->flags & IEEE80211_SDATA_DISCONNECT_RESUME) {
sdata->flags &= ~IEEE80211_SDATA_DISCONNECT_RESUME;
mlme_dbg(sdata, "driver requested disconnect after resume\n");
ieee80211_sta_connection_lost(sdata,
ifmgd->associated->bssid,
WLAN_REASON_UNSPECIFIED,
true);
sdata_unlock(sdata);
return;
}
sdata_unlock(sdata);
}
#endif
/* interface setup */
void ieee80211_sta_setup_sdata(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_if_managed *ifmgd;
ifmgd = &sdata->u.mgd;
INIT_WORK(&ifmgd->monitor_work, ieee80211_sta_monitor_work);
INIT_WORK(&ifmgd->chswitch_work, ieee80211_chswitch_work);
INIT_WORK(&ifmgd->beacon_connection_loss_work,
ieee80211_beacon_connection_loss_work);
INIT_WORK(&ifmgd->csa_connection_drop_work,
ieee80211_csa_connection_drop_work);
INIT_WORK(&ifmgd->request_smps_work, ieee80211_request_smps_mgd_work);
INIT_DELAYED_WORK(&ifmgd->tdls_peer_del_work,
ieee80211_tdls_peer_del_work);
setup_timer(&ifmgd->timer, ieee80211_sta_timer,
(unsigned long) sdata);
setup_timer(&ifmgd->bcn_mon_timer, ieee80211_sta_bcn_mon_timer,
(unsigned long) sdata);
setup_timer(&ifmgd->conn_mon_timer, ieee80211_sta_conn_mon_timer,
(unsigned long) sdata);
setup_timer(&ifmgd->chswitch_timer, ieee80211_chswitch_timer,
(unsigned long) sdata);
ifmgd->flags = 0;
ifmgd->powersave = sdata->wdev.ps;
ifmgd->uapsd_queues = sdata->local->hw.uapsd_queues;
ifmgd->uapsd_max_sp_len = sdata->local->hw.uapsd_max_sp_len;
ifmgd->p2p_noa_index = -1;
if (sdata->local->hw.wiphy->features & NL80211_FEATURE_DYNAMIC_SMPS)
ifmgd->req_smps = IEEE80211_SMPS_AUTOMATIC;
else
ifmgd->req_smps = IEEE80211_SMPS_OFF;
}
/* scan finished notification */
void ieee80211_mlme_notify_scan_completed(struct ieee80211_local *local)
{
struct ieee80211_sub_if_data *sdata;
/* Restart STA timers */
rcu_read_lock();
list_for_each_entry_rcu(sdata, &local->interfaces, list) {
if (ieee80211_sdata_running(sdata))
ieee80211_restart_sta_timer(sdata);
}
rcu_read_unlock();
}
int ieee80211_max_network_latency(struct notifier_block *nb,
unsigned long data, void *dummy)
{
s32 latency_usec = (s32) data;
struct ieee80211_local *local =
container_of(nb, struct ieee80211_local,
network_latency_notifier);
mutex_lock(&local->iflist_mtx);
ieee80211_recalc_ps(local, latency_usec);
mutex_unlock(&local->iflist_mtx);
return NOTIFY_OK;
}
static u8 ieee80211_ht_vht_rx_chains(struct ieee80211_sub_if_data *sdata,
struct cfg80211_bss *cbss)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
const u8 *ht_cap_ie, *vht_cap_ie;
const struct ieee80211_ht_cap *ht_cap;
const struct ieee80211_vht_cap *vht_cap;
u8 chains = 1;
if (ifmgd->flags & IEEE80211_STA_DISABLE_HT)
return chains;
ht_cap_ie = ieee80211_bss_get_ie(cbss, WLAN_EID_HT_CAPABILITY);
if (ht_cap_ie && ht_cap_ie[1] >= sizeof(*ht_cap)) {
ht_cap = (void *)(ht_cap_ie + 2);
chains = ieee80211_mcs_to_chains(&ht_cap->mcs);
/*
* TODO: use "Tx Maximum Number Spatial Streams Supported" and
* "Tx Unequal Modulation Supported" fields.
*/
}
if (ifmgd->flags & IEEE80211_STA_DISABLE_VHT)
return chains;
vht_cap_ie = ieee80211_bss_get_ie(cbss, WLAN_EID_VHT_CAPABILITY);
if (vht_cap_ie && vht_cap_ie[1] >= sizeof(*vht_cap)) {
u8 nss;
u16 tx_mcs_map;
vht_cap = (void *)(vht_cap_ie + 2);
tx_mcs_map = le16_to_cpu(vht_cap->supp_mcs.tx_mcs_map);
for (nss = 8; nss > 0; nss--) {
if (((tx_mcs_map >> (2 * (nss - 1))) & 3) !=
IEEE80211_VHT_MCS_NOT_SUPPORTED)
break;
}
/* TODO: use "Tx Highest Supported Long GI Data Rate" field? */
chains = max(chains, nss);
}
return chains;
}
static int ieee80211_prep_channel(struct ieee80211_sub_if_data *sdata,
struct cfg80211_bss *cbss)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
const struct ieee80211_ht_cap *ht_cap = NULL;
const struct ieee80211_ht_operation *ht_oper = NULL;
const struct ieee80211_vht_operation *vht_oper = NULL;
struct ieee80211_supported_band *sband;
struct cfg80211_chan_def chandef;
int ret;
sband = local->hw.wiphy->bands[cbss->channel->band];
ifmgd->flags &= ~(IEEE80211_STA_DISABLE_40MHZ |
IEEE80211_STA_DISABLE_80P80MHZ |
IEEE80211_STA_DISABLE_160MHZ);
rcu_read_lock();
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_HT) &&
sband->ht_cap.ht_supported) {
const u8 *ht_oper_ie, *ht_cap_ie;
ht_oper_ie = ieee80211_bss_get_ie(cbss, WLAN_EID_HT_OPERATION);
if (ht_oper_ie && ht_oper_ie[1] >= sizeof(*ht_oper))
ht_oper = (void *)(ht_oper_ie + 2);
ht_cap_ie = ieee80211_bss_get_ie(cbss, WLAN_EID_HT_CAPABILITY);
if (ht_cap_ie && ht_cap_ie[1] >= sizeof(*ht_cap))
ht_cap = (void *)(ht_cap_ie + 2);
if (!ht_cap) {
ifmgd->flags |= IEEE80211_STA_DISABLE_HT;
ht_oper = NULL;
}
}
if (!(ifmgd->flags & IEEE80211_STA_DISABLE_VHT) &&
sband->vht_cap.vht_supported) {
const u8 *vht_oper_ie, *vht_cap;
vht_oper_ie = ieee80211_bss_get_ie(cbss,
WLAN_EID_VHT_OPERATION);
if (vht_oper_ie && vht_oper_ie[1] >= sizeof(*vht_oper))
vht_oper = (void *)(vht_oper_ie + 2);
if (vht_oper && !ht_oper) {
vht_oper = NULL;
sdata_info(sdata,
"AP advertised VHT without HT, disabling both\n");
ifmgd->flags |= IEEE80211_STA_DISABLE_HT;
ifmgd->flags |= IEEE80211_STA_DISABLE_VHT;
}
vht_cap = ieee80211_bss_get_ie(cbss, WLAN_EID_VHT_CAPABILITY);
if (!vht_cap || vht_cap[1] < sizeof(struct ieee80211_vht_cap)) {
ifmgd->flags |= IEEE80211_STA_DISABLE_VHT;
vht_oper = NULL;
}
}
ifmgd->flags |= ieee80211_determine_chantype(sdata, sband,
cbss->channel,
ht_cap, ht_oper, vht_oper,
&chandef, false);
sdata->needed_rx_chains = min(ieee80211_ht_vht_rx_chains(sdata, cbss),
local->rx_chains);
rcu_read_unlock();
/* will change later if needed */
sdata->smps_mode = IEEE80211_SMPS_OFF;
mutex_lock(&local->mtx);
/*
* If this fails (possibly due to channel context sharing
* on incompatible channels, e.g. 80+80 and 160 sharing the
* same control channel) try to use a smaller bandwidth.
*/
ret = ieee80211_vif_use_channel(sdata, &chandef,
IEEE80211_CHANCTX_SHARED);
/* don't downgrade for 5 and 10 MHz channels, though. */
if (chandef.width == NL80211_CHAN_WIDTH_5 ||
chandef.width == NL80211_CHAN_WIDTH_10)
goto out;
while (ret && chandef.width != NL80211_CHAN_WIDTH_20_NOHT) {
ifmgd->flags |= ieee80211_chandef_downgrade(&chandef);
ret = ieee80211_vif_use_channel(sdata, &chandef,
IEEE80211_CHANCTX_SHARED);
}
out:
mutex_unlock(&local->mtx);
return ret;
}
static int ieee80211_prep_connection(struct ieee80211_sub_if_data *sdata,
struct cfg80211_bss *cbss, bool assoc)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_bss *bss = (void *)cbss->priv;
struct sta_info *new_sta = NULL;
bool have_sta = false;
int err;
if (WARN_ON(!ifmgd->auth_data && !ifmgd->assoc_data))
return -EINVAL;
if (assoc) {
rcu_read_lock();
have_sta = sta_info_get(sdata, cbss->bssid);
rcu_read_unlock();
}
if (!have_sta) {
new_sta = sta_info_alloc(sdata, cbss->bssid, GFP_KERNEL);
if (!new_sta)
return -ENOMEM;
}
if (new_sta) {
u32 rates = 0, basic_rates = 0;
bool have_higher_than_11mbit;
int min_rate = INT_MAX, min_rate_index = -1;
struct ieee80211_chanctx_conf *chanctx_conf;
struct ieee80211_supported_band *sband;
const struct cfg80211_bss_ies *ies;
int shift;
u32 rate_flags;
sband = local->hw.wiphy->bands[cbss->channel->band];
err = ieee80211_prep_channel(sdata, cbss);
if (err) {
sta_info_free(local, new_sta);
return -EINVAL;
}
shift = ieee80211_vif_get_shift(&sdata->vif);
rcu_read_lock();
chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf);
if (WARN_ON(!chanctx_conf)) {
rcu_read_unlock();
sta_info_free(local, new_sta);
return -EINVAL;
}
rate_flags = ieee80211_chandef_rate_flags(&chanctx_conf->def);
rcu_read_unlock();
ieee80211_get_rates(sband, bss->supp_rates,
bss->supp_rates_len,
&rates, &basic_rates,
&have_higher_than_11mbit,
&min_rate, &min_rate_index,
shift, rate_flags);
/*
* This used to be a workaround for basic rates missing
* in the association response frame. Now that we no
* longer use the basic rates from there, it probably
* doesn't happen any more, but keep the workaround so
* in case some *other* APs are buggy in different ways
* we can connect -- with a warning.
*/
if (!basic_rates && min_rate_index >= 0) {
sdata_info(sdata,
"No basic rates, using min rate instead\n");
basic_rates = BIT(min_rate_index);
}
new_sta->sta.supp_rates[cbss->channel->band] = rates;
sdata->vif.bss_conf.basic_rates = basic_rates;
/* cf. IEEE 802.11 9.2.12 */
if (cbss->channel->band == IEEE80211_BAND_2GHZ &&
have_higher_than_11mbit)
sdata->flags |= IEEE80211_SDATA_OPERATING_GMODE;
else
sdata->flags &= ~IEEE80211_SDATA_OPERATING_GMODE;
memcpy(ifmgd->bssid, cbss->bssid, ETH_ALEN);
/* set timing information */
sdata->vif.bss_conf.beacon_int = cbss->beacon_interval;
rcu_read_lock();
ies = rcu_dereference(cbss->beacon_ies);
if (ies) {
const u8 *tim_ie;
sdata->vif.bss_conf.sync_tsf = ies->tsf;
sdata->vif.bss_conf.sync_device_ts =
bss->device_ts_beacon;
tim_ie = cfg80211_find_ie(WLAN_EID_TIM,
ies->data, ies->len);
if (tim_ie && tim_ie[1] >= 2)
sdata->vif.bss_conf.sync_dtim_count = tim_ie[2];
else
sdata->vif.bss_conf.sync_dtim_count = 0;
} else if (!(local->hw.flags &
IEEE80211_HW_TIMING_BEACON_ONLY)) {
ies = rcu_dereference(cbss->proberesp_ies);
/* must be non-NULL since beacon IEs were NULL */
sdata->vif.bss_conf.sync_tsf = ies->tsf;
sdata->vif.bss_conf.sync_device_ts =
bss->device_ts_presp;
sdata->vif.bss_conf.sync_dtim_count = 0;
} else {
sdata->vif.bss_conf.sync_tsf = 0;
sdata->vif.bss_conf.sync_device_ts = 0;
sdata->vif.bss_conf.sync_dtim_count = 0;
}
rcu_read_unlock();
/* tell driver about BSSID, basic rates and timing */
ieee80211_bss_info_change_notify(sdata,
BSS_CHANGED_BSSID | BSS_CHANGED_BASIC_RATES |
BSS_CHANGED_BEACON_INT);
if (assoc)
sta_info_pre_move_state(new_sta, IEEE80211_STA_AUTH);
err = sta_info_insert(new_sta);
new_sta = NULL;
if (err) {
sdata_info(sdata,
"failed to insert STA entry for the AP (error %d)\n",
err);
return err;
}
} else
WARN_ON_ONCE(!ether_addr_equal(ifmgd->bssid, cbss->bssid));
return 0;
}
/* config hooks */
int ieee80211_mgd_auth(struct ieee80211_sub_if_data *sdata,
struct cfg80211_auth_request *req)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_mgd_auth_data *auth_data;
u16 auth_alg;
int err;
/* prepare auth data structure */
switch (req->auth_type) {
case NL80211_AUTHTYPE_OPEN_SYSTEM:
auth_alg = WLAN_AUTH_OPEN;
break;
case NL80211_AUTHTYPE_SHARED_KEY:
if (IS_ERR(local->wep_tx_tfm))
return -EOPNOTSUPP;
auth_alg = WLAN_AUTH_SHARED_KEY;
break;
case NL80211_AUTHTYPE_FT:
auth_alg = WLAN_AUTH_FT;
break;
case NL80211_AUTHTYPE_NETWORK_EAP:
auth_alg = WLAN_AUTH_LEAP;
break;
case NL80211_AUTHTYPE_SAE:
auth_alg = WLAN_AUTH_SAE;
break;
default:
return -EOPNOTSUPP;
}
auth_data = kzalloc(sizeof(*auth_data) + req->sae_data_len +
req->ie_len, GFP_KERNEL);
if (!auth_data)
return -ENOMEM;
auth_data->bss = req->bss;
if (req->sae_data_len >= 4) {
__le16 *pos = (__le16 *) req->sae_data;
auth_data->sae_trans = le16_to_cpu(pos[0]);
auth_data->sae_status = le16_to_cpu(pos[1]);
memcpy(auth_data->data, req->sae_data + 4,
req->sae_data_len - 4);
auth_data->data_len += req->sae_data_len - 4;
}
if (req->ie && req->ie_len) {
memcpy(&auth_data->data[auth_data->data_len],
req->ie, req->ie_len);
auth_data->data_len += req->ie_len;
}
if (req->key && req->key_len) {
auth_data->key_len = req->key_len;
auth_data->key_idx = req->key_idx;
memcpy(auth_data->key, req->key, req->key_len);
}
auth_data->algorithm = auth_alg;
/* try to authenticate/probe */
if ((ifmgd->auth_data && !ifmgd->auth_data->done) ||
ifmgd->assoc_data) {
err = -EBUSY;
goto err_free;
}
if (ifmgd->auth_data)
ieee80211_destroy_auth_data(sdata, false);
/* prep auth_data so we don't go into idle on disassoc */
ifmgd->auth_data = auth_data;
if (ifmgd->associated) {
u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN];
ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH,
WLAN_REASON_UNSPECIFIED,
false, frame_buf);
cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf,
sizeof(frame_buf));
}
sdata_info(sdata, "authenticate with %pM\n", req->bss->bssid);
err = ieee80211_prep_connection(sdata, req->bss, false);
if (err)
goto err_clear;
err = ieee80211_probe_auth(sdata);
if (err) {
sta_info_destroy_addr(sdata, req->bss->bssid);
goto err_clear;
}
/* hold our own reference */
cfg80211_ref_bss(local->hw.wiphy, auth_data->bss);
return 0;
err_clear:
memset(ifmgd->bssid, 0, ETH_ALEN);
ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_BSSID);
ifmgd->auth_data = NULL;
err_free:
kfree(auth_data);
return err;
}
static bool ieee80211_usable_wmm_params(struct ieee80211_sub_if_data *sdata,
const u8 *wmm_param, int len)
{
const u8 *pos;
size_t left;
if (len < 8)
return false;
if (wmm_param[5] != 1 /* version */)
return false;
pos = wmm_param + 8;
left = len - 8;
for (; left >= 4; left -= 4, pos += 4) {
u8 aifsn = pos[0] & 0x0f;
u8 ecwmin = pos[1] & 0x0f;
u8 ecwmax = (pos[1] & 0xf0) >> 4;
int aci = (pos[0] >> 5) & 0x03;
if (aifsn < 2) {
sdata_info(sdata,
"AP has invalid WMM params (AIFSN=%d for ACI %d), disabling WMM\n",
aifsn, aci);
return false;
}
if (ecwmin > ecwmax) {
sdata_info(sdata,
"AP has invalid WMM params (ECWmin/max=%d/%d for ACI %d), disabling WMM\n",
ecwmin, ecwmax, aci);
return false;
}
}
return true;
}
int ieee80211_mgd_assoc(struct ieee80211_sub_if_data *sdata,
struct cfg80211_assoc_request *req)
{
struct ieee80211_local *local = sdata->local;
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
struct ieee80211_bss *bss = (void *)req->bss->priv;
struct ieee80211_mgd_assoc_data *assoc_data;
const struct cfg80211_bss_ies *beacon_ies;
struct ieee80211_supported_band *sband;
const u8 *ssidie, *ht_ie, *vht_ie;
int i, err;
assoc_data = kzalloc(sizeof(*assoc_data) + req->ie_len, GFP_KERNEL);
if (!assoc_data)
return -ENOMEM;
rcu_read_lock();
ssidie = ieee80211_bss_get_ie(req->bss, WLAN_EID_SSID);
if (!ssidie) {
rcu_read_unlock();
kfree(assoc_data);
return -EINVAL;
}
memcpy(assoc_data->ssid, ssidie + 2, ssidie[1]);
assoc_data->ssid_len = ssidie[1];
rcu_read_unlock();
if (ifmgd->associated) {
u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN];
ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH,
WLAN_REASON_UNSPECIFIED,
false, frame_buf);
cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf,
sizeof(frame_buf));
}
if (ifmgd->auth_data && !ifmgd->auth_data->done) {
err = -EBUSY;
goto err_free;
}
if (ifmgd->assoc_data) {
err = -EBUSY;
goto err_free;
}
if (ifmgd->auth_data) {
bool match;
/* keep sta info, bssid if matching */
match = ether_addr_equal(ifmgd->bssid, req->bss->bssid);
ieee80211_destroy_auth_data(sdata, match);
}
/* prepare assoc data */
ifmgd->beacon_crc_valid = false;
assoc_data->wmm = bss->wmm_used &&
(local->hw.queues >= IEEE80211_NUM_ACS);
if (assoc_data->wmm) {
/* try to check validity of WMM params IE */
const struct cfg80211_bss_ies *ies;
const u8 *wp, *start, *end;
rcu_read_lock();
ies = rcu_dereference(req->bss->ies);
start = ies->data;
end = start + ies->len;
while (true) {
wp = cfg80211_find_vendor_ie(
WLAN_OUI_MICROSOFT,
WLAN_OUI_TYPE_MICROSOFT_WMM,
start, end - start);
if (!wp)
break;
start = wp + wp[1] + 2;
/* if this IE is too short, try the next */
if (wp[1] <= 4)
continue;
/* if this IE is WMM params, we found what we wanted */
if (wp[6] == 1)
break;
}
if (!wp || !ieee80211_usable_wmm_params(sdata, wp + 2,
wp[1] - 2)) {
assoc_data->wmm = false;
ifmgd->flags |= IEEE80211_STA_DISABLE_WMM;
}
rcu_read_unlock();
}
/*
* IEEE802.11n does not allow TKIP/WEP as pairwise ciphers in HT mode.
* We still associate in non-HT mode (11a/b/g) if any one of these
* ciphers is configured as pairwise.
* We can set this to true for non-11n hardware, that'll be checked
* separately along with the peer capabilities.
*/
for (i = 0; i < req->crypto.n_ciphers_pairwise; i++) {
if (req->crypto.ciphers_pairwise[i] == WLAN_CIPHER_SUITE_WEP40 ||
req->crypto.ciphers_pairwise[i] == WLAN_CIPHER_SUITE_TKIP ||
req->crypto.ciphers_pairwise[i] == WLAN_CIPHER_SUITE_WEP104) {
ifmgd->flags |= IEEE80211_STA_DISABLE_HT;
ifmgd->flags |= IEEE80211_STA_DISABLE_VHT;
netdev_info(sdata->dev,
"disabling HT/VHT due to WEP/TKIP use\n");
}
}
if (req->flags & ASSOC_REQ_DISABLE_HT) {
ifmgd->flags |= IEEE80211_STA_DISABLE_HT;
ifmgd->flags |= IEEE80211_STA_DISABLE_VHT;
}
if (req->flags & ASSOC_REQ_DISABLE_VHT)
ifmgd->flags |= IEEE80211_STA_DISABLE_VHT;
/* Also disable HT if we don't support it or the AP doesn't use WMM */
sband = local->hw.wiphy->bands[req->bss->channel->band];
if (!sband->ht_cap.ht_supported ||
local->hw.queues < IEEE80211_NUM_ACS || !bss->wmm_used ||
ifmgd->flags & IEEE80211_STA_DISABLE_WMM) {
ifmgd->flags |= IEEE80211_STA_DISABLE_HT;
if (!bss->wmm_used &&
!(ifmgd->flags & IEEE80211_STA_DISABLE_WMM))
netdev_info(sdata->dev,
"disabling HT as WMM/QoS is not supported by the AP\n");
}
/* disable VHT if we don't support it or the AP doesn't use WMM */
if (!sband->vht_cap.vht_supported ||
local->hw.queues < IEEE80211_NUM_ACS || !bss->wmm_used ||
ifmgd->flags & IEEE80211_STA_DISABLE_WMM) {
ifmgd->flags |= IEEE80211_STA_DISABLE_VHT;
if (!bss->wmm_used &&
!(ifmgd->flags & IEEE80211_STA_DISABLE_WMM))
netdev_info(sdata->dev,
"disabling VHT as WMM/QoS is not supported by the AP\n");
}
memcpy(&ifmgd->ht_capa, &req->ht_capa, sizeof(ifmgd->ht_capa));
memcpy(&ifmgd->ht_capa_mask, &req->ht_capa_mask,
sizeof(ifmgd->ht_capa_mask));
memcpy(&ifmgd->vht_capa, &req->vht_capa, sizeof(ifmgd->vht_capa));
memcpy(&ifmgd->vht_capa_mask, &req->vht_capa_mask,
sizeof(ifmgd->vht_capa_mask));
if (req->ie && req->ie_len) {
memcpy(assoc_data->ie, req->ie, req->ie_len);
assoc_data->ie_len = req->ie_len;
}
assoc_data->bss = req->bss;
if (ifmgd->req_smps == IEEE80211_SMPS_AUTOMATIC) {
if (ifmgd->powersave)
sdata->smps_mode = IEEE80211_SMPS_DYNAMIC;
else
sdata->smps_mode = IEEE80211_SMPS_OFF;
} else
sdata->smps_mode = ifmgd->req_smps;
assoc_data->capability = req->bss->capability;
assoc_data->supp_rates = bss->supp_rates;
assoc_data->supp_rates_len = bss->supp_rates_len;
rcu_read_lock();
ht_ie = ieee80211_bss_get_ie(req->bss, WLAN_EID_HT_OPERATION);
if (ht_ie && ht_ie[1] >= sizeof(struct ieee80211_ht_operation))
assoc_data->ap_ht_param =
((struct ieee80211_ht_operation *)(ht_ie + 2))->ht_param;
else
ifmgd->flags |= IEEE80211_STA_DISABLE_HT;
vht_ie = ieee80211_bss_get_ie(req->bss, WLAN_EID_VHT_CAPABILITY);
if (vht_ie && vht_ie[1] >= sizeof(struct ieee80211_vht_cap))
memcpy(&assoc_data->ap_vht_cap, vht_ie + 2,
sizeof(struct ieee80211_vht_cap));
else
ifmgd->flags |= IEEE80211_STA_DISABLE_VHT;
rcu_read_unlock();
if (bss->wmm_used && bss->uapsd_supported &&
(sdata->local->hw.flags & IEEE80211_HW_SUPPORTS_UAPSD)) {
assoc_data->uapsd = true;
ifmgd->flags |= IEEE80211_STA_UAPSD_ENABLED;
} else {
assoc_data->uapsd = false;
ifmgd->flags &= ~IEEE80211_STA_UAPSD_ENABLED;
}
if (req->prev_bssid)
memcpy(assoc_data->prev_bssid, req->prev_bssid, ETH_ALEN);
if (req->use_mfp) {
ifmgd->mfp = IEEE80211_MFP_REQUIRED;
ifmgd->flags |= IEEE80211_STA_MFP_ENABLED;
} else {
ifmgd->mfp = IEEE80211_MFP_DISABLED;
ifmgd->flags &= ~IEEE80211_STA_MFP_ENABLED;
}
if (req->flags & ASSOC_REQ_USE_RRM)
ifmgd->flags |= IEEE80211_STA_ENABLE_RRM;
else
ifmgd->flags &= ~IEEE80211_STA_ENABLE_RRM;
if (req->crypto.control_port)
ifmgd->flags |= IEEE80211_STA_CONTROL_PORT;
else
ifmgd->flags &= ~IEEE80211_STA_CONTROL_PORT;
sdata->control_port_protocol = req->crypto.control_port_ethertype;
sdata->control_port_no_encrypt = req->crypto.control_port_no_encrypt;
sdata->encrypt_headroom = ieee80211_cs_headroom(local, &req->crypto,
sdata->vif.type);
/* kick off associate process */
ifmgd->assoc_data = assoc_data;
ifmgd->dtim_period = 0;
ifmgd->have_beacon = false;
err = ieee80211_prep_connection(sdata, req->bss, true);
if (err)
goto err_clear;
rcu_read_lock();
beacon_ies = rcu_dereference(req->bss->beacon_ies);
if (sdata->local->hw.flags & IEEE80211_HW_NEED_DTIM_BEFORE_ASSOC &&
!beacon_ies) {
/*
* Wait up to one beacon interval ...
* should this be more if we miss one?
*/
sdata_info(sdata, "waiting for beacon from %pM\n",
ifmgd->bssid);
assoc_data->timeout = TU_TO_EXP_TIME(req->bss->beacon_interval);
assoc_data->timeout_started = true;
assoc_data->need_beacon = true;
} else if (beacon_ies) {
const u8 *tim_ie = cfg80211_find_ie(WLAN_EID_TIM,
beacon_ies->data,
beacon_ies->len);
u8 dtim_count = 0;
if (tim_ie && tim_ie[1] >= sizeof(struct ieee80211_tim_ie)) {
const struct ieee80211_tim_ie *tim;
tim = (void *)(tim_ie + 2);
ifmgd->dtim_period = tim->dtim_period;
dtim_count = tim->dtim_count;
}
ifmgd->have_beacon = true;
assoc_data->timeout = jiffies;
assoc_data->timeout_started = true;
if (local->hw.flags & IEEE80211_HW_TIMING_BEACON_ONLY) {
sdata->vif.bss_conf.sync_tsf = beacon_ies->tsf;
sdata->vif.bss_conf.sync_device_ts =
bss->device_ts_beacon;
sdata->vif.bss_conf.sync_dtim_count = dtim_count;
}
} else {
assoc_data->timeout = jiffies;
assoc_data->timeout_started = true;
}
rcu_read_unlock();
run_again(sdata, assoc_data->timeout);
if (bss->corrupt_data) {
char *corrupt_type = "data";
if (bss->corrupt_data & IEEE80211_BSS_CORRUPT_BEACON) {
if (bss->corrupt_data &
IEEE80211_BSS_CORRUPT_PROBE_RESP)
corrupt_type = "beacon and probe response";
else
corrupt_type = "beacon";
} else if (bss->corrupt_data & IEEE80211_BSS_CORRUPT_PROBE_RESP)
corrupt_type = "probe response";
sdata_info(sdata, "associating with AP with corrupt %s\n",
corrupt_type);
}
return 0;
err_clear:
memset(ifmgd->bssid, 0, ETH_ALEN);
ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_BSSID);
ifmgd->assoc_data = NULL;
err_free:
kfree(assoc_data);
return err;
}
int ieee80211_mgd_deauth(struct ieee80211_sub_if_data *sdata,
struct cfg80211_deauth_request *req)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN];
bool tx = !req->local_state_change;
if (ifmgd->auth_data &&
ether_addr_equal(ifmgd->auth_data->bss->bssid, req->bssid)) {
sdata_info(sdata,
"aborting authentication with %pM by local choice (Reason: %u=%s)\n",
req->bssid, req->reason_code,
ieee80211_get_reason_code_string(req->reason_code));
drv_mgd_prepare_tx(sdata->local, sdata);
ieee80211_send_deauth_disassoc(sdata, req->bssid,
IEEE80211_STYPE_DEAUTH,
req->reason_code, tx,
frame_buf);
ieee80211_destroy_auth_data(sdata, false);
cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf,
IEEE80211_DEAUTH_FRAME_LEN);
return 0;
}
if (ifmgd->associated &&
ether_addr_equal(ifmgd->associated->bssid, req->bssid)) {
sdata_info(sdata,
"deauthenticating from %pM by local choice (Reason: %u=%s)\n",
req->bssid, req->reason_code,
ieee80211_get_reason_code_string(req->reason_code));
ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DEAUTH,
req->reason_code, tx, frame_buf);
cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf,
IEEE80211_DEAUTH_FRAME_LEN);
return 0;
}
return -ENOTCONN;
}
int ieee80211_mgd_disassoc(struct ieee80211_sub_if_data *sdata,
struct cfg80211_disassoc_request *req)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
u8 bssid[ETH_ALEN];
u8 frame_buf[IEEE80211_DEAUTH_FRAME_LEN];
/*
* cfg80211 should catch this ... but it's racy since
* we can receive a disassoc frame, process it, hand it
* to cfg80211 while that's in a locked section already
* trying to tell us that the user wants to disconnect.
*/
if (ifmgd->associated != req->bss)
return -ENOLINK;
sdata_info(sdata,
"disassociating from %pM by local choice (Reason: %u=%s)\n",
req->bss->bssid, req->reason_code, ieee80211_get_reason_code_string(req->reason_code));
memcpy(bssid, req->bss->bssid, ETH_ALEN);
ieee80211_set_disassoc(sdata, IEEE80211_STYPE_DISASSOC,
req->reason_code, !req->local_state_change,
frame_buf);
cfg80211_tx_mlme_mgmt(sdata->dev, frame_buf,
IEEE80211_DEAUTH_FRAME_LEN);
return 0;
}
void ieee80211_mgd_stop(struct ieee80211_sub_if_data *sdata)
{
struct ieee80211_if_managed *ifmgd = &sdata->u.mgd;
/*
* Make sure some work items will not run after this,
* they will not do anything but might not have been
* cancelled when disconnecting.
*/
cancel_work_sync(&ifmgd->monitor_work);
cancel_work_sync(&ifmgd->beacon_connection_loss_work);
cancel_work_sync(&ifmgd->request_smps_work);
cancel_work_sync(&ifmgd->csa_connection_drop_work);
cancel_work_sync(&ifmgd->chswitch_work);
cancel_delayed_work_sync(&ifmgd->tdls_peer_del_work);
sdata_lock(sdata);
if (ifmgd->assoc_data) {
struct cfg80211_bss *bss = ifmgd->assoc_data->bss;
ieee80211_destroy_assoc_data(sdata, false);
cfg80211_assoc_timeout(sdata->dev, bss);
}
if (ifmgd->auth_data)
ieee80211_destroy_auth_data(sdata, false);
del_timer_sync(&ifmgd->timer);
sdata_unlock(sdata);
}
void ieee80211_cqm_rssi_notify(struct ieee80211_vif *vif,
enum nl80211_cqm_rssi_threshold_event rssi_event,
gfp_t gfp)
{
struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif);
trace_api_cqm_rssi_notify(sdata, rssi_event);
cfg80211_cqm_rssi_notify(sdata->dev, rssi_event, gfp);
}
EXPORT_SYMBOL(ieee80211_cqm_rssi_notify);
| gpl-2.0 |
EZchip/gcc | gcc/testsuite/gcc.dg/vect/no-scevccp-outer-13.c | 126 | 1172 | /* { dg-require-effective-target vect_int } */
#include <stdarg.h>
#include "tree-vect.h"
#define N 16
unsigned short in[N];
__attribute__ ((noinline)) unsigned int
foo (short scale){
int i;
unsigned short j;
unsigned int sum = 0;
unsigned short sum_j;
for (i = 0; i < N; i++) {
sum_j = 0;
for (j = 0; j < N; j++) {
sum_j += j;
}
sum += ((unsigned int) in[i] * (unsigned int) sum_j) >> scale;
}
return sum;
}
__attribute__ ((noinline)) unsigned short
bar (void)
{
unsigned short j;
unsigned short sum_j;
sum_j = 0;
for (j = 0; j < N; j++) {
sum_j += j;
}
return sum_j;
}
int main (void)
{
int i;
unsigned short j, sum_j;
unsigned int sum = 0;
unsigned int res;
check_vect ();
for (i=0; i<N; i++){
in[i] = i;
}
res = foo (2);
/* check results: */
for (i=0; i<N; i++)
{
sum_j = bar ();
sum += ((unsigned int) in[i] * (unsigned int) sum_j) >> 2;
}
if (res != sum)
abort ();
return 0;
}
/* { dg-final { scan-tree-dump-times "OUTER LOOP VECTORIZED." 1 "vect" { target vect_widen_mult_hi_to_si } } } */
/* { dg-final { cleanup-tree-dump "vect" } } */
| gpl-2.0 |
da-anda/xbmc | lib/cximage-6.0/CxImage/ximatran.cpp | 126 | 83293 | // xImaTran.cpp : Transformation functions
/* 07/08/2001 v1.00 - Davide Pizzolato - www.xdp.it
* CxImage version 6.0.0 02/Feb/2008
*/
#include "ximage.h"
#include "ximath.h"
#if CXIMAGE_SUPPORT_BASICTRANSFORMATIONS
////////////////////////////////////////////////////////////////////////////////
bool CxImage::GrayScale()
{
if (!pDib) return false;
if (head.biBitCount<=8){
RGBQUAD* ppal=GetPalette();
int gray;
//converts the colors to gray, use the blue channel only
for(DWORD i=0;i<head.biClrUsed;i++){
gray=(int)RGB2GRAY(ppal[i].rgbRed,ppal[i].rgbGreen,ppal[i].rgbBlue);
ppal[i].rgbBlue = (BYTE)gray;
}
// preserve transparency
if (info.nBkgndIndex >= 0) info.nBkgndIndex = ppal[info.nBkgndIndex].rgbBlue;
//create a "real" 8 bit gray scale image
if (head.biBitCount==8){
BYTE *img=info.pImage;
for(DWORD i=0;i<head.biSizeImage;i++) img[i]=ppal[img[i]].rgbBlue;
SetGrayPalette();
}
//transform to 8 bit gray scale
if (head.biBitCount==4 || head.biBitCount==1){
CxImage ima;
ima.CopyInfo(*this);
if (!ima.Create(head.biWidth,head.biHeight,8,info.dwType)) return false;
ima.SetGrayPalette();
#if CXIMAGE_SUPPORT_SELECTION
ima.SelectionCopy(*this);
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
ima.AlphaCopy(*this);
#endif //CXIMAGE_SUPPORT_ALPHA
for (long y=0;y<head.biHeight;y++){
BYTE *iDst = ima.GetBits(y);
BYTE *iSrc = GetBits(y);
for (long x=0;x<head.biWidth; x++){
//iDst[x]=ppal[BlindGetPixelIndex(x,y)].rgbBlue;
if (head.biBitCount==4){
BYTE pos = (BYTE)(4*(1-x%2));
iDst[x]= ppal[(BYTE)((iSrc[x >> 1]&((BYTE)0x0F<<pos)) >> pos)].rgbBlue;
} else {
BYTE pos = (BYTE)(7-x%8);
iDst[x]= ppal[(BYTE)((iSrc[x >> 3]&((BYTE)0x01<<pos)) >> pos)].rgbBlue;
}
}
}
Transfer(ima);
}
} else { //from RGB to 8 bit gray scale
BYTE *iSrc=info.pImage;
CxImage ima;
ima.CopyInfo(*this);
if (!ima.Create(head.biWidth,head.biHeight,8,info.dwType)) return false;
ima.SetGrayPalette();
#if CXIMAGE_SUPPORT_SELECTION
ima.SelectionCopy(*this);
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
ima.AlphaCopy(*this);
#endif //CXIMAGE_SUPPORT_ALPHA
BYTE *img=ima.GetBits();
long l8=ima.GetEffWidth();
long l=head.biWidth * 3;
for(long y=0; y < head.biHeight; y++) {
for(long x=0,x8=0; x < l; x+=3,x8++) {
img[x8+y*l8]=(BYTE)RGB2GRAY(*(iSrc+x+2),*(iSrc+x+1),*(iSrc+x+0));
}
iSrc+=info.dwEffWidth;
}
Transfer(ima);
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* \sa Mirror
* \author [qhbo]
*/
bool CxImage::Flip(bool bFlipSelection, bool bFlipAlpha)
{
if (!pDib) return false;
BYTE *buff = (BYTE*)malloc(info.dwEffWidth);
if (!buff) return false;
BYTE *iSrc,*iDst;
iSrc = GetBits(head.biHeight-1);
iDst = GetBits(0);
for (long i=0; i<(head.biHeight/2); ++i)
{
memcpy(buff, iSrc, info.dwEffWidth);
memcpy(iSrc, iDst, info.dwEffWidth);
memcpy(iDst, buff, info.dwEffWidth);
iSrc-=info.dwEffWidth;
iDst+=info.dwEffWidth;
}
free(buff);
if (bFlipSelection){
#if CXIMAGE_SUPPORT_SELECTION
SelectionFlip();
#endif //CXIMAGE_SUPPORT_SELECTION
}
if (bFlipAlpha){
#if CXIMAGE_SUPPORT_ALPHA
AlphaFlip();
#endif //CXIMAGE_SUPPORT_ALPHA
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* \sa Flip
*/
bool CxImage::Mirror(bool bMirrorSelection, bool bMirrorAlpha)
{
if (!pDib) return false;
CxImage* imatmp = new CxImage(*this,false,true,true);
if (!imatmp) return false;
if (!imatmp->IsValid()){
delete imatmp;
return false;
}
BYTE *iSrc,*iDst;
long wdt=(head.biWidth-1) * (head.biBitCount==24 ? 3:1);
iSrc=info.pImage + wdt;
iDst=imatmp->info.pImage;
long x,y;
switch (head.biBitCount){
case 24:
for(y=0; y < head.biHeight; y++){
for(x=0; x <= wdt; x+=3){
*(iDst+x)=*(iSrc-x);
*(iDst+x+1)=*(iSrc-x+1);
*(iDst+x+2)=*(iSrc-x+2);
}
iSrc+=info.dwEffWidth;
iDst+=info.dwEffWidth;
}
break;
case 8:
for(y=0; y < head.biHeight; y++){
for(x=0; x <= wdt; x++)
*(iDst+x)=*(iSrc-x);
iSrc+=info.dwEffWidth;
iDst+=info.dwEffWidth;
}
break;
default:
for(y=0; y < head.biHeight; y++){
for(x=0; x <= wdt; x++)
imatmp->SetPixelIndex(x,y,GetPixelIndex(wdt-x,y));
}
}
if (bMirrorSelection){
#if CXIMAGE_SUPPORT_SELECTION
imatmp->SelectionMirror();
#endif //CXIMAGE_SUPPORT_SELECTION
}
if (bMirrorAlpha){
#if CXIMAGE_SUPPORT_ALPHA
imatmp->AlphaMirror();
#endif //CXIMAGE_SUPPORT_ALPHA
}
Transfer(*imatmp);
delete imatmp;
return true;
}
#ifdef XBMC
bool CxImage::RotateExif(int orientation /* = 0 */)
{
bool ret = true;
if (orientation <= 0)
orientation = info.ExifInfo.Orientation;
if (orientation == 3)
ret = Rotate180();
else if (orientation == 6)
ret = RotateRight();
else if (orientation == 8)
ret = RotateLeft();
else if (orientation == 5)
ret = RotateLeft();
info.ExifInfo.Orientation = 1;
return ret;
}
#endif
////////////////////////////////////////////////////////////////////////////////
#define RBLOCK 64
////////////////////////////////////////////////////////////////////////////////
bool CxImage::RotateLeft(CxImage* iDst)
{
if (!pDib) return false;
long newWidth = GetHeight();
long newHeight = GetWidth();
CxImage imgDest;
imgDest.CopyInfo(*this);
imgDest.Create(newWidth,newHeight,GetBpp(),GetType());
imgDest.SetPalette(GetPalette());
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()) imgDest.AlphaCreate();
#endif
#if CXIMAGE_SUPPORT_SELECTION
if (SelectionIsValid()) imgDest.SelectionCreate();
#endif
long x,x2,y,dlineup;
// Speedy rotate for BW images <Robert Abram>
if (head.biBitCount == 1) {
BYTE *sbits, *dbits, *dbitsmax, bitpos, *nrow,*srcdisp;
ldiv_t div_r;
BYTE *bsrc = GetBits(), *bdest = imgDest.GetBits();
dbitsmax = bdest + imgDest.head.biSizeImage - 1;
dlineup = 8 * imgDest.info.dwEffWidth - imgDest.head.biWidth;
imgDest.Clear(0);
for (y = 0; y < head.biHeight; y++) {
// Figure out the Column we are going to be copying to
div_r = ldiv(y + dlineup, (long)8);
// set bit pos of src column byte
bitpos = (BYTE)(1 << div_r.rem);
srcdisp = bsrc + y * info.dwEffWidth;
for (x = 0; x < (long)info.dwEffWidth; x++) {
// Get Source Bits
sbits = srcdisp + x;
// Get destination column
nrow = bdest + (x * 8) * imgDest.info.dwEffWidth + imgDest.info.dwEffWidth - 1 - div_r.quot;
for (long z = 0; z < 8; z++) {
// Get Destination Byte
dbits = nrow + z * imgDest.info.dwEffWidth;
if ((dbits < bdest) || (dbits > dbitsmax)) break;
if (*sbits & (128 >> z)) *dbits |= bitpos;
}
}
}//for y
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()) {
for (x = 0; x < newWidth; x++){
x2=newWidth-x-1;
for (y = 0; y < newHeight; y++){
imgDest.AlphaSet(x,y,BlindAlphaGet(y, x2));
}//for y
}//for x
}
#endif //CXIMAGE_SUPPORT_ALPHA
#if CXIMAGE_SUPPORT_SELECTION
if (SelectionIsValid()) {
imgDest.info.rSelectionBox.left = newWidth-info.rSelectionBox.top;
imgDest.info.rSelectionBox.right = newWidth-info.rSelectionBox.bottom;
imgDest.info.rSelectionBox.bottom = info.rSelectionBox.left;
imgDest.info.rSelectionBox.top = info.rSelectionBox.right;
for (x = 0; x < newWidth; x++){
x2=newWidth-x-1;
for (y = 0; y < newHeight; y++){
imgDest.SelectionSet(x,y,BlindSelectionGet(y, x2));
}//for y
}//for x
}
#endif //CXIMAGE_SUPPORT_SELECTION
} else {
//anything other than BW:
//bd, 10. 2004: This optimized version of rotation rotates image by smaller blocks. It is quite
//a bit faster than obvious algorithm, because it produces much less CPU cache misses.
//This optimization can be tuned by changing block size (RBLOCK). 96 is good value for current
//CPUs (tested on Athlon XP and Celeron D). Larger value (if CPU has enough cache) will increase
//speed somehow, but once you drop out of CPU's cache, things will slow down drastically.
//For older CPUs with less cache, lower value would yield better results.
BYTE *srcPtr, *dstPtr; //source and destionation for 24-bit version
int xs, ys; //x-segment and y-segment
for (xs = 0; xs < newWidth; xs+=RBLOCK) { //for all image blocks of RBLOCK*RBLOCK pixels
for (ys = 0; ys < newHeight; ys+=RBLOCK) {
if (head.biBitCount==24) {
//RGB24 optimized pixel access:
for (x = xs; x < min(newWidth, xs+RBLOCK); x++){ //do rotation
info.nProgress = (long)(100*x/newWidth);
x2=newWidth-x-1;
dstPtr = (BYTE*) imgDest.BlindGetPixelPointer(x,ys);
srcPtr = (BYTE*) BlindGetPixelPointer(ys, x2);
for (y = ys; y < min(newHeight, ys+RBLOCK); y++){
//imgDest.SetPixelColor(x, y, GetPixelColor(y, x2));
*(dstPtr) = *(srcPtr);
*(dstPtr+1) = *(srcPtr+1);
*(dstPtr+2) = *(srcPtr+2);
srcPtr += 3;
dstPtr += imgDest.info.dwEffWidth;
}//for y
}//for x
} else {
//anything else than 24bpp (and 1bpp): palette
for (x = xs; x < min(newWidth, xs+RBLOCK); x++){
info.nProgress = (long)(100*x/newWidth); //<Anatoly Ivasyuk>
x2=newWidth-x-1;
for (y = ys; y < min(newHeight, ys+RBLOCK); y++){
imgDest.SetPixelIndex(x, y, BlindGetPixelIndex(y, x2));
}//for y
}//for x
}//if (version selection)
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()) {
for (x = xs; x < min(newWidth, xs+RBLOCK); x++){
x2=newWidth-x-1;
for (y = ys; y < min(newHeight, ys+RBLOCK); y++){
imgDest.AlphaSet(x,y,BlindAlphaGet(y, x2));
}//for y
}//for x
}//if (alpha channel)
#endif //CXIMAGE_SUPPORT_ALPHA
#if CXIMAGE_SUPPORT_SELECTION
if (SelectionIsValid()) {
imgDest.info.rSelectionBox.left = newWidth-info.rSelectionBox.top;
imgDest.info.rSelectionBox.right = newWidth-info.rSelectionBox.bottom;
imgDest.info.rSelectionBox.bottom = info.rSelectionBox.left;
imgDest.info.rSelectionBox.top = info.rSelectionBox.right;
for (x = xs; x < min(newWidth, xs+RBLOCK); x++){
x2=newWidth-x-1;
for (y = ys; y < min(newHeight, ys+RBLOCK); y++){
imgDest.SelectionSet(x,y,BlindSelectionGet(y, x2));
}//for y
}//for x
}//if (selection)
#endif //CXIMAGE_SUPPORT_SELECTION
}//for ys
}//for xs
}//if
//select the destination
if (iDst) iDst->Transfer(imgDest);
else Transfer(imgDest);
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool CxImage::RotateRight(CxImage* iDst)
{
if (!pDib) return false;
long newWidth = GetHeight();
long newHeight = GetWidth();
CxImage imgDest;
imgDest.CopyInfo(*this);
imgDest.Create(newWidth,newHeight,GetBpp(),GetType());
imgDest.SetPalette(GetPalette());
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()) imgDest.AlphaCreate();
#endif
#if CXIMAGE_SUPPORT_SELECTION
if (SelectionIsValid()) imgDest.SelectionCreate();
#endif
long x,y,y2;
// Speedy rotate for BW images <Robert Abram>
if (head.biBitCount == 1) {
BYTE *sbits, *dbits, *dbitsmax, bitpos, *nrow,*srcdisp;
ldiv_t div_r;
BYTE *bsrc = GetBits(), *bdest = imgDest.GetBits();
dbitsmax = bdest + imgDest.head.biSizeImage - 1;
imgDest.Clear(0);
for (y = 0; y < head.biHeight; y++) {
// Figure out the Column we are going to be copying to
div_r = ldiv(y, (long)8);
// set bit pos of src column byte
bitpos = (BYTE)(128 >> div_r.rem);
srcdisp = bsrc + y * info.dwEffWidth;
for (x = 0; x < (long)info.dwEffWidth; x++) {
// Get Source Bits
sbits = srcdisp + x;
// Get destination column
nrow = bdest + (imgDest.head.biHeight-1-(x*8)) * imgDest.info.dwEffWidth + div_r.quot;
for (long z = 0; z < 8; z++) {
// Get Destination Byte
dbits = nrow - z * imgDest.info.dwEffWidth;
if ((dbits < bdest) || (dbits > dbitsmax)) break;
if (*sbits & (128 >> z)) *dbits |= bitpos;
}
}
}
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()){
for (y = 0; y < newHeight; y++){
y2=newHeight-y-1;
for (x = 0; x < newWidth; x++){
imgDest.AlphaSet(x,y,BlindAlphaGet(y2, x));
}
}
}
#endif //CXIMAGE_SUPPORT_ALPHA
#if CXIMAGE_SUPPORT_SELECTION
if (SelectionIsValid()){
imgDest.info.rSelectionBox.left = info.rSelectionBox.bottom;
imgDest.info.rSelectionBox.right = info.rSelectionBox.top;
imgDest.info.rSelectionBox.bottom = newHeight-info.rSelectionBox.right;
imgDest.info.rSelectionBox.top = newHeight-info.rSelectionBox.left;
for (y = 0; y < newHeight; y++){
y2=newHeight-y-1;
for (x = 0; x < newWidth; x++){
imgDest.SelectionSet(x,y,BlindSelectionGet(y2, x));
}
}
}
#endif //CXIMAGE_SUPPORT_SELECTION
} else {
//anything else but BW
BYTE *srcPtr, *dstPtr; //source and destionation for 24-bit version
int xs, ys; //x-segment and y-segment
for (xs = 0; xs < newWidth; xs+=RBLOCK) {
for (ys = 0; ys < newHeight; ys+=RBLOCK) {
if (head.biBitCount==24) {
//RGB24 optimized pixel access:
for (y = ys; y < min(newHeight, ys+RBLOCK); y++){
info.nProgress = (long)(100*y/newHeight); //<Anatoly Ivasyuk>
y2=newHeight-y-1;
dstPtr = (BYTE*) imgDest.BlindGetPixelPointer(xs,y);
srcPtr = (BYTE*) BlindGetPixelPointer(y2, xs);
for (x = xs; x < min(newWidth, xs+RBLOCK); x++){
//imgDest.SetPixelColor(x, y, GetPixelColor(y2, x));
*(dstPtr) = *(srcPtr);
*(dstPtr+1) = *(srcPtr+1);
*(dstPtr+2) = *(srcPtr+2);
dstPtr += 3;
srcPtr += info.dwEffWidth;
}//for x
}//for y
} else {
//anything else than BW & RGB24: palette
for (y = ys; y < min(newHeight, ys+RBLOCK); y++){
info.nProgress = (long)(100*y/newHeight); //<Anatoly Ivasyuk>
y2=newHeight-y-1;
for (x = xs; x < min(newWidth, xs+RBLOCK); x++){
imgDest.SetPixelIndex(x, y, BlindGetPixelIndex(y2, x));
}//for x
}//for y
}//if
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()){
for (y = ys; y < min(newHeight, ys+RBLOCK); y++){
y2=newHeight-y-1;
for (x = xs; x < min(newWidth, xs+RBLOCK); x++){
imgDest.AlphaSet(x,y,BlindAlphaGet(y2, x));
}//for x
}//for y
}//if (has alpha)
#endif //CXIMAGE_SUPPORT_ALPHA
#if CXIMAGE_SUPPORT_SELECTION
if (SelectionIsValid()){
imgDest.info.rSelectionBox.left = info.rSelectionBox.bottom;
imgDest.info.rSelectionBox.right = info.rSelectionBox.top;
imgDest.info.rSelectionBox.bottom = newHeight-info.rSelectionBox.right;
imgDest.info.rSelectionBox.top = newHeight-info.rSelectionBox.left;
for (y = ys; y < min(newHeight, ys+RBLOCK); y++){
y2=newHeight-y-1;
for (x = xs; x < min(newWidth, xs+RBLOCK); x++){
imgDest.SelectionSet(x,y,BlindSelectionGet(y2, x));
}//for x
}//for y
}//if (has alpha)
#endif //CXIMAGE_SUPPORT_SELECTION
}//for ys
}//for xs
}//if
//select the destination
if (iDst) iDst->Transfer(imgDest);
else Transfer(imgDest);
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool CxImage::Negative()
{
if (!pDib) return false;
if (head.biBitCount<=8){
if (IsGrayScale()){ //GRAYSCALE, selection
if (pSelection){
for(long y=info.rSelectionBox.bottom; y<info.rSelectionBox.top; y++){
for(long x=info.rSelectionBox.left; x<info.rSelectionBox.right; x++){
#if CXIMAGE_SUPPORT_SELECTION
if (BlindSelectionIsInside(x,y))
#endif //CXIMAGE_SUPPORT_SELECTION
{
BlindSetPixelIndex(x,y,(BYTE)(255-BlindGetPixelIndex(x,y)));
}
}
}
} else {
BYTE *iSrc=info.pImage;
for(unsigned long i=0; i < head.biSizeImage; i++){
*iSrc=(BYTE)~(*(iSrc));
iSrc++;
}
}
} else { //PALETTE, full image
RGBQUAD* ppal=GetPalette();
for(DWORD i=0;i<head.biClrUsed;i++){
ppal[i].rgbBlue =(BYTE)(255-ppal[i].rgbBlue);
ppal[i].rgbGreen =(BYTE)(255-ppal[i].rgbGreen);
ppal[i].rgbRed =(BYTE)(255-ppal[i].rgbRed);
}
}
} else {
if (pSelection==NULL){ //RGB, full image
BYTE *iSrc=info.pImage;
for(unsigned long i=0; i < head.biSizeImage; i++){
*iSrc=(BYTE)~(*(iSrc));
iSrc++;
}
} else { // RGB with selection
RGBQUAD color;
for(long y=info.rSelectionBox.bottom; y<info.rSelectionBox.top; y++){
for(long x=info.rSelectionBox.left; x<info.rSelectionBox.right; x++){
#if CXIMAGE_SUPPORT_SELECTION
if (BlindSelectionIsInside(x,y))
#endif //CXIMAGE_SUPPORT_SELECTION
{
color = BlindGetPixelColor(x,y);
color.rgbRed = (BYTE)(255-color.rgbRed);
color.rgbGreen = (BYTE)(255-color.rgbGreen);
color.rgbBlue = (BYTE)(255-color.rgbBlue);
BlindSetPixelColor(x,y,color);
}
}
}
}
//<DP> invert transparent color too
info.nBkgndColor.rgbBlue = (BYTE)(255-info.nBkgndColor.rgbBlue);
info.nBkgndColor.rgbGreen = (BYTE)(255-info.nBkgndColor.rgbGreen);
info.nBkgndColor.rgbRed = (BYTE)(255-info.nBkgndColor.rgbRed);
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
#endif //CXIMAGE_SUPPORT_BASICTRANSFORMATIONS
////////////////////////////////////////////////////////////////////////////////
#if CXIMAGE_SUPPORT_TRANSFORMATION
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool CxImage::Rotate(float angle, CxImage* iDst)
{
if (!pDib) return false;
// Copyright (c) 1996-1998 Ulrich von Zadow
// Negative the angle, because the y-axis is negative.
double ang = -angle*acos((float)0)/90;
int newWidth, newHeight;
int nWidth = GetWidth();
int nHeight= GetHeight();
double cos_angle = cos(ang);
double sin_angle = sin(ang);
// Calculate the size of the new bitmap
POINT p1={0,0};
POINT p2={nWidth,0};
POINT p3={0,nHeight};
POINT p4={nWidth,nHeight};
CxPoint2 newP1,newP2,newP3,newP4, leftTop, rightTop, leftBottom, rightBottom;
newP1.x = (float)p1.x;
newP1.y = (float)p1.y;
newP2.x = (float)(p2.x*cos_angle - p2.y*sin_angle);
newP2.y = (float)(p2.x*sin_angle + p2.y*cos_angle);
newP3.x = (float)(p3.x*cos_angle - p3.y*sin_angle);
newP3.y = (float)(p3.x*sin_angle + p3.y*cos_angle);
newP4.x = (float)(p4.x*cos_angle - p4.y*sin_angle);
newP4.y = (float)(p4.x*sin_angle + p4.y*cos_angle);
leftTop.x = min(min(newP1.x,newP2.x),min(newP3.x,newP4.x));
leftTop.y = min(min(newP1.y,newP2.y),min(newP3.y,newP4.y));
rightBottom.x = max(max(newP1.x,newP2.x),max(newP3.x,newP4.x));
rightBottom.y = max(max(newP1.y,newP2.y),max(newP3.y,newP4.y));
leftBottom.x = leftTop.x;
leftBottom.y = rightBottom.y;
rightTop.x = rightBottom.x;
rightTop.y = leftTop.y;
newWidth = (int) floor(0.5f + rightTop.x - leftTop.x);
newHeight= (int) floor(0.5f + leftBottom.y - leftTop.y);
CxImage imgDest;
imgDest.CopyInfo(*this);
imgDest.Create(newWidth,newHeight,GetBpp(),GetType());
imgDest.SetPalette(GetPalette());
#if CXIMAGE_SUPPORT_ALPHA
if(AlphaIsValid()) //MTA: Fix for rotation problem when the image has an alpha channel
{
imgDest.AlphaCreate();
imgDest.AlphaClear();
}
#endif //CXIMAGE_SUPPORT_ALPHA
int x,y,newX,newY,oldX,oldY;
if (head.biClrUsed==0){ //RGB
for (y = (int)leftTop.y, newY = 0; y<=(int)leftBottom.y; y++,newY++){
info.nProgress = (long)(100*newY/newHeight);
if (info.nEscape) break;
for (x = (int)leftTop.x, newX = 0; x<=(int)rightTop.x; x++,newX++){
oldX = (long)(x*cos_angle + y*sin_angle + 0.5);
oldY = (long)(y*cos_angle - x*sin_angle + 0.5);
imgDest.SetPixelColor(newX,newY,GetPixelColor(oldX,oldY));
#if CXIMAGE_SUPPORT_ALPHA
imgDest.AlphaSet(newX,newY,AlphaGet(oldX,oldY)); //MTA: copy the alpha value
#endif //CXIMAGE_SUPPORT_ALPHA
}
}
} else { //PALETTE
for (y = (int)leftTop.y, newY = 0; y<=(int)leftBottom.y; y++,newY++){
info.nProgress = (long)(100*newY/newHeight);
if (info.nEscape) break;
for (x = (int)leftTop.x, newX = 0; x<=(int)rightTop.x; x++,newX++){
oldX = (long)(x*cos_angle + y*sin_angle + 0.5);
oldY = (long)(y*cos_angle - x*sin_angle + 0.5);
imgDest.SetPixelIndex(newX,newY,GetPixelIndex(oldX,oldY));
#if CXIMAGE_SUPPORT_ALPHA
imgDest.AlphaSet(newX,newY,AlphaGet(oldX,oldY)); //MTA: copy the alpha value
#endif //CXIMAGE_SUPPORT_ALPHA
}
}
}
//select the destination
if (iDst) iDst->Transfer(imgDest);
else Transfer(imgDest);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Rotates image around it's center.
* Method can use interpolation with paletted images, but does not change pallete, so results vary.
* (If you have only four colours in a palette, there's not much room for interpolation.)
*
* \param angle - angle in degrees (positive values rotate clockwise)
* \param *iDst - destination image (if null, this image is changed)
* \param inMethod - interpolation method used
* (IM_NEAREST_NEIGHBOUR produces aliasing (fast), IM_BILINEAR softens picture a bit (slower)
* IM_SHARPBICUBIC is slower and produces some halos...)
* \param ofMethod - overflow method (how to choose colour of pixels that have no source)
* \param replColor - replacement colour to use (OM_COLOR, OM_BACKGROUND with no background colour...)
* \param optimizeRightAngles - call faster methods for 90, 180, and 270 degree rotations. Faster methods
* are called for angles, where error (in location of corner pixels) is less
* than 0.25 pixels.
* \param bKeepOriginalSize - rotates the image without resizing.
*
* \author ***bd*** 2.2004
*/
bool CxImage::Rotate2(float angle,
CxImage *iDst,
InterpolationMethod inMethod,
OverflowMethod ofMethod,
RGBQUAD *replColor,
bool const optimizeRightAngles,
bool const bKeepOriginalSize)
{
if (!pDib) return false; //no dib no go
double ang = -angle*acos(0.0f)/90.0f; //convert angle to radians and invert (positive angle performs clockwise rotation)
float cos_angle = (float) cos(ang); //these two are needed later (to rotate)
float sin_angle = (float) sin(ang);
//Calculate the size of the new bitmap (rotate corners of image)
CxPoint2 p[4]; //original corners of the image
p[0]=CxPoint2(-0.5f,-0.5f);
p[1]=CxPoint2(GetWidth()-0.5f,-0.5f);
p[2]=CxPoint2(-0.5f,GetHeight()-0.5f);
p[3]=CxPoint2(GetWidth()-0.5f,GetHeight()-0.5f);
CxPoint2 newp[4]; //rotated positions of corners
//(rotate corners)
if (bKeepOriginalSize){
for (int i=0; i<4; i++) {
newp[i].x = p[i].x;
newp[i].y = p[i].y;
}//for
} else {
for (int i=0; i<4; i++) {
newp[i].x = (p[i].x*cos_angle - p[i].y*sin_angle);
newp[i].y = (p[i].x*sin_angle + p[i].y*cos_angle);
}//for i
if (optimizeRightAngles) {
//For rotations of 90, -90 or 180 or 0 degrees, call faster routines
if (newp[3].Distance(CxPoint2(GetHeight()-0.5f, 0.5f-GetWidth())) < 0.25)
//rotation right for circa 90 degrees (diagonal pixels less than 0.25 pixel away from 90 degree rotation destination)
return RotateRight(iDst);
if (newp[3].Distance(CxPoint2(0.5f-GetHeight(), -0.5f+GetWidth())) < 0.25)
//rotation left for ~90 degrees
return RotateLeft(iDst);
if (newp[3].Distance(CxPoint2(0.5f-GetWidth(), 0.5f-GetHeight())) < 0.25)
//rotation left for ~180 degrees
return Rotate180(iDst);
if (newp[3].Distance(p[3]) < 0.25) {
//rotation not significant
if (iDst) iDst->Copy(*this); //copy image to iDst, if required
return true; //and we're done
}//if
}//if
}//if
//(read new dimensions from location of corners)
float minx = (float) min(min(newp[0].x,newp[1].x),min(newp[2].x,newp[3].x));
float miny = (float) min(min(newp[0].y,newp[1].y),min(newp[2].y,newp[3].y));
float maxx = (float) max(max(newp[0].x,newp[1].x),max(newp[2].x,newp[3].x));
float maxy = (float) max(max(newp[0].y,newp[1].y),max(newp[2].y,newp[3].y));
int newWidth = (int) floor(maxx-minx+0.5f);
int newHeight= (int) floor(maxy-miny+0.5f);
float ssx=((maxx+minx)- ((float) newWidth-1))/2.0f; //start for x
float ssy=((maxy+miny)- ((float) newHeight-1))/2.0f; //start for y
float newxcenteroffset = 0.5f * newWidth;
float newycenteroffset = 0.5f * newHeight;
if (bKeepOriginalSize){
ssx -= 0.5f * GetWidth();
ssy -= 0.5f * GetHeight();
}
//create destination image
CxImage imgDest;
imgDest.CopyInfo(*this);
imgDest.Create(newWidth,newHeight,GetBpp(),GetType());
imgDest.SetPalette(GetPalette());
#if CXIMAGE_SUPPORT_ALPHA
if(AlphaIsValid()) imgDest.AlphaCreate(); //MTA: Fix for rotation problem when the image has an alpha channel
#endif //CXIMAGE_SUPPORT_ALPHA
RGBQUAD rgb; //pixel colour
RGBQUAD rc;
if (replColor!=0)
rc=*replColor;
else {
rc.rgbRed=255; rc.rgbGreen=255; rc.rgbBlue=255; rc.rgbReserved=0;
}//if
float x,y; //destination location (float, with proper offset)
float origx, origy; //origin location
int destx, desty; //destination location
y=ssy; //initialize y
if (!IsIndexed()){ //RGB24
//optimized RGB24 implementation (direct write to destination):
BYTE *pxptr;
#if CXIMAGE_SUPPORT_ALPHA
BYTE *pxptra=0;
#endif //CXIMAGE_SUPPORT_ALPHA
for (desty=0; desty<newHeight; desty++) {
info.nProgress = (long)(100*desty/newHeight);
if (info.nEscape) break;
//initialize x
x=ssx;
//calculate pointer to first byte in row
pxptr=(BYTE *)imgDest.BlindGetPixelPointer(0, desty);
#if CXIMAGE_SUPPORT_ALPHA
//calculate pointer to first byte in row
if (AlphaIsValid()) pxptra=imgDest.AlphaGetPointer(0, desty);
#endif //CXIMAGE_SUPPORT_ALPHA
for (destx=0; destx<newWidth; destx++) {
//get source pixel coordinate for current destination point
//origx = (cos_angle*(x-head.biWidth/2)+sin_angle*(y-head.biHeight/2))+newWidth/2;
//origy = (cos_angle*(y-head.biHeight/2)-sin_angle*(x-head.biWidth/2))+newHeight/2;
origx = cos_angle*x+sin_angle*y;
origy = cos_angle*y-sin_angle*x;
if (bKeepOriginalSize){
origx += newxcenteroffset;
origy += newycenteroffset;
}
rgb = GetPixelColorInterpolated(origx, origy, inMethod, ofMethod, &rc); //get interpolated colour value
//copy alpha and colour value to destination
#if CXIMAGE_SUPPORT_ALPHA
if (pxptra) *pxptra++ = rgb.rgbReserved;
#endif //CXIMAGE_SUPPORT_ALPHA
*pxptr++ = rgb.rgbBlue;
*pxptr++ = rgb.rgbGreen;
*pxptr++ = rgb.rgbRed;
x++;
}//for destx
y++;
}//for desty
} else {
//non-optimized implementation for paletted images
for (desty=0; desty<newHeight; desty++) {
info.nProgress = (long)(100*desty/newHeight);
if (info.nEscape) break;
x=ssx;
for (destx=0; destx<newWidth; destx++) {
//get source pixel coordinate for current destination point
origx=(cos_angle*x+sin_angle*y);
origy=(cos_angle*y-sin_angle*x);
if (bKeepOriginalSize){
origx += newxcenteroffset;
origy += newycenteroffset;
}
rgb = GetPixelColorInterpolated(origx, origy, inMethod, ofMethod, &rc);
//***!*** SetPixelColor is slow for palleted images
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid())
imgDest.SetPixelColor(destx,desty,rgb,true);
else
#endif //CXIMAGE_SUPPORT_ALPHA
imgDest.SetPixelColor(destx,desty,rgb,false);
x++;
}//for destx
y++;
}//for desty
}
//select the destination
if (iDst) iDst->Transfer(imgDest);
else Transfer(imgDest);
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool CxImage::Rotate180(CxImage* iDst)
{
if (!pDib) return false;
long wid = GetWidth();
long ht = GetHeight();
CxImage imgDest;
imgDest.CopyInfo(*this);
imgDest.Create(wid,ht,GetBpp(),GetType());
imgDest.SetPalette(GetPalette());
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()) imgDest.AlphaCreate();
#endif //CXIMAGE_SUPPORT_ALPHA
long x,y,y2;
for (y = 0; y < ht; y++){
info.nProgress = (long)(100*y/ht); //<Anatoly Ivasyuk>
y2=ht-y-1;
for (x = 0; x < wid; x++){
if(head.biClrUsed==0)//RGB
imgDest.SetPixelColor(wid-x-1, y2, BlindGetPixelColor(x, y));
else //PALETTE
imgDest.SetPixelIndex(wid-x-1, y2, BlindGetPixelIndex(x, y));
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()) imgDest.AlphaSet(wid-x-1, y2,BlindAlphaGet(x, y));
#endif //CXIMAGE_SUPPORT_ALPHA
}
}
//select the destination
if (iDst) iDst->Transfer(imgDest);
else Transfer(imgDest);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Resizes the image. mode can be 0 for slow (bilinear) method ,
* 1 for fast (nearest pixel) method, or 2 for accurate (bicubic spline interpolation) method.
* The function is faster with 24 and 1 bpp images, slow for 4 bpp images and slowest for 8 bpp images.
*/
bool CxImage::Resample(long newx, long newy, int mode, CxImage* iDst)
{
if (newx==0 || newy==0) return false;
if (head.biWidth==newx && head.biHeight==newy){
if (iDst) iDst->Copy(*this);
return true;
}
float xScale, yScale, fX, fY;
xScale = (float)head.biWidth / (float)newx;
yScale = (float)head.biHeight / (float)newy;
CxImage newImage;
newImage.CopyInfo(*this);
newImage.Create(newx,newy,head.biBitCount,GetType());
newImage.SetPalette(GetPalette());
if (!newImage.IsValid()){
strcpy(info.szLastError,newImage.GetLastError());
return false;
}
switch (mode) {
case 1: // nearest pixel
{
for(long y=0; y<newy; y++){
info.nProgress = (long)(100*y/newy);
if (info.nEscape) break;
fY = y * yScale;
for(long x=0; x<newx; x++){
fX = x * xScale;
newImage.SetPixelColor(x,y,GetPixelColor((long)fX,(long)fY));
}
}
break;
}
case 2: // bicubic interpolation by Blake L. Carlson <blake-carlson(at)uiowa(dot)edu
{
float f_x, f_y, a, b, rr, gg, bb, r1, r2;
int i_x, i_y, xx, yy;
RGBQUAD rgb;
BYTE* iDst;
for(long y=0; y<newy; y++){
info.nProgress = (long)(100*y/newy);
if (info.nEscape) break;
f_y = (float) y * yScale - 0.5f;
i_y = (int) floor(f_y);
a = f_y - (float)floor(f_y);
for(long x=0; x<newx; x++){
f_x = (float) x * xScale - 0.5f;
i_x = (int) floor(f_x);
b = f_x - (float)floor(f_x);
rr = gg = bb = 0.0f;
for(int m=-1; m<3; m++) {
r1 = KernelBSpline((float) m - a);
yy = i_y+m;
if (yy<0) yy=0;
if (yy>=head.biHeight) yy = head.biHeight-1;
for(int n=-1; n<3; n++) {
r2 = r1 * KernelBSpline(b - (float)n);
xx = i_x+n;
if (xx<0) xx=0;
if (xx>=head.biWidth) xx=head.biWidth-1;
if (head.biClrUsed){
rgb = GetPixelColor(xx,yy);
} else {
iDst = info.pImage + yy*info.dwEffWidth + xx*3;
rgb.rgbBlue = *iDst++;
rgb.rgbGreen= *iDst++;
rgb.rgbRed = *iDst;
}
rr += rgb.rgbRed * r2;
gg += rgb.rgbGreen * r2;
bb += rgb.rgbBlue * r2;
}
}
if (head.biClrUsed)
newImage.SetPixelColor(x,y,RGB(rr,gg,bb));
else {
iDst = newImage.info.pImage + y*newImage.info.dwEffWidth + x*3;
*iDst++ = (BYTE)bb;
*iDst++ = (BYTE)gg;
*iDst = (BYTE)rr;
}
}
}
break;
}
default: // bilinear interpolation
if (!(head.biWidth>newx && head.biHeight>newy && head.biBitCount==24)) {
// (c) 1999 Steve McMahon (steve@dogma.demon.co.uk)
long ifX, ifY, ifX1, ifY1, xmax, ymax;
float ir1, ir2, ig1, ig2, ib1, ib2, dx, dy;
BYTE r,g,b;
RGBQUAD rgb1, rgb2, rgb3, rgb4;
xmax = head.biWidth-1;
ymax = head.biHeight-1;
for(long y=0; y<newy; y++){
info.nProgress = (long)(100*y/newy);
if (info.nEscape) break;
fY = y * yScale;
ifY = (int)fY;
ifY1 = min(ymax, ifY+1);
dy = fY - ifY;
for(long x=0; x<newx; x++){
fX = x * xScale;
ifX = (int)fX;
ifX1 = min(xmax, ifX+1);
dx = fX - ifX;
// Interpolate using the four nearest pixels in the source
if (head.biClrUsed){
rgb1=GetPaletteColor(GetPixelIndex(ifX,ifY));
rgb2=GetPaletteColor(GetPixelIndex(ifX1,ifY));
rgb3=GetPaletteColor(GetPixelIndex(ifX,ifY1));
rgb4=GetPaletteColor(GetPixelIndex(ifX1,ifY1));
}
else {
BYTE* iDst;
iDst = info.pImage + ifY*info.dwEffWidth + ifX*3;
rgb1.rgbBlue = *iDst++; rgb1.rgbGreen= *iDst++; rgb1.rgbRed =*iDst;
iDst = info.pImage + ifY*info.dwEffWidth + ifX1*3;
rgb2.rgbBlue = *iDst++; rgb2.rgbGreen= *iDst++; rgb2.rgbRed =*iDst;
iDst = info.pImage + ifY1*info.dwEffWidth + ifX*3;
rgb3.rgbBlue = *iDst++; rgb3.rgbGreen= *iDst++; rgb3.rgbRed =*iDst;
iDst = info.pImage + ifY1*info.dwEffWidth + ifX1*3;
rgb4.rgbBlue = *iDst++; rgb4.rgbGreen= *iDst++; rgb4.rgbRed =*iDst;
}
// Interplate in x direction:
ir1 = rgb1.rgbRed + (rgb3.rgbRed - rgb1.rgbRed) * dy;
ig1 = rgb1.rgbGreen + (rgb3.rgbGreen - rgb1.rgbGreen) * dy;
ib1 = rgb1.rgbBlue + (rgb3.rgbBlue - rgb1.rgbBlue) * dy;
ir2 = rgb2.rgbRed + (rgb4.rgbRed - rgb2.rgbRed) * dy;
ig2 = rgb2.rgbGreen + (rgb4.rgbGreen - rgb2.rgbGreen) * dy;
ib2 = rgb2.rgbBlue + (rgb4.rgbBlue - rgb2.rgbBlue) * dy;
// Interpolate in y:
r = (BYTE)(ir1 + (ir2-ir1) * dx);
g = (BYTE)(ig1 + (ig2-ig1) * dx);
b = (BYTE)(ib1 + (ib2-ib1) * dx);
// Set output
newImage.SetPixelColor(x,y,RGB(r,g,b));
}
}
} else {
//high resolution shrink, thanks to Henrik Stellmann <henrik.stellmann@volleynet.de>
const long ACCURACY = 1000;
long i,j; // index for faValue
long x,y; // coordinates in source image
BYTE* pSource;
BYTE* pDest = newImage.info.pImage;
long* naAccu = new long[3 * newx + 3];
long* naCarry = new long[3 * newx + 3];
long* naTemp;
long nWeightX,nWeightY;
float fEndX;
long nScale = (long)(ACCURACY * xScale * yScale);
memset(naAccu, 0, sizeof(long) * 3 * newx);
memset(naCarry, 0, sizeof(long) * 3 * newx);
int u, v = 0; // coordinates in dest image
float fEndY = yScale - 1.0f;
for (y = 0; y < head.biHeight; y++){
info.nProgress = (long)(100*y/head.biHeight); //<Anatoly Ivasyuk>
if (info.nEscape) break;
pSource = info.pImage + y * info.dwEffWidth;
u = i = 0;
fEndX = xScale - 1.0f;
if ((float)y < fEndY) { // complete source row goes into dest row
for (x = 0; x < head.biWidth; x++){
if ((float)x < fEndX){ // complete source pixel goes into dest pixel
for (j = 0; j < 3; j++) naAccu[i + j] += (*pSource++) * ACCURACY;
} else { // source pixel is splitted for 2 dest pixels
nWeightX = (long)(((float)x - fEndX) * ACCURACY);
for (j = 0; j < 3; j++){
naAccu[i] += (ACCURACY - nWeightX) * (*pSource);
naAccu[3 + i++] += nWeightX * (*pSource++);
}
fEndX += xScale;
u++;
}
}
} else { // source row is splitted for 2 dest rows
nWeightY = (long)(((float)y - fEndY) * ACCURACY);
for (x = 0; x < head.biWidth; x++){
if ((float)x < fEndX){ // complete source pixel goes into 2 pixel
for (j = 0; j < 3; j++){
naAccu[i + j] += ((ACCURACY - nWeightY) * (*pSource));
naCarry[i + j] += nWeightY * (*pSource++);
}
} else { // source pixel is splitted for 4 dest pixels
nWeightX = (int)(((float)x - fEndX) * ACCURACY);
for (j = 0; j < 3; j++) {
naAccu[i] += ((ACCURACY - nWeightY) * (ACCURACY - nWeightX)) * (*pSource) / ACCURACY;
*pDest++ = (BYTE)(naAccu[i] / nScale);
naCarry[i] += (nWeightY * (ACCURACY - nWeightX) * (*pSource)) / ACCURACY;
naAccu[i + 3] += ((ACCURACY - nWeightY) * nWeightX * (*pSource)) / ACCURACY;
naCarry[i + 3] = (nWeightY * nWeightX * (*pSource)) / ACCURACY;
i++;
pSource++;
}
fEndX += xScale;
u++;
}
}
if (u < newx){ // possibly not completed due to rounding errors
for (j = 0; j < 3; j++) *pDest++ = (BYTE)(naAccu[i++] / nScale);
}
naTemp = naCarry;
naCarry = naAccu;
naAccu = naTemp;
memset(naCarry, 0, sizeof(long) * 3); // need only to set first pixel zero
pDest = newImage.info.pImage + (++v * newImage.info.dwEffWidth);
fEndY += yScale;
}
}
if (v < newy){ // possibly not completed due to rounding errors
for (i = 0; i < 3 * newx; i++) *pDest++ = (BYTE)(naAccu[i] / nScale);
}
delete [] naAccu;
delete [] naCarry;
}
}
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()){
newImage.AlphaCreate();
for(long y=0; y<newy; y++){
fY = y * yScale;
for(long x=0; x<newx; x++){
fX = x * xScale;
newImage.AlphaSet(x,y,AlphaGet((long)fX,(long)fY));
}
}
}
#endif //CXIMAGE_SUPPORT_ALPHA
//select the destination
if (iDst) iDst->Transfer(newImage);
else Transfer(newImage);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* New simpler resample. Adds new interpolation methods and simplifies code (using GetPixelColorInterpolated
* and GetAreaColorInterpolated). It also (unlike old method) interpolates alpha layer.
*
* \param newx, newy - size of resampled image
* \param inMethod - interpolation method to use (see comments at GetPixelColorInterpolated)
* If image size is being reduced, averaging is used instead (or simultaneously with) inMethod.
* \param ofMethod - what to replace outside pixels by (only significant for bordering pixels of enlarged image)
* \param iDst - pointer to destination CxImage or NULL.
* \param disableAveraging - force no averaging when shrinking images (Produces aliasing.
* You probably just want to leave this off...)
*
* \author ***bd*** 2.2004
*/
bool CxImage::Resample2(
long newx, long newy,
InterpolationMethod const inMethod,
OverflowMethod const ofMethod,
CxImage* const iDst,
bool const disableAveraging)
{
if (newx<=0 || newy<=0 || !pDib) return false;
if (head.biWidth==newx && head.biHeight==newy) {
//image already correct size (just copy and return)
if (iDst) iDst->Copy(*this);
return true;
}//if
//calculate scale of new image (less than 1 for enlarge)
float xScale, yScale;
xScale = (float)head.biWidth / (float)newx;
yScale = (float)head.biHeight / (float)newy;
//create temporary destination image
CxImage newImage;
newImage.CopyInfo(*this);
newImage.Create(newx,newy,head.biBitCount,GetType());
newImage.SetPalette(GetPalette());
if (!newImage.IsValid()){
strcpy(info.szLastError,newImage.GetLastError());
return false;
}
//and alpha channel if required
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()) newImage.AlphaCreate();
BYTE *pxptra = 0; // destination alpha data
#endif
float sX, sY; //source location
long dX,dY; //destination pixel (int value)
if ((xScale<=1 && yScale<=1) || disableAveraging) {
//image is being enlarged (or interpolation on demand)
if (!IsIndexed()) {
//RGB24 image (optimized version with direct writes)
RGBQUAD q; //pixel colour
BYTE *pxptr; //pointer to destination pixel
for(dY=0; dY<newy; dY++){
info.nProgress = (long)(100*dY/newy);
if (info.nEscape) break;
sY = (dY + 0.5f) * yScale - 0.5f;
pxptr=(BYTE*)(newImage.BlindGetPixelPointer(0,dY));
#if CXIMAGE_SUPPORT_ALPHA
pxptra=newImage.AlphaGetPointer(0,dY);
#endif
for(dX=0; dX<newx; dX++){
sX = (dX + 0.5f) * xScale - 0.5f;
q=GetPixelColorInterpolated(sX,sY,inMethod,ofMethod,0);
*pxptr++=q.rgbBlue;
*pxptr++=q.rgbGreen;
*pxptr++=q.rgbRed;
#if CXIMAGE_SUPPORT_ALPHA
if (pxptra) *pxptra++=q.rgbReserved;
#endif
}//for dX
}//for dY
} else {
//enlarge paletted image. Slower method.
for(dY=0; dY<newy; dY++){
info.nProgress = (long)(100*dY/newy);
if (info.nEscape) break;
sY = (dY + 0.5f) * yScale - 0.5f;
for(dX=0; dX<newx; dX++){
sX = (dX + 0.5f) * xScale - 0.5f;
newImage.SetPixelColor(dX,dY,GetPixelColorInterpolated(sX,sY,inMethod,ofMethod,0),true);
}//for x
}//for y
}//if
} else {
//image size is being reduced (averaging enabled)
for(dY=0; dY<newy; dY++){
info.nProgress = (long)(100*dY/newy); if (info.nEscape) break;
sY = (dY+0.5f) * yScale - 0.5f;
for(dX=0; dX<newx; dX++){
sX = (dX+0.5f) * xScale - 0.5f;
newImage.SetPixelColor(dX,dY,GetAreaColorInterpolated(sX, sY, xScale, yScale, inMethod, ofMethod,0),true);
}//for x
}//for y
}//if
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid() && pxptra == 0){
for(long y=0; y<newy; y++){
dY = (long)(y * yScale);
for(long x=0; x<newx; x++){
dX = (long)(x * xScale);
newImage.AlphaSet(x,y,AlphaGet(dX,dY));
}
}
}
#endif //CXIMAGE_SUPPORT_ALPHA
//copy new image to the destination
if (iDst)
iDst->Transfer(newImage);
else
Transfer(newImage);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Reduces the number of bits per pixel to nbit (1, 4 or 8).
* ppal points to a valid palette for the final image; if not supplied the function will use a standard palette.
* ppal is not necessary for reduction to 1 bpp.
*/
bool CxImage::DecreaseBpp(DWORD nbit, bool errordiffusion, RGBQUAD* ppal, DWORD clrimportant)
{
if (!pDib) return false;
if (head.biBitCount < nbit){
strcpy(info.szLastError,"DecreaseBpp: target BPP greater than source BPP");
return false;
}
if (head.biBitCount == nbit){
if (clrimportant==0) return true;
if (head.biClrImportant && (head.biClrImportant<clrimportant)) return true;
}
long er,eg,eb;
RGBQUAD c,ce;
CxImage tmp;
tmp.CopyInfo(*this);
tmp.Create(head.biWidth,head.biHeight,(WORD)nbit,info.dwType);
if (clrimportant) tmp.SetClrImportant(clrimportant);
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
#if CXIMAGE_SUPPORT_SELECTION
tmp.SelectionCopy(*this);
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
tmp.AlphaCopy(*this);
#endif //CXIMAGE_SUPPORT_ALPHA
if (ppal) {
if (clrimportant) {
tmp.SetPalette(ppal,clrimportant);
} else {
tmp.SetPalette(ppal,1<<tmp.head.biBitCount);
}
} else {
tmp.SetStdPalette();
}
for (long y=0;y<head.biHeight;y++){
if (info.nEscape) break;
info.nProgress = (long)(100*y/head.biHeight);
for (long x=0;x<head.biWidth;x++){
if (!errordiffusion){
tmp.BlindSetPixelColor(x,y,BlindGetPixelColor(x,y));
} else {
c = BlindGetPixelColor(x,y);
tmp.BlindSetPixelColor(x,y,c);
ce = tmp.BlindGetPixelColor(x,y);
er=(long)c.rgbRed - (long)ce.rgbRed;
eg=(long)c.rgbGreen - (long)ce.rgbGreen;
eb=(long)c.rgbBlue - (long)ce.rgbBlue;
c = GetPixelColor(x+1,y);
c.rgbRed = (BYTE)min(255L,max(0L,(long)c.rgbRed + ((er*7)/16)));
c.rgbGreen = (BYTE)min(255L,max(0L,(long)c.rgbGreen + ((eg*7)/16)));
c.rgbBlue = (BYTE)min(255L,max(0L,(long)c.rgbBlue + ((eb*7)/16)));
SetPixelColor(x+1,y,c);
int coeff=1;
for(int i=-1; i<2; i++){
switch(i){
case -1:
coeff=2; break;
case 0:
coeff=4; break;
case 1:
coeff=1; break;
}
c = GetPixelColor(x+i,y+1);
c.rgbRed = (BYTE)min(255L,max(0L,(long)c.rgbRed + ((er * coeff)/16)));
c.rgbGreen = (BYTE)min(255L,max(0L,(long)c.rgbGreen + ((eg * coeff)/16)));
c.rgbBlue = (BYTE)min(255L,max(0L,(long)c.rgbBlue + ((eb * coeff)/16)));
SetPixelColor(x+i,y+1,c);
}
}
}
}
Transfer(tmp);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Increases the number of bits per pixel of the image.
* \param nbit: 4, 8, 24
*/
bool CxImage::IncreaseBpp(DWORD nbit)
{
if (!pDib) return false;
switch (nbit){
case 4:
{
if (head.biBitCount==4) return true;
if (head.biBitCount>4) return false;
CxImage tmp;
tmp.CopyInfo(*this);
tmp.Create(head.biWidth,head.biHeight,4,info.dwType);
tmp.SetPalette(GetPalette(),GetNumColors());
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
#if CXIMAGE_SUPPORT_SELECTION
tmp.SelectionCopy(*this);
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
tmp.AlphaCopy(*this);
#endif //CXIMAGE_SUPPORT_ALPHA
for (long y=0;y<head.biHeight;y++){
if (info.nEscape) break;
for (long x=0;x<head.biWidth;x++){
tmp.BlindSetPixelIndex(x,y,BlindGetPixelIndex(x,y));
}
}
Transfer(tmp);
return true;
}
case 8:
{
if (head.biBitCount==8) return true;
if (head.biBitCount>8) return false;
CxImage tmp;
tmp.CopyInfo(*this);
tmp.Create(head.biWidth,head.biHeight,8,info.dwType);
tmp.SetPalette(GetPalette(),GetNumColors());
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
#if CXIMAGE_SUPPORT_SELECTION
tmp.SelectionCopy(*this);
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
tmp.AlphaCopy(*this);
#endif //CXIMAGE_SUPPORT_ALPHA
for (long y=0;y<head.biHeight;y++){
if (info.nEscape) break;
for (long x=0;x<head.biWidth;x++){
tmp.BlindSetPixelIndex(x,y,BlindGetPixelIndex(x,y));
}
}
Transfer(tmp);
return true;
}
case 24:
{
if (head.biBitCount==24) return true;
if (head.biBitCount>24) return false;
CxImage tmp;
tmp.CopyInfo(*this);
tmp.Create(head.biWidth,head.biHeight,24,info.dwType);
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
if (info.nBkgndIndex>=0) //translate transparency
tmp.info.nBkgndColor=GetPaletteColor((BYTE)info.nBkgndIndex);
#if CXIMAGE_SUPPORT_SELECTION
tmp.SelectionCopy(*this);
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
tmp.AlphaCopy(*this);
if (AlphaPaletteIsValid() && !AlphaIsValid()) tmp.AlphaCreate();
#endif //CXIMAGE_SUPPORT_ALPHA
for (long y=0;y<head.biHeight;y++){
if (info.nEscape) break;
for (long x=0;x<head.biWidth;x++){
tmp.BlindSetPixelColor(x,y,BlindGetPixelColor(x,y),true);
}
}
Transfer(tmp);
return true;
}
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Converts the image to B&W using the desired method :
* - 0 = Floyd-Steinberg
* - 1 = Ordered-Dithering (4x4)
* - 2 = Burkes
* - 3 = Stucki
* - 4 = Jarvis-Judice-Ninke
* - 5 = Sierra
* - 6 = Stevenson-Arce
* - 7 = Bayer (4x4 ordered dithering)
*/
bool CxImage::Dither(long method)
{
if (!pDib) return false;
if (head.biBitCount == 1) return true;
GrayScale();
CxImage tmp;
tmp.CopyInfo(*this);
tmp.Create(head.biWidth, head.biHeight, 1, info.dwType);
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
#if CXIMAGE_SUPPORT_SELECTION
tmp.SelectionCopy(*this);
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
tmp.AlphaCopy(*this);
#endif //CXIMAGE_SUPPORT_ALPHA
switch (method){
case 1:
{
// Multi-Level Ordered-Dithering by Kenny Hoff (Oct. 12, 1995)
#define dth_NumRows 4
#define dth_NumCols 4
#define dth_NumIntensityLevels 2
#define dth_NumRowsLessOne (dth_NumRows-1)
#define dth_NumColsLessOne (dth_NumCols-1)
#define dth_RowsXCols (dth_NumRows*dth_NumCols)
#define dth_MaxIntensityVal 255
#define dth_MaxDitherIntensityVal (dth_NumRows*dth_NumCols*(dth_NumIntensityLevels-1))
int DitherMatrix[dth_NumRows][dth_NumCols] = {{0,8,2,10}, {12,4,14,6}, {3,11,1,9}, {15,7,13,5} };
unsigned char Intensity[dth_NumIntensityLevels] = { 0,1 }; // 2 LEVELS B/W
//unsigned char Intensity[NumIntensityLevels] = { 0,255 }; // 2 LEVELS
//unsigned char Intensity[NumIntensityLevels] = { 0,127,255 }; // 3 LEVELS
//unsigned char Intensity[NumIntensityLevels] = { 0,85,170,255 }; // 4 LEVELS
//unsigned char Intensity[NumIntensityLevels] = { 0,63,127,191,255 }; // 5 LEVELS
//unsigned char Intensity[NumIntensityLevels] = { 0,51,102,153,204,255 }; // 6 LEVELS
//unsigned char Intensity[NumIntensityLevels] = { 0,42,85,127,170,213,255 }; // 7 LEVELS
//unsigned char Intensity[NumIntensityLevels] = { 0,36,73,109,145,182,219,255 }; // 8 LEVELS
int DitherIntensity, DitherMatrixIntensity, Offset, DeviceIntensity;
unsigned char DitherValue;
for (long y=0;y<head.biHeight;y++){
info.nProgress = (long)(100*y/head.biHeight);
if (info.nEscape) break;
for (long x=0;x<head.biWidth;x++){
DeviceIntensity = BlindGetPixelIndex(x,y);
DitherIntensity = DeviceIntensity*dth_MaxDitherIntensityVal/dth_MaxIntensityVal;
DitherMatrixIntensity = DitherIntensity % dth_RowsXCols;
Offset = DitherIntensity / dth_RowsXCols;
if (DitherMatrix[y&dth_NumRowsLessOne][x&dth_NumColsLessOne] < DitherMatrixIntensity)
DitherValue = Intensity[1+Offset];
else
DitherValue = Intensity[0+Offset];
tmp.BlindSetPixelIndex(x,y,DitherValue);
}
}
break;
}
case 2:
{
//Burkes error diffusion (Thanks to Franco Gerevini)
int TotalCoeffSum = 32;
long error, nlevel, coeff=1;
BYTE level;
for (long y = 0; y < head.biHeight; y++) {
info.nProgress = (long)(100 * y / head.biHeight);
if (info.nEscape)
break;
for (long x = 0; x < head.biWidth; x++) {
level = BlindGetPixelIndex(x, y);
if (level > 128) {
tmp.SetPixelIndex(x, y, 1);
error = level - 255;
} else {
tmp.SetPixelIndex(x, y, 0);
error = level;
}
nlevel = GetPixelIndex(x + 1, y) + (error * 8) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + 1, y, level);
nlevel = GetPixelIndex(x + 2, y) + (error * 4) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + 2, y, level);
int i;
for (i = -2; i < 3; i++) {
switch (i) {
case -2:
coeff = 2;
break;
case -1:
coeff = 4;
break;
case 0:
coeff = 8;
break;
case 1:
coeff = 4;
break;
case 2:
coeff = 2;
break;
}
nlevel = GetPixelIndex(x + i, y + 1) + (error * coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + i, y + 1, level);
}
}
}
break;
}
case 3:
{
//Stucki error diffusion (Thanks to Franco Gerevini)
int TotalCoeffSum = 42;
long error, nlevel, coeff=1;
BYTE level;
for (long y = 0; y < head.biHeight; y++) {
info.nProgress = (long)(100 * y / head.biHeight);
if (info.nEscape)
break;
for (long x = 0; x < head.biWidth; x++) {
level = BlindGetPixelIndex(x, y);
if (level > 128) {
tmp.SetPixelIndex(x, y, 1);
error = level - 255;
} else {
tmp.SetPixelIndex(x, y, 0);
error = level;
}
nlevel = GetPixelIndex(x + 1, y) + (error * 8) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + 1, y, level);
nlevel = GetPixelIndex(x + 2, y) + (error * 4) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + 2, y, level);
int i;
for (i = -2; i < 3; i++) {
switch (i) {
case -2:
coeff = 2;
break;
case -1:
coeff = 4;
break;
case 0:
coeff = 8;
break;
case 1:
coeff = 4;
break;
case 2:
coeff = 2;
break;
}
nlevel = GetPixelIndex(x + i, y + 1) + (error * coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + i, y + 1, level);
}
for (i = -2; i < 3; i++) {
switch (i) {
case -2:
coeff = 1;
break;
case -1:
coeff = 2;
break;
case 0:
coeff = 4;
break;
case 1:
coeff = 2;
break;
case 2:
coeff = 1;
break;
}
nlevel = GetPixelIndex(x + i, y + 2) + (error * coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + i, y + 2, level);
}
}
}
break;
}
case 4:
{
//Jarvis, Judice and Ninke error diffusion (Thanks to Franco Gerevini)
int TotalCoeffSum = 48;
long error, nlevel, coeff=1;
BYTE level;
for (long y = 0; y < head.biHeight; y++) {
info.nProgress = (long)(100 * y / head.biHeight);
if (info.nEscape)
break;
for (long x = 0; x < head.biWidth; x++) {
level = BlindGetPixelIndex(x, y);
if (level > 128) {
tmp.SetPixelIndex(x, y, 1);
error = level - 255;
} else {
tmp.SetPixelIndex(x, y, 0);
error = level;
}
nlevel = GetPixelIndex(x + 1, y) + (error * 7) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + 1, y, level);
nlevel = GetPixelIndex(x + 2, y) + (error * 5) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + 2, y, level);
int i;
for (i = -2; i < 3; i++) {
switch (i) {
case -2:
coeff = 3;
break;
case -1:
coeff = 5;
break;
case 0:
coeff = 7;
break;
case 1:
coeff = 5;
break;
case 2:
coeff = 3;
break;
}
nlevel = GetPixelIndex(x + i, y + 1) + (error * coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + i, y + 1, level);
}
for (i = -2; i < 3; i++) {
switch (i) {
case -2:
coeff = 1;
break;
case -1:
coeff = 3;
break;
case 0:
coeff = 5;
break;
case 1:
coeff = 3;
break;
case 2:
coeff = 1;
break;
}
nlevel = GetPixelIndex(x + i, y + 2) + (error * coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + i, y + 2, level);
}
}
}
break;
}
case 5:
{
//Sierra error diffusion (Thanks to Franco Gerevini)
int TotalCoeffSum = 32;
long error, nlevel, coeff=1;
BYTE level;
for (long y = 0; y < head.biHeight; y++) {
info.nProgress = (long)(100 * y / head.biHeight);
if (info.nEscape)
break;
for (long x = 0; x < head.biWidth; x++) {
level = BlindGetPixelIndex(x, y);
if (level > 128) {
tmp.SetPixelIndex(x, y, 1);
error = level - 255;
} else {
tmp.SetPixelIndex(x, y, 0);
error = level;
}
nlevel = GetPixelIndex(x + 1, y) + (error * 5) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + 1, y, level);
nlevel = GetPixelIndex(x + 2, y) + (error * 3) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + 2, y, level);
int i;
for (i = -2; i < 3; i++) {
switch (i) {
case -2:
coeff = 2;
break;
case -1:
coeff = 4;
break;
case 0:
coeff = 5;
break;
case 1:
coeff = 4;
break;
case 2:
coeff = 2;
break;
}
nlevel = GetPixelIndex(x + i, y + 1) + (error * coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + i, y + 1, level);
}
for (i = -1; i < 2; i++) {
switch (i) {
case -1:
coeff = 2;
break;
case 0:
coeff = 3;
break;
case 1:
coeff = 2;
break;
}
nlevel = GetPixelIndex(x + i, y + 2) + (error * coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(x + i, y + 2, level);
}
}
}
break;
}
case 6:
{
//Stevenson and Arce error diffusion (Thanks to Franco Gerevini)
int TotalCoeffSum = 200;
long error, nlevel;
BYTE level;
for (long y = 0; y < head.biHeight; y++) {
info.nProgress = (long)(100 * y / head.biHeight);
if (info.nEscape)
break;
for (long x = 0; x < head.biWidth; x++) {
level = BlindGetPixelIndex(x, y);
if (level > 128) {
tmp.SetPixelIndex(x, y, 1);
error = level - 255;
} else {
tmp.SetPixelIndex(x, y, 0);
error = level;
}
int tmp_index_x = x + 2;
int tmp_index_y = y;
int tmp_coeff = 32;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x - 3;
tmp_index_y = y + 1;
tmp_coeff = 12;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x - 1;
tmp_coeff = 26;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x + 1;
tmp_coeff = 30;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x + 3;
tmp_coeff = 16;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x - 2;
tmp_index_y = y + 2;
tmp_coeff = 12;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x;
tmp_coeff = 26;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x + 2;
tmp_coeff = 12;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x - 3;
tmp_index_y = y + 3;
tmp_coeff = 5;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x - 1;
tmp_coeff = 12;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x + 1;
tmp_coeff = 12;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
tmp_index_x = x + 3;
tmp_coeff = 5;
nlevel = GetPixelIndex(tmp_index_x, tmp_index_y) + (error * tmp_coeff) / TotalCoeffSum;
level = (BYTE)min(255, max(0, (int)nlevel));
SetPixelIndex(tmp_index_x, tmp_index_y, level);
}
}
break;
}
case 7:
{
// Bayer ordered dither
int order = 4;
//create Bayer matrix
if (order>4) order = 4;
int size = (1 << (2*order));
BYTE* Bmatrix = (BYTE*) malloc(size * sizeof(BYTE));
for(int i = 0; i < size; i++) {
int n = order;
int x = i / n;
int y = i % n;
int dither = 0;
while (n-- > 0){
dither = (((dither<<1)|((x&1) ^ (y&1)))<<1) | (y&1);
x >>= 1;
y >>= 1;
}
Bmatrix[i] = (BYTE)(dither);
}
int scale = max(0,(8-2*order));
int level;
for (long y=0;y<head.biHeight;y++){
info.nProgress = (long)(100*y/head.biHeight);
if (info.nEscape) break;
for (long x=0;x<head.biWidth;x++){
level = BlindGetPixelIndex(x,y) >> scale;
if(level > Bmatrix[ (x % order) + order * (y % order) ]){
tmp.SetPixelIndex(x,y,1);
} else {
tmp.SetPixelIndex(x,y,0);
}
}
}
free(Bmatrix);
break;
}
default:
{
// Floyd-Steinberg error diffusion (Thanks to Steve McMahon)
long error,nlevel,coeff=1;
BYTE level;
for (long y=0;y<head.biHeight;y++){
info.nProgress = (long)(100*y/head.biHeight);
if (info.nEscape) break;
for (long x=0;x<head.biWidth;x++){
level = BlindGetPixelIndex(x,y);
if (level > 128){
tmp.SetPixelIndex(x,y,1);
error = level-255;
} else {
tmp.SetPixelIndex(x,y,0);
error = level;
}
nlevel = GetPixelIndex(x+1,y) + (error * 7)/16;
level = (BYTE)min(255,max(0,(int)nlevel));
SetPixelIndex(x+1,y,level);
for(int i=-1; i<2; i++){
switch(i){
case -1:
coeff=3; break;
case 0:
coeff=5; break;
case 1:
coeff=1; break;
}
nlevel = GetPixelIndex(x+i,y+1) + (error * coeff)/16;
level = (BYTE)min(255,max(0,(int)nlevel));
SetPixelIndex(x+i,y+1,level);
}
}
}
}
}
tmp.SetPaletteColor(0,0,0,0);
tmp.SetPaletteColor(1,255,255,255);
Transfer(tmp);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* CropRotatedRectangle
* \param topx,topy : topmost and leftmost point of the rectangle
(topmost, and if there are 2 topmost points, the left one)
* \param width : size of the right hand side of rect, from (topx,topy) roundwalking clockwise
* \param height : size of the left hand side of rect, from (topx,topy) roundwalking clockwise
* \param angle : angle of the right hand side of rect, from (topx,topy)
* \param iDst : pointer to destination image (if 0, this image is modified)
* \author [VATI]
*/
bool CxImage::CropRotatedRectangle( long topx, long topy, long width, long height, float angle, CxImage* iDst)
{
if (!pDib) return false;
long startx,starty,endx,endy;
double cos_angle = cos(angle/*/57.295779513082320877*/);
double sin_angle = sin(angle/*/57.295779513082320877*/);
// if there is nothing special, call the original Crop():
if ( fabs(angle)<0.0002 )
return Crop( topx, topy, topx+width, topy+height, iDst);
startx = min(topx, topx - (long)(sin_angle*(double)height));
endx = topx + (long)(cos_angle*(double)width);
endy = topy + (long)(cos_angle*(double)height + sin_angle*(double)width);
// check: corners of the rectangle must be inside
if ( IsInside( startx, topy )==false ||
IsInside( endx, endy ) == false )
return false;
// first crop to bounding rectangle
CxImage tmp(*this, true, false, true);
// tmp.Copy(*this, true, false, true);
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
if (!tmp.Crop( startx, topy, endx, endy)){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
// the midpoint of the image now became the same as the midpoint of the rectangle
// rotate new image with minus angle amount
if ( false == tmp.Rotate( (float)(-angle*57.295779513082320877) ) ) // Rotate expects angle in degrees
return false;
// crop rotated image to the original selection rectangle
endx = (tmp.head.biWidth+width)/2;
startx = (tmp.head.biWidth-width)/2;
starty = (tmp.head.biHeight+height)/2;
endy = (tmp.head.biHeight-height)/2;
if ( false == tmp.Crop( startx, starty, endx, endy ) )
return false;
if (iDst) iDst->Transfer(tmp);
else Transfer(tmp);
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool CxImage::Crop(const RECT& rect, CxImage* iDst)
{
return Crop(rect.left, rect.top, rect.right, rect.bottom, iDst);
}
////////////////////////////////////////////////////////////////////////////////
bool CxImage::Crop(long left, long top, long right, long bottom, CxImage* iDst)
{
if (!pDib) return false;
long startx = max(0L,min(left,head.biWidth));
long endx = max(0L,min(right,head.biWidth));
long starty = head.biHeight - max(0L,min(top,head.biHeight));
long endy = head.biHeight - max(0L,min(bottom,head.biHeight));
if (startx==endx || starty==endy) return false;
if (startx>endx) {long tmp=startx; startx=endx; endx=tmp;}
if (starty>endy) {long tmp=starty; starty=endy; endy=tmp;}
CxImage tmp(endx-startx,endy-starty,head.biBitCount,info.dwType);
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
tmp.SetPalette(GetPalette(),head.biClrUsed);
tmp.info.nBkgndIndex = info.nBkgndIndex;
tmp.info.nBkgndColor = info.nBkgndColor;
switch (head.biBitCount) {
case 1:
case 4:
{
for(long y=starty, yd=0; y<endy; y++, yd++){
info.nProgress = (long)(100*(y-starty)/(endy-starty)); //<Anatoly Ivasyuk>
for(long x=startx, xd=0; x<endx; x++, xd++){
tmp.SetPixelIndex(xd,yd,GetPixelIndex(x,y));
}
}
break;
}
case 8:
case 24:
{
int linelen = tmp.head.biWidth * tmp.head.biBitCount >> 3;
BYTE* pDest = tmp.info.pImage;
BYTE* pSrc = info.pImage + starty * info.dwEffWidth + (startx*head.biBitCount >> 3);
for(long y=starty; y<endy; y++){
info.nProgress = (long)(100*(y-starty)/(endy-starty)); //<Anatoly Ivasyuk>
memcpy(pDest,pSrc,linelen);
pDest+=tmp.info.dwEffWidth;
pSrc+=info.dwEffWidth;
}
}
}
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()){ //<oboolo>
tmp.AlphaCreate();
if (!tmp.AlphaIsValid()) return false;
BYTE* pDest = tmp.pAlpha;
BYTE* pSrc = pAlpha + startx + starty*head.biWidth;
for (long y=starty; y<endy; y++){
memcpy(pDest,pSrc,endx-startx);
pDest+=tmp.head.biWidth;
pSrc+=head.biWidth;
}
}
#endif //CXIMAGE_SUPPORT_ALPHA
//select the destination
if (iDst) iDst->Transfer(tmp);
else Transfer(tmp);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* \param xgain, ygain : can be from 0 to 1.
* \param xpivot, ypivot : is the center of the transformation.
* \param bEnableInterpolation : if true, enables bilinear interpolation.
* \return true if everything is ok
*/
bool CxImage::Skew(float xgain, float ygain, long xpivot, long ypivot, bool bEnableInterpolation)
{
if (!pDib) return false;
float nx,ny;
CxImage tmp(*this);
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
long xmin,xmax,ymin,ymax;
if (pSelection){
xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right;
ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top;
} else {
xmin = ymin = 0;
xmax = head.biWidth; ymax=head.biHeight;
}
for(long y=ymin; y<ymax; y++){
info.nProgress = (long)(100*(y-ymin)/(ymax-ymin));
if (info.nEscape) break;
for(long x=xmin; x<xmax; x++){
#if CXIMAGE_SUPPORT_SELECTION
if (BlindSelectionIsInside(x,y))
#endif //CXIMAGE_SUPPORT_SELECTION
{
nx = x + (xgain*(y - ypivot));
ny = y + (ygain*(x - xpivot));
#if CXIMAGE_SUPPORT_INTERPOLATION
if (bEnableInterpolation){
tmp.SetPixelColor(x,y,GetPixelColorInterpolated(nx, ny, CxImage::IM_BILINEAR, CxImage::OM_BACKGROUND),true);
} else
#endif //CXIMAGE_SUPPORT_INTERPOLATION
{
if (head.biClrUsed==0){
tmp.SetPixelColor(x,y,GetPixelColor((long)nx,(long)ny));
} else {
tmp.SetPixelIndex(x,y,GetPixelIndex((long)nx,(long)ny));
}
#if CXIMAGE_SUPPORT_ALPHA
tmp.AlphaSet(x,y,AlphaGet((long)nx,(long)ny));
#endif //CXIMAGE_SUPPORT_ALPHA
}
}
}
}
Transfer(tmp);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Expands the borders.
* \param left, top, right, bottom = additional dimensions, should be greater than 0.
* \param canvascolor = border color. canvascolor.rgbReserved will set the alpha channel (if any) in the border.
* \param iDst = pointer to destination image (if it's 0, this image is modified)
* \return true if everything is ok
* \author [Colin Urquhart]; changes [DP]
*/
bool CxImage::Expand(long left, long top, long right, long bottom, RGBQUAD canvascolor, CxImage* iDst)
{
if (!pDib) return false;
if ((left < 0) || (right < 0) || (bottom < 0) || (top < 0)) return false;
long newWidth = head.biWidth + left + right;
long newHeight = head.biHeight + top + bottom;
right = left + head.biWidth - 1;
top = bottom + head.biHeight - 1;
CxImage tmp;
tmp.CopyInfo(*this);
if (!tmp.Create(newWidth, newHeight, head.biBitCount, info.dwType)){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
tmp.SetPalette(GetPalette(),head.biClrUsed);
switch (head.biBitCount) {
case 1:
case 4:
{
BYTE pixel = tmp.GetNearestIndex(canvascolor);
for(long y=0; y < newHeight; y++){
info.nProgress = (long)(100*y/newHeight);
for(long x=0; x < newWidth; x++){
if ((y < bottom) || (y > top) || (x < left) || (x > right)) {
tmp.SetPixelIndex(x,y, pixel);
} else {
tmp.SetPixelIndex(x,y,GetPixelIndex(x-left,y-bottom));
}
}
}
break;
}
case 8:
case 24:
{
if (head.biBitCount == 8) {
BYTE pixel = tmp.GetNearestIndex( canvascolor);
memset(tmp.info.pImage, pixel, + (tmp.info.dwEffWidth * newHeight));
} else {
for (long y = 0; y < newHeight; ++y) {
BYTE *pDest = tmp.info.pImage + (y * tmp.info.dwEffWidth);
for (long x = 0; x < newWidth; ++x) {
*pDest++ = canvascolor.rgbBlue;
*pDest++ = canvascolor.rgbGreen;
*pDest++ = canvascolor.rgbRed;
}
}
}
BYTE* pDest = tmp.info.pImage + (tmp.info.dwEffWidth * bottom) + (left*(head.biBitCount >> 3));
BYTE* pSrc = info.pImage;
for(long y=bottom; y <= top; y++){
info.nProgress = (long)(100*y/(1 + top - bottom));
memcpy(pDest,pSrc,(head.biBitCount >> 3) * (right - left + 1));
pDest+=tmp.info.dwEffWidth;
pSrc+=info.dwEffWidth;
}
}
}
#if CXIMAGE_SUPPORT_SELECTION
if (SelectionIsValid()){
if (!tmp.SelectionCreate())
return false;
BYTE* pSrc = SelectionGetPointer();
BYTE* pDst = tmp.SelectionGetPointer(left,bottom);
for(long y=bottom; y <= top; y++){
memcpy(pDst,pSrc, (right - left + 1));
pSrc+=head.biWidth;
pDst+=tmp.head.biWidth;
}
tmp.info.rSelectionBox.left = info.rSelectionBox.left + left;
tmp.info.rSelectionBox.right = info.rSelectionBox.right + left;
tmp.info.rSelectionBox.top = info.rSelectionBox.top + bottom;
tmp.info.rSelectionBox.bottom = info.rSelectionBox.bottom + bottom;
}
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()){
if (!tmp.AlphaCreate())
return false;
tmp.AlphaSet(canvascolor.rgbReserved);
BYTE* pSrc = AlphaGetPointer();
BYTE* pDst = tmp.AlphaGetPointer(left,bottom);
for(long y=bottom; y <= top; y++){
memcpy(pDst,pSrc, (right - left + 1));
pSrc+=head.biWidth;
pDst+=tmp.head.biWidth;
}
}
#endif //CXIMAGE_SUPPORT_ALPHA
//select the destination
if (iDst) iDst->Transfer(tmp);
else Transfer(tmp);
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool CxImage::Expand(long newx, long newy, RGBQUAD canvascolor, CxImage* iDst)
{
//thanks to <Colin Urquhart>
if (!pDib) return false;
if ((newx < head.biWidth) || (newy < head.biHeight)) return false;
int nAddLeft = (newx - head.biWidth) / 2;
int nAddTop = (newy - head.biHeight) / 2;
return Expand(nAddLeft, nAddTop, newx - (head.biWidth + nAddLeft), newy - (head.biHeight + nAddTop), canvascolor, iDst);
}
////////////////////////////////////////////////////////////////////////////////
/**
* Resamples the image with the correct aspect ratio, and fills the borders.
* \param newx, newy = thumbnail size.
* \param canvascolor = border color.
* \param iDst = pointer to destination image (if it's 0, this image is modified).
* \return true if everything is ok.
* \author [Colin Urquhart]
*/
bool CxImage::Thumbnail(long newx, long newy, RGBQUAD canvascolor, CxImage* iDst)
{
if (!pDib) return false;
if ((newx <= 0) || (newy <= 0)) return false;
CxImage tmp(*this);
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
// determine whether we need to shrink the image
if ((head.biWidth > newx) || (head.biHeight > newy)) {
float fScale;
float fAspect = (float) newx / (float) newy;
if (fAspect * head.biHeight > head.biWidth) {
fScale = (float) newy / head.biHeight;
} else {
fScale = (float) newx / head.biWidth;
}
tmp.Resample((long) (fScale * head.biWidth), (long) (fScale * head.biHeight), 0);
}
// expand the frame
tmp.Expand(newx, newy, canvascolor, iDst);
//select the destination
if (iDst) iDst->Transfer(tmp);
else Transfer(tmp);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Perform circle_based transformations.
* \param type - for different transformations
* - 0 for normal (proturberant) FishEye
* - 1 for reverse (concave) FishEye
* - 2 for Swirle
* - 3 for Cilinder mirror
* - 4 for bathroom
*
* \param rmax - effect radius. If 0, the whole image is processed
* \param Koeff - only for swirle
* \author Arkadiy Olovyannikov ark(at)msun(dot)ru
*/
bool CxImage::CircleTransform(int type,long rmax,float Koeff)
{
if (!pDib) return false;
long nx,ny;
double angle,radius,rnew;
CxImage tmp(*this);
if (!tmp.IsValid()){
strcpy(info.szLastError,tmp.GetLastError());
return false;
}
long xmin,xmax,ymin,ymax,xmid,ymid;
if (pSelection){
xmin = info.rSelectionBox.left; xmax = info.rSelectionBox.right;
ymin = info.rSelectionBox.bottom; ymax = info.rSelectionBox.top;
} else {
xmin = ymin = 0;
xmax = head.biWidth; ymax=head.biHeight;
}
xmid = (long) (tmp.GetWidth()/2);
ymid = (long) (tmp.GetHeight()/2);
if (!rmax) rmax=(long)sqrt((float)((xmid-xmin)*(xmid-xmin)+(ymid-ymin)*(ymid-ymin)));
if (Koeff==0.0f) Koeff=1.0f;
for(long y=ymin; y<ymax; y++){
info.nProgress = (long)(100*(y-ymin)/(ymax-ymin));
if (info.nEscape) break;
for(long x=xmin; x<xmax; x++){
#if CXIMAGE_SUPPORT_SELECTION
if (BlindSelectionIsInside(x,y))
#endif //CXIMAGE_SUPPORT_SELECTION
{
nx=xmid-x;
ny=ymid-y;
radius=sqrt((float)(nx*nx+ny*ny));
if (radius<rmax) {
angle=atan2((double)ny,(double)nx);
if (type==0) rnew=radius*radius/rmax;
else if (type==1) rnew=sqrt(radius*rmax);
else if (type==2) {rnew=radius;angle += radius / Koeff;}
else rnew = 1; // potentially uninitialized
if (type<3){
nx = xmid + (long)(rnew * cos(angle));
ny = ymid - (long)(rnew * sin(angle));
}
else if (type==3){
nx = (long)fabs((angle*xmax/6.2831852));
ny = (long)fabs((radius*ymax/rmax));
}
else {
nx=x+(x%32)-16;
ny=y;
}
// nx=max(xmin,min(nx,xmax));
// ny=max(ymin,min(ny,ymax));
}
else { nx=-1;ny=-1;}
if (head.biClrUsed==0){
tmp.SetPixelColor(x,y,GetPixelColor(nx,ny));
} else {
tmp.SetPixelIndex(x,y,GetPixelIndex(nx,ny));
}
#if CXIMAGE_SUPPORT_ALPHA
tmp.AlphaSet(x,y,AlphaGet(nx,ny));
#endif //CXIMAGE_SUPPORT_ALPHA
}
}
}
Transfer(tmp);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/**
* Faster way to almost properly shrink image. Algorithm produces results comparable with "high resoultion shrink"
* when resulting image is much smaller (that would be 3 times or more) than original. When
* resulting image is only slightly smaller, results are closer to nearest pixel.
* This algorithm works by averaging, but it does not calculate fractions of pixels. It adds whole
* source pixels to the best destionation. It is not geometrically "correct".
* It's main advantage over "high" resulution shrink is speed, so it's useful, when speed is most
* important (preview thumbnails, "map" view, ...).
* Method is optimized for RGB24 images.
*
* \param newx, newy - size of destination image (must be smaller than original!)
* \param iDst - pointer to destination image (if it's 0, this image is modified)
* \param bChangeBpp - flag points to change result image bpp (if it's true, this result image bpp = 24 (useful for B/W image thumbnails))
*
* \return true if everything is ok
* \author [bd], 9.2004; changes [Artiom Mirolubov], 1.2005
*/
bool CxImage::QIShrink(long newx, long newy, CxImage* const iDst, bool bChangeBpp)
{
if (!pDib) return false;
if (newx>head.biWidth || newy>head.biHeight) {
//let me repeat... this method can't enlarge image
strcpy(info.szLastError,"QIShrink can't enlarge image");
return false;
}
if (newx==head.biWidth && newy==head.biHeight) {
//image already correct size (just copy and return)
if (iDst) iDst->Copy(*this);
return true;
}//if
//create temporary destination image
CxImage newImage;
newImage.CopyInfo(*this);
newImage.Create(newx,newy,(bChangeBpp)?24:head.biBitCount,GetType());
newImage.SetPalette(GetPalette());
if (!newImage.IsValid()){
strcpy(info.szLastError,newImage.GetLastError());
return false;
}
//and alpha channel if required
#if CXIMAGE_SUPPORT_ALPHA
if (AlphaIsValid()) newImage.AlphaCreate();
#endif
const int oldx = head.biWidth;
const int oldy = head.biHeight;
int accuCellSize = 4;
#if CXIMAGE_SUPPORT_ALPHA
BYTE *alphaPtr;
if (AlphaIsValid()) accuCellSize=5;
#endif
unsigned int *accu = new unsigned int[newx*accuCellSize]; //array for suming pixels... one pixel for every destination column
unsigned int *accuPtr; //pointer for walking through accu
//each cell consists of blue, red, green component and count of pixels summed in this cell
memset(accu, 0, newx * accuCellSize * sizeof(unsigned int)); //clear accu
if (!IsIndexed()) {
//RGB24 version with pointers
BYTE *destPtr, *srcPtr, *destPtrS, *srcPtrS; //destination and source pixel, and beginnings of current row
srcPtrS=(BYTE*)BlindGetPixelPointer(0,0);
destPtrS=(BYTE*)newImage.BlindGetPixelPointer(0,0);
int ex=0, ey=0; //ex and ey replace division...
int dy=0;
//(we just add pixels, until by adding newx or newy we get a number greater than old size... then
// it's time to move to next pixel)
for(int y=0; y<oldy; y++){ //for all source rows
info.nProgress = (long)(100*y/oldy); if (info.nEscape) break;
ey += newy;
ex = 0; //restart with ex = 0
accuPtr=accu; //restart from beginning of accu
srcPtr=srcPtrS; //and from new source line
#if CXIMAGE_SUPPORT_ALPHA
alphaPtr = AlphaGetPointer(0, y);
#endif
for(int x=0; x<oldx; x++){ //for all source columns
ex += newx;
*accuPtr += *(srcPtr++); //add current pixel to current accu slot
*(accuPtr+1) += *(srcPtr++);
*(accuPtr+2) += *(srcPtr++);
(*(accuPtr+3)) ++;
#if CXIMAGE_SUPPORT_ALPHA
if (alphaPtr) *(accuPtr+4) += *(alphaPtr++);
#endif
if (ex>oldx) { //when we reach oldx, it's time to move to new slot
accuPtr += accuCellSize;
ex -= oldx; //(substract oldx from ex and resume from there on)
}//if (ex overflow)
}//for x
if (ey>=oldy) { //now when this happens
ey -= oldy; //it's time to move to new destination row
destPtr = destPtrS; //reset pointers to proper initial values
accuPtr = accu;
#if CXIMAGE_SUPPORT_ALPHA
alphaPtr = newImage.AlphaGetPointer(0, dy++);
#endif
for (int k=0; k<newx; k++) { //copy accu to destination row (divided by number of pixels in each slot)
*(destPtr++) = (BYTE)(*(accuPtr) / *(accuPtr+3));
*(destPtr++) = (BYTE)(*(accuPtr+1) / *(accuPtr+3));
*(destPtr++) = (BYTE)(*(accuPtr+2) / *(accuPtr+3));
#if CXIMAGE_SUPPORT_ALPHA
if (alphaPtr) *(alphaPtr++) = (BYTE)(*(accuPtr+4) / *(accuPtr+3));
#endif
accuPtr += accuCellSize;
}//for k
memset(accu, 0, newx * accuCellSize * sizeof(unsigned int)); //clear accu
destPtrS += newImage.info.dwEffWidth;
}//if (ey overflow)
srcPtrS += info.dwEffWidth; //next round we start from new source row
}//for y
} else {
//standard version with GetPixelColor...
int ex=0, ey=0; //ex and ey replace division...
int dy=0;
//(we just add pixels, until by adding newx or newy we get a number greater than old size... then
// it's time to move to next pixel)
RGBQUAD rgb;
for(int y=0; y<oldy; y++){ //for all source rows
info.nProgress = (long)(100*y/oldy); if (info.nEscape) break;
ey += newy;
ex = 0; //restart with ex = 0
accuPtr=accu; //restart from beginning of accu
for(int x=0; x<oldx; x++){ //for all source columns
ex += newx;
rgb = GetPixelColor(x, y, true);
*accuPtr += rgb.rgbBlue; //add current pixel to current accu slot
*(accuPtr+1) += rgb.rgbRed;
*(accuPtr+2) += rgb.rgbGreen;
(*(accuPtr+3)) ++;
#if CXIMAGE_SUPPORT_ALPHA
if (pAlpha) *(accuPtr+4) += rgb.rgbReserved;
#endif
if (ex>oldx) { //when we reach oldx, it's time to move to new slot
accuPtr += accuCellSize;
ex -= oldx; //(substract oldx from ex and resume from there on)
}//if (ex overflow)
}//for x
if (ey>=oldy) { //now when this happens
ey -= oldy; //it's time to move to new destination row
accuPtr = accu;
for (int dx=0; dx<newx; dx++) { //copy accu to destination row (divided by number of pixels in each slot)
rgb.rgbBlue = (BYTE)(*(accuPtr) / *(accuPtr+3));
rgb.rgbRed = (BYTE)(*(accuPtr+1) / *(accuPtr+3));
rgb.rgbGreen= (BYTE)(*(accuPtr+2) / *(accuPtr+3));
#if CXIMAGE_SUPPORT_ALPHA
if (pAlpha) rgb.rgbReserved = (BYTE)(*(accuPtr+4) / *(accuPtr+3));
#endif
newImage.SetPixelColor(dx, dy, rgb, pAlpha!=0);
accuPtr += accuCellSize;
}//for dx
memset(accu, 0, newx * accuCellSize * sizeof(unsigned int)); //clear accu
dy++;
}//if (ey overflow)
}//for y
}//if
delete [] accu; //delete helper array
//copy new image to the destination
if (iDst)
iDst->Transfer(newImage);
else
Transfer(newImage);
return true;
}
////////////////////////////////////////////////////////////////////////////////
#endif //CXIMAGE_SUPPORT_TRANSFORMATION
| gpl-2.0 |
VanirRezound/kernel-vigor-aosp-3.4 | kernel/ksysfs.c | 382 | 4893 | /*
* kernel/ksysfs.c - sysfs attributes in /sys/kernel, which
* are not related to any other subsystem
*
* Copyright (C) 2004 Kay Sievers <kay.sievers@vrfy.org>
*
* This file is release under the GPLv2
*
*/
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/sysfs.h>
#include <linux/export.h>
#include <linux/init.h>
#include <linux/kexec.h>
#include <linux/profile.h>
#include <linux/stat.h>
#include <linux/sched.h>
#include <linux/capability.h>
#define KERNEL_ATTR_RO(_name) \
static struct kobj_attribute _name##_attr = __ATTR_RO(_name)
#define KERNEL_ATTR_RW(_name) \
static struct kobj_attribute _name##_attr = \
__ATTR(_name, 0644, _name##_show, _name##_store)
#if defined(CONFIG_HOTPLUG)
static ssize_t uevent_seqnum_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%llu\n", (unsigned long long)uevent_seqnum);
}
KERNEL_ATTR_RO(uevent_seqnum);
static ssize_t uevent_helper_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", uevent_helper);
}
static ssize_t uevent_helper_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
if (count+1 > UEVENT_HELPER_PATH_LEN)
return -ENOENT;
memcpy(uevent_helper, buf, count);
uevent_helper[count] = '\0';
if (count && uevent_helper[count-1] == '\n')
uevent_helper[count-1] = '\0';
return count;
}
KERNEL_ATTR_RW(uevent_helper);
#endif
#ifdef CONFIG_PROFILING
static ssize_t profiling_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", prof_on);
}
static ssize_t profiling_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
int ret;
if (prof_on)
return -EEXIST;
profile_setup((char *)buf);
ret = profile_init();
if (ret)
return ret;
ret = create_proc_profile();
if (ret)
return ret;
return count;
}
KERNEL_ATTR_RW(profiling);
#endif
#ifdef CONFIG_KEXEC
static ssize_t kexec_loaded_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", !!kexec_image);
}
KERNEL_ATTR_RO(kexec_loaded);
static ssize_t kexec_crash_loaded_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", !!kexec_crash_image);
}
KERNEL_ATTR_RO(kexec_crash_loaded);
static ssize_t kexec_crash_size_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%zu\n", crash_get_memory_size());
}
static ssize_t kexec_crash_size_store(struct kobject *kobj,
struct kobj_attribute *attr,
const char *buf, size_t count)
{
unsigned long cnt;
int ret;
if (strict_strtoul(buf, 0, &cnt))
return -EINVAL;
ret = crash_shrink_memory(cnt);
return ret < 0 ? ret : count;
}
KERNEL_ATTR_RW(kexec_crash_size);
static ssize_t vmcoreinfo_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%lx %x\n",
paddr_vmcoreinfo_note(),
(unsigned int)vmcoreinfo_max_size);
}
KERNEL_ATTR_RO(vmcoreinfo);
#endif
static ssize_t fscaps_show(struct kobject *kobj,
struct kobj_attribute *attr, char *buf)
{
return sprintf(buf, "%d\n", file_caps_enabled);
}
KERNEL_ATTR_RO(fscaps);
extern const void __start_notes __attribute__((weak));
extern const void __stop_notes __attribute__((weak));
#define notes_size (&__stop_notes - &__start_notes)
static ssize_t notes_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
memcpy(buf, &__start_notes + off, count);
return count;
}
static struct bin_attribute notes_attr = {
.attr = {
.name = "notes",
.mode = S_IRUGO,
},
.read = ¬es_read,
};
struct kobject *kernel_kobj;
EXPORT_SYMBOL_GPL(kernel_kobj);
static struct attribute * kernel_attrs[] = {
&fscaps_attr.attr,
#if defined(CONFIG_HOTPLUG)
&uevent_seqnum_attr.attr,
&uevent_helper_attr.attr,
#endif
#ifdef CONFIG_PROFILING
&profiling_attr.attr,
#endif
#ifdef CONFIG_KEXEC
&kexec_loaded_attr.attr,
&kexec_crash_loaded_attr.attr,
&kexec_crash_size_attr.attr,
&vmcoreinfo_attr.attr,
#endif
NULL
};
static struct attribute_group kernel_attr_group = {
.attrs = kernel_attrs,
};
static int __init ksysfs_init(void)
{
int error;
kernel_kobj = kobject_create_and_add("kernel", NULL);
if (!kernel_kobj) {
error = -ENOMEM;
goto exit;
}
error = sysfs_create_group(kernel_kobj, &kernel_attr_group);
if (error)
goto kset_exit;
if (notes_size > 0) {
notes_attr.size = notes_size;
error = sysfs_create_bin_file(kernel_kobj, ¬es_attr);
if (error)
goto group_exit;
}
return 0;
group_exit:
sysfs_remove_group(kernel_kobj, &kernel_attr_group);
kset_exit:
kobject_put(kernel_kobj);
exit:
return error;
}
core_initcall(ksysfs_init);
| gpl-2.0 |
jose51197/Infernal_3.4 | security/commoncap.c | 382 | 14024 | /* Common capabilities, needed by capability.o.
*
* 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/capability.h>
#include <linux/audit.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/security.h>
#include <linux/file.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/pagemap.h>
#include <linux/swap.h>
#include <linux/skbuff.h>
#include <linux/netlink.h>
#include <linux/ptrace.h>
#include <linux/xattr.h>
#include <linux/hugetlb.h>
#include <linux/mount.h>
#include <linux/sched.h>
#include <linux/prctl.h>
#include <linux/securebits.h>
#include <linux/user_namespace.h>
#include <linux/binfmts.h>
#include <linux/personality.h>
#ifdef CONFIG_ANDROID_PARANOID_NETWORK
#include <linux/android_aid.h>
#endif
static void warn_setuid_and_fcaps_mixed(const char *fname)
{
static int warned;
if (!warned) {
printk(KERN_INFO "warning: `%s' has both setuid-root and"
" effective capabilities. Therefore not raising all"
" capabilities.\n", fname);
warned = 1;
}
}
int cap_netlink_send(struct sock *sk, struct sk_buff *skb)
{
return 0;
}
int cap_capable(const struct cred *cred, struct user_namespace *targ_ns,
int cap, int audit)
{
#ifdef CONFIG_ANDROID_PARANOID_NETWORK
if (cap == CAP_NET_RAW && in_egroup_p(AID_NET_RAW))
return 0;
if (cap == CAP_NET_ADMIN && in_egroup_p(AID_NET_ADMIN))
return 0;
#endif
for (;;) {
if (targ_ns != &init_user_ns && targ_ns->creator == cred->user)
return 0;
if (targ_ns == cred->user->user_ns)
return cap_raised(cred->cap_effective, cap) ? 0 : -EPERM;
if (targ_ns == &init_user_ns)
return -EPERM;
targ_ns = targ_ns->creator->user_ns;
}
}
int cap_settime(const struct timespec *ts, const struct timezone *tz)
{
if (!capable(CAP_SYS_TIME))
return -EPERM;
return 0;
}
int cap_ptrace_access_check(struct task_struct *child, unsigned int mode)
{
int ret = 0;
const struct cred *cred, *child_cred;
rcu_read_lock();
cred = current_cred();
child_cred = __task_cred(child);
if (cred->user->user_ns == child_cred->user->user_ns &&
cap_issubset(child_cred->cap_permitted, cred->cap_permitted))
goto out;
if (ns_capable(child_cred->user->user_ns, CAP_SYS_PTRACE))
goto out;
ret = -EPERM;
out:
rcu_read_unlock();
return ret;
}
int cap_ptrace_traceme(struct task_struct *parent)
{
int ret = 0;
const struct cred *cred, *child_cred;
rcu_read_lock();
cred = __task_cred(parent);
child_cred = current_cred();
if (cred->user->user_ns == child_cred->user->user_ns &&
cap_issubset(child_cred->cap_permitted, cred->cap_permitted))
goto out;
if (has_ns_capability(parent, child_cred->user->user_ns, CAP_SYS_PTRACE))
goto out;
ret = -EPERM;
out:
rcu_read_unlock();
return ret;
}
int cap_capget(struct task_struct *target, kernel_cap_t *effective,
kernel_cap_t *inheritable, kernel_cap_t *permitted)
{
const struct cred *cred;
rcu_read_lock();
cred = __task_cred(target);
*effective = cred->cap_effective;
*inheritable = cred->cap_inheritable;
*permitted = cred->cap_permitted;
rcu_read_unlock();
return 0;
}
static inline int cap_inh_is_capped(void)
{
if (cap_capable(current_cred(), current_cred()->user->user_ns,
CAP_SETPCAP, SECURITY_CAP_AUDIT) == 0)
return 0;
return 1;
}
int cap_capset(struct cred *new,
const struct cred *old,
const kernel_cap_t *effective,
const kernel_cap_t *inheritable,
const kernel_cap_t *permitted)
{
if (cap_inh_is_capped() &&
!cap_issubset(*inheritable,
cap_combine(old->cap_inheritable,
old->cap_permitted)))
return -EPERM;
if (!cap_issubset(*inheritable,
cap_combine(old->cap_inheritable,
old->cap_bset)))
return -EPERM;
if (!cap_issubset(*permitted, old->cap_permitted))
return -EPERM;
if (!cap_issubset(*effective, *permitted))
return -EPERM;
new->cap_effective = *effective;
new->cap_inheritable = *inheritable;
new->cap_permitted = *permitted;
return 0;
}
static inline void bprm_clear_caps(struct linux_binprm *bprm)
{
cap_clear(bprm->cred->cap_permitted);
bprm->cap_effective = false;
}
int cap_inode_need_killpriv(struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
int error;
if (!inode->i_op->getxattr)
return 0;
error = inode->i_op->getxattr(dentry, XATTR_NAME_CAPS, NULL, 0);
if (error <= 0)
return 0;
return 1;
}
int cap_inode_killpriv(struct dentry *dentry)
{
struct inode *inode = dentry->d_inode;
if (!inode->i_op->removexattr)
return 0;
return inode->i_op->removexattr(dentry, XATTR_NAME_CAPS);
}
static inline int bprm_caps_from_vfs_caps(struct cpu_vfs_cap_data *caps,
struct linux_binprm *bprm,
bool *effective,
bool *has_cap)
{
struct cred *new = bprm->cred;
unsigned i;
int ret = 0;
if (caps->magic_etc & VFS_CAP_FLAGS_EFFECTIVE)
*effective = true;
if (caps->magic_etc & VFS_CAP_REVISION_MASK)
*has_cap = true;
CAP_FOR_EACH_U32(i) {
__u32 permitted = caps->permitted.cap[i];
__u32 inheritable = caps->inheritable.cap[i];
new->cap_permitted.cap[i] =
(new->cap_bset.cap[i] & permitted) |
(new->cap_inheritable.cap[i] & inheritable);
if (permitted & ~new->cap_permitted.cap[i])
ret = -EPERM;
}
return *effective ? ret : 0;
}
int get_vfs_caps_from_disk(const struct dentry *dentry, struct cpu_vfs_cap_data *cpu_caps)
{
struct inode *inode = dentry->d_inode;
__u32 magic_etc;
unsigned tocopy, i;
int size;
struct vfs_cap_data caps;
memset(cpu_caps, 0, sizeof(struct cpu_vfs_cap_data));
if (!inode || !inode->i_op->getxattr)
return -ENODATA;
size = inode->i_op->getxattr((struct dentry *)dentry, XATTR_NAME_CAPS, &caps,
XATTR_CAPS_SZ);
if (size == -ENODATA || size == -EOPNOTSUPP)
return -ENODATA;
if (size < 0)
return size;
if (size < sizeof(magic_etc))
return -EINVAL;
cpu_caps->magic_etc = magic_etc = le32_to_cpu(caps.magic_etc);
switch (magic_etc & VFS_CAP_REVISION_MASK) {
case VFS_CAP_REVISION_1:
if (size != XATTR_CAPS_SZ_1)
return -EINVAL;
tocopy = VFS_CAP_U32_1;
break;
case VFS_CAP_REVISION_2:
if (size != XATTR_CAPS_SZ_2)
return -EINVAL;
tocopy = VFS_CAP_U32_2;
break;
default:
return -EINVAL;
}
CAP_FOR_EACH_U32(i) {
if (i >= tocopy)
break;
cpu_caps->permitted.cap[i] = le32_to_cpu(caps.data[i].permitted);
cpu_caps->inheritable.cap[i] = le32_to_cpu(caps.data[i].inheritable);
}
return 0;
}
static int get_file_caps(struct linux_binprm *bprm, bool *effective, bool *has_cap)
{
struct dentry *dentry;
int rc = 0;
struct cpu_vfs_cap_data vcaps;
bprm_clear_caps(bprm);
if (!file_caps_enabled)
return 0;
if (bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)
return 0;
dentry = dget(bprm->file->f_dentry);
rc = get_vfs_caps_from_disk(dentry, &vcaps);
if (rc < 0) {
if (rc == -EINVAL)
printk(KERN_NOTICE "%s: get_vfs_caps_from_disk returned %d for %s\n",
__func__, rc, bprm->filename);
else if (rc == -ENODATA)
rc = 0;
goto out;
}
rc = bprm_caps_from_vfs_caps(&vcaps, bprm, effective, has_cap);
if (rc == -EINVAL)
printk(KERN_NOTICE "%s: cap_from_disk returned %d for %s\n",
__func__, rc, bprm->filename);
out:
dput(dentry);
if (rc)
bprm_clear_caps(bprm);
return rc;
}
int cap_bprm_set_creds(struct linux_binprm *bprm)
{
const struct cred *old = current_cred();
struct cred *new = bprm->cred;
bool effective, has_cap = false;
int ret;
effective = false;
ret = get_file_caps(bprm, &effective, &has_cap);
if (ret < 0)
return ret;
if (!issecure(SECURE_NOROOT)) {
if (has_cap && new->uid != 0 && new->euid == 0) {
warn_setuid_and_fcaps_mixed(bprm->filename);
goto skip;
}
if (new->euid == 0 || new->uid == 0) {
new->cap_permitted = cap_combine(old->cap_bset,
old->cap_inheritable);
}
if (new->euid == 0)
effective = true;
}
skip:
if (!cap_issubset(new->cap_permitted, old->cap_permitted))
bprm->per_clear |= PER_CLEAR_ON_SETID;
if ((new->euid != old->uid ||
new->egid != old->gid ||
!cap_issubset(new->cap_permitted, old->cap_permitted)) &&
bprm->unsafe & ~LSM_UNSAFE_PTRACE_CAP) {
if (!capable(CAP_SETUID)) {
new->euid = new->uid;
new->egid = new->gid;
}
new->cap_permitted = cap_intersect(new->cap_permitted,
old->cap_permitted);
}
new->suid = new->fsuid = new->euid;
new->sgid = new->fsgid = new->egid;
if (effective)
new->cap_effective = new->cap_permitted;
else
cap_clear(new->cap_effective);
bprm->cap_effective = effective;
if (!cap_isclear(new->cap_effective)) {
if (!cap_issubset(CAP_FULL_SET, new->cap_effective) ||
new->euid != 0 || new->uid != 0 ||
issecure(SECURE_NOROOT)) {
ret = audit_log_bprm_fcaps(bprm, new, old);
if (ret < 0)
return ret;
}
}
new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS);
return 0;
}
int cap_bprm_secureexec(struct linux_binprm *bprm)
{
const struct cred *cred = current_cred();
if (cred->uid != 0) {
if (bprm->cap_effective)
return 1;
if (!cap_isclear(cred->cap_permitted))
return 1;
}
return (cred->euid != cred->uid ||
cred->egid != cred->gid);
}
int cap_inode_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags)
{
if (!strcmp(name, XATTR_NAME_CAPS)) {
if (!capable(CAP_SETFCAP))
return -EPERM;
return 0;
}
if (!strncmp(name, XATTR_SECURITY_PREFIX,
sizeof(XATTR_SECURITY_PREFIX) - 1) &&
!capable(CAP_SYS_ADMIN))
return -EPERM;
return 0;
}
int cap_inode_removexattr(struct dentry *dentry, const char *name)
{
if (!strcmp(name, XATTR_NAME_CAPS)) {
if (!capable(CAP_SETFCAP))
return -EPERM;
return 0;
}
if (!strncmp(name, XATTR_SECURITY_PREFIX,
sizeof(XATTR_SECURITY_PREFIX) - 1) &&
!capable(CAP_SYS_ADMIN))
return -EPERM;
return 0;
}
static inline void cap_emulate_setxuid(struct cred *new, const struct cred *old)
{
if ((old->uid == 0 || old->euid == 0 || old->suid == 0) &&
(new->uid != 0 && new->euid != 0 && new->suid != 0) &&
!issecure(SECURE_KEEP_CAPS)) {
cap_clear(new->cap_permitted);
cap_clear(new->cap_effective);
}
if (old->euid == 0 && new->euid != 0)
cap_clear(new->cap_effective);
if (old->euid != 0 && new->euid == 0)
new->cap_effective = new->cap_permitted;
}
int cap_task_fix_setuid(struct cred *new, const struct cred *old, int flags)
{
switch (flags) {
case LSM_SETID_RE:
case LSM_SETID_ID:
case LSM_SETID_RES:
if (!issecure(SECURE_NO_SETUID_FIXUP))
cap_emulate_setxuid(new, old);
break;
case LSM_SETID_FS:
if (!issecure(SECURE_NO_SETUID_FIXUP)) {
if (old->fsuid == 0 && new->fsuid != 0)
new->cap_effective =
cap_drop_fs_set(new->cap_effective);
if (old->fsuid != 0 && new->fsuid == 0)
new->cap_effective =
cap_raise_fs_set(new->cap_effective,
new->cap_permitted);
}
break;
default:
return -EINVAL;
}
return 0;
}
static int cap_safe_nice(struct task_struct *p)
{
int is_subset;
rcu_read_lock();
is_subset = cap_issubset(__task_cred(p)->cap_permitted,
current_cred()->cap_permitted);
rcu_read_unlock();
if (!is_subset && !capable(CAP_SYS_NICE))
return -EPERM;
return 0;
}
int cap_task_setscheduler(struct task_struct *p)
{
return cap_safe_nice(p);
}
int cap_task_setioprio(struct task_struct *p, int ioprio)
{
return cap_safe_nice(p);
}
int cap_task_setnice(struct task_struct *p, int nice)
{
return cap_safe_nice(p);
}
static long cap_prctl_drop(struct cred *new, unsigned long cap)
{
if (!capable(CAP_SETPCAP))
return -EPERM;
if (!cap_valid(cap))
return -EINVAL;
cap_lower(new->cap_bset, cap);
return 0;
}
int cap_task_prctl(int option, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5)
{
struct cred *new;
long error = 0;
new = prepare_creds();
if (!new)
return -ENOMEM;
switch (option) {
case PR_CAPBSET_READ:
error = -EINVAL;
if (!cap_valid(arg2))
goto error;
error = !!cap_raised(new->cap_bset, arg2);
goto no_change;
case PR_CAPBSET_DROP:
error = cap_prctl_drop(new, arg2);
if (error < 0)
goto error;
goto changed;
case PR_SET_SECUREBITS:
error = -EPERM;
if ((((new->securebits & SECURE_ALL_LOCKS) >> 1)
& (new->securebits ^ arg2))
|| ((new->securebits & SECURE_ALL_LOCKS & ~arg2))
|| (arg2 & ~(SECURE_ALL_LOCKS | SECURE_ALL_BITS))
|| (cap_capable(current_cred(),
current_cred()->user->user_ns, CAP_SETPCAP,
SECURITY_CAP_AUDIT) != 0)
)
goto error;
new->securebits = arg2;
goto changed;
case PR_GET_SECUREBITS:
error = new->securebits;
goto no_change;
case PR_GET_KEEPCAPS:
if (issecure(SECURE_KEEP_CAPS))
error = 1;
goto no_change;
case PR_SET_KEEPCAPS:
error = -EINVAL;
if (arg2 > 1)
goto error;
error = -EPERM;
if (issecure(SECURE_KEEP_CAPS_LOCKED))
goto error;
if (arg2)
new->securebits |= issecure_mask(SECURE_KEEP_CAPS);
else
new->securebits &= ~issecure_mask(SECURE_KEEP_CAPS);
goto changed;
default:
error = -ENOSYS;
goto error;
}
changed:
return commit_creds(new);
no_change:
error:
abort_creds(new);
return error;
}
int cap_vm_enough_memory(struct mm_struct *mm, long pages)
{
int cap_sys_admin = 0;
if (cap_capable(current_cred(), &init_user_ns, CAP_SYS_ADMIN,
SECURITY_CAP_NOAUDIT) == 0)
cap_sys_admin = 1;
return __vm_enough_memory(mm, pages, cap_sys_admin);
}
int cap_file_mmap(struct file *file, unsigned long reqprot,
unsigned long prot, unsigned long flags,
unsigned long addr, unsigned long addr_only)
{
int ret = 0;
if (addr < dac_mmap_min_addr) {
ret = cap_capable(current_cred(), &init_user_ns, CAP_SYS_RAWIO,
SECURITY_CAP_AUDIT);
if (ret == 0)
current->flags |= PF_SUPERPRIV;
}
return ret;
}
| gpl-2.0 |
boa19861105/android_443_KitKat_kernel_htc_dlxub1 | crypto/krng.c | 382 | 1458 | /*
* RNG implementation using standard kernel RNG.
*
* Copyright (c) 2008 Herbert Xu <herbert@gondor.apana.org.au>
*
* 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
* any later version.
*
*/
#include <crypto/internal/rng.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/random.h>
static int krng_get_random(struct crypto_rng *tfm, u8 *rdata, unsigned int dlen)
{
get_random_bytes(rdata, dlen);
return 0;
}
static int krng_reset(struct crypto_rng *tfm, u8 *seed, unsigned int slen)
{
return 0;
}
static struct crypto_alg krng_alg = {
.cra_name = "stdrng",
.cra_driver_name = "krng",
.cra_priority = 200,
.cra_flags = CRYPTO_ALG_TYPE_RNG,
.cra_ctxsize = 0,
.cra_type = &crypto_rng_type,
.cra_module = THIS_MODULE,
.cra_list = LIST_HEAD_INIT(krng_alg.cra_list),
.cra_u = {
.rng = {
.rng_make_random = krng_get_random,
.rng_reset = krng_reset,
.seedsize = 0,
}
}
};
static int __init krng_mod_init(void)
{
return crypto_register_alg(&krng_alg);
}
static void __exit krng_mod_fini(void)
{
crypto_unregister_alg(&krng_alg);
return;
}
module_init(krng_mod_init);
module_exit(krng_mod_fini);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Kernel Random Number Generator");
MODULE_ALIAS("stdrng");
| gpl-2.0 |
froggy666uk/froggy_grouper_kernel | drivers/input/mouse/hgpk.c | 382 | 28024 | /*
* OLPC HGPK (XO-1) touchpad PS/2 mouse driver
*
* Copyright (c) 2006-2008 One Laptop Per Child
* Authors:
* Zephaniah E. Hull
* Andres Salomon <dilinger@debian.org>
*
* This driver is partly based on the ALPS driver, which is:
*
* Copyright (c) 2003 Neil Brown <neilb@cse.unsw.edu.au>
* Copyright (c) 2003-2005 Peter Osterlund <petero2@telia.com>
* Copyright (c) 2004 Dmitry Torokhov <dtor@mail.ru>
* Copyright (c) 2005 Vojtech Pavlik <vojtech@suse.cz>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/*
* The spec from ALPS is available from
* <http://wiki.laptop.org/go/Touch_Pad/Tablet>. It refers to this
* device as HGPK (Hybrid GS, PT, and Keymatrix).
*
* The earliest versions of the device had simultaneous reporting; that
* was removed. After that, the device used the Advanced Mode GS/PT streaming
* stuff. That turned out to be too buggy to support, so we've finally
* switched to Mouse Mode (which utilizes only the center 1/3 of the touchpad).
*/
#define DEBUG
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include <linux/delay.h>
#include <asm/olpc.h>
#include "psmouse.h"
#include "hgpk.h"
#define ILLEGAL_XY 999999
static bool tpdebug;
module_param(tpdebug, bool, 0644);
MODULE_PARM_DESC(tpdebug, "enable debugging, dumping packets to KERN_DEBUG.");
static int recalib_delta = 100;
module_param(recalib_delta, int, 0644);
MODULE_PARM_DESC(recalib_delta,
"packets containing a delta this large will be discarded, and a "
"recalibration may be scheduled.");
static int jumpy_delay = 20;
module_param(jumpy_delay, int, 0644);
MODULE_PARM_DESC(jumpy_delay,
"delay (ms) before recal after jumpiness detected");
static int spew_delay = 1;
module_param(spew_delay, int, 0644);
MODULE_PARM_DESC(spew_delay,
"delay (ms) before recal after packet spew detected");
static int recal_guard_time;
module_param(recal_guard_time, int, 0644);
MODULE_PARM_DESC(recal_guard_time,
"interval (ms) during which recal will be restarted if packet received");
static int post_interrupt_delay = 40;
module_param(post_interrupt_delay, int, 0644);
MODULE_PARM_DESC(post_interrupt_delay,
"delay (ms) before recal after recal interrupt detected");
static bool autorecal = true;
module_param(autorecal, bool, 0644);
MODULE_PARM_DESC(autorecal, "enable recalibration in the driver");
static char hgpk_mode_name[16];
module_param_string(hgpk_mode, hgpk_mode_name, sizeof(hgpk_mode_name), 0644);
MODULE_PARM_DESC(hgpk_mode,
"default hgpk mode: mouse, glidesensor or pentablet");
static int hgpk_default_mode = HGPK_MODE_MOUSE;
static const char * const hgpk_mode_names[] = {
[HGPK_MODE_MOUSE] = "Mouse",
[HGPK_MODE_GLIDESENSOR] = "GlideSensor",
[HGPK_MODE_PENTABLET] = "PenTablet",
};
static int hgpk_mode_from_name(const char *buf, int len)
{
int i;
for (i = 0; i < ARRAY_SIZE(hgpk_mode_names); i++) {
const char *name = hgpk_mode_names[i];
if (strlen(name) == len && !strncasecmp(name, buf, len))
return i;
}
return HGPK_MODE_INVALID;
}
/*
* see if new value is within 20% of half of old value
*/
static int approx_half(int curr, int prev)
{
int belowhalf, abovehalf;
if (curr < 5 || prev < 5)
return 0;
belowhalf = (prev * 8) / 20;
abovehalf = (prev * 12) / 20;
return belowhalf < curr && curr <= abovehalf;
}
/*
* Throw out oddly large delta packets, and any that immediately follow whose
* values are each approximately half of the previous. It seems that the ALPS
* firmware emits errant packets, and they get averaged out slowly.
*/
static int hgpk_discard_decay_hack(struct psmouse *psmouse, int x, int y)
{
struct hgpk_data *priv = psmouse->private;
int avx, avy;
bool do_recal = false;
avx = abs(x);
avy = abs(y);
/* discard if too big, or half that but > 4 times the prev delta */
if (avx > recalib_delta ||
(avx > recalib_delta / 2 && ((avx / 4) > priv->xlast))) {
hgpk_err(psmouse, "detected %dpx jump in x\n", x);
priv->xbigj = avx;
} else if (approx_half(avx, priv->xbigj)) {
hgpk_err(psmouse, "detected secondary %dpx jump in x\n", x);
priv->xbigj = avx;
priv->xsaw_secondary++;
} else {
if (priv->xbigj && priv->xsaw_secondary > 1)
do_recal = true;
priv->xbigj = 0;
priv->xsaw_secondary = 0;
}
if (avy > recalib_delta ||
(avy > recalib_delta / 2 && ((avy / 4) > priv->ylast))) {
hgpk_err(psmouse, "detected %dpx jump in y\n", y);
priv->ybigj = avy;
} else if (approx_half(avy, priv->ybigj)) {
hgpk_err(psmouse, "detected secondary %dpx jump in y\n", y);
priv->ybigj = avy;
priv->ysaw_secondary++;
} else {
if (priv->ybigj && priv->ysaw_secondary > 1)
do_recal = true;
priv->ybigj = 0;
priv->ysaw_secondary = 0;
}
priv->xlast = avx;
priv->ylast = avy;
if (do_recal && jumpy_delay) {
hgpk_err(psmouse, "scheduling recalibration\n");
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(jumpy_delay));
}
return priv->xbigj || priv->ybigj;
}
static void hgpk_reset_spew_detection(struct hgpk_data *priv)
{
priv->spew_count = 0;
priv->dupe_count = 0;
priv->x_tally = 0;
priv->y_tally = 0;
priv->spew_flag = NO_SPEW;
}
static void hgpk_reset_hack_state(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
priv->abs_x = priv->abs_y = -1;
priv->xlast = priv->ylast = ILLEGAL_XY;
priv->xbigj = priv->ybigj = 0;
priv->xsaw_secondary = priv->ysaw_secondary = 0;
hgpk_reset_spew_detection(priv);
}
/*
* We have no idea why this particular hardware bug occurs. The touchpad
* will randomly start spewing packets without anything touching the
* pad. This wouldn't necessarily be bad, but it's indicative of a
* severely miscalibrated pad; attempting to use the touchpad while it's
* spewing means the cursor will jump all over the place, and act "drunk".
*
* The packets that are spewed tend to all have deltas between -2 and 2, and
* the cursor will move around without really going very far. It will
* tend to end up in the same location; if we tally up the changes over
* 100 packets, we end up w/ a final delta of close to 0. This happens
* pretty regularly when the touchpad is spewing, and is pretty hard to
* manually trigger (at least for *my* fingers). So, it makes a perfect
* scheme for detecting spews.
*/
static void hgpk_spewing_hack(struct psmouse *psmouse,
int l, int r, int x, int y)
{
struct hgpk_data *priv = psmouse->private;
/* ignore button press packets; many in a row could trigger
* a false-positive! */
if (l || r)
return;
/* don't track spew if the workaround feature has been turned off */
if (!spew_delay)
return;
if (abs(x) > 3 || abs(y) > 3) {
/* no spew, or spew ended */
hgpk_reset_spew_detection(priv);
return;
}
/* Keep a tally of the overall delta to the cursor position caused by
* the spew */
priv->x_tally += x;
priv->y_tally += y;
switch (priv->spew_flag) {
case NO_SPEW:
/* we're not spewing, but this packet might be the start */
priv->spew_flag = MAYBE_SPEWING;
/* fall-through */
case MAYBE_SPEWING:
priv->spew_count++;
if (priv->spew_count < SPEW_WATCH_COUNT)
break;
/* excessive spew detected, request recalibration */
priv->spew_flag = SPEW_DETECTED;
/* fall-through */
case SPEW_DETECTED:
/* only recalibrate when the overall delta to the cursor
* is really small. if the spew is causing significant cursor
* movement, it is probably a case of the user moving the
* cursor very slowly across the screen. */
if (abs(priv->x_tally) < 3 && abs(priv->y_tally) < 3) {
hgpk_err(psmouse, "packet spew detected (%d,%d)\n",
priv->x_tally, priv->y_tally);
priv->spew_flag = RECALIBRATING;
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(spew_delay));
}
break;
case RECALIBRATING:
/* we already detected a spew and requested a recalibration,
* just wait for the queue to kick into action. */
break;
}
}
/*
* HGPK Mouse Mode format (standard mouse format, sans middle button)
*
* byte 0: y-over x-over y-neg x-neg 1 0 swr swl
* byte 1: x7 x6 x5 x4 x3 x2 x1 x0
* byte 2: y7 y6 y5 y4 y3 y2 y1 y0
*
* swr/swl are the left/right buttons.
* x-neg/y-neg are the x and y delta negative bits
* x-over/y-over are the x and y overflow bits
*
* ---
*
* HGPK Advanced Mode - single-mode format
*
* byte 0(PT): 1 1 0 0 1 1 1 1
* byte 0(GS): 1 1 1 1 1 1 1 1
* byte 1: 0 x6 x5 x4 x3 x2 x1 x0
* byte 2(PT): 0 0 x9 x8 x7 ? pt-dsw 0
* byte 2(GS): 0 x10 x9 x8 x7 ? gs-dsw pt-dsw
* byte 3: 0 y9 y8 y7 1 0 swr swl
* byte 4: 0 y6 y5 y4 y3 y2 y1 y0
* byte 5: 0 z6 z5 z4 z3 z2 z1 z0
*
* ?'s are not defined in the protocol spec, may vary between models.
*
* swr/swl are the left/right buttons.
*
* pt-dsw/gs-dsw indicate that the pt/gs sensor is detecting a
* pen/finger
*/
static bool hgpk_is_byte_valid(struct psmouse *psmouse, unsigned char *packet)
{
struct hgpk_data *priv = psmouse->private;
int pktcnt = psmouse->pktcnt;
bool valid;
switch (priv->mode) {
case HGPK_MODE_MOUSE:
valid = (packet[0] & 0x0C) == 0x08;
break;
case HGPK_MODE_GLIDESENSOR:
valid = pktcnt == 1 ?
packet[0] == HGPK_GS : !(packet[pktcnt - 1] & 0x80);
break;
case HGPK_MODE_PENTABLET:
valid = pktcnt == 1 ?
packet[0] == HGPK_PT : !(packet[pktcnt - 1] & 0x80);
break;
default:
valid = false;
break;
}
if (!valid)
hgpk_dbg(psmouse,
"bad data, mode %d (%d) %02x %02x %02x %02x %02x %02x\n",
priv->mode, pktcnt,
psmouse->packet[0], psmouse->packet[1],
psmouse->packet[2], psmouse->packet[3],
psmouse->packet[4], psmouse->packet[5]);
return valid;
}
static void hgpk_process_advanced_packet(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
struct input_dev *idev = psmouse->dev;
unsigned char *packet = psmouse->packet;
int down = !!(packet[2] & 2);
int left = !!(packet[3] & 1);
int right = !!(packet[3] & 2);
int x = packet[1] | ((packet[2] & 0x78) << 4);
int y = packet[4] | ((packet[3] & 0x70) << 3);
if (priv->mode == HGPK_MODE_GLIDESENSOR) {
int pt_down = !!(packet[2] & 1);
int finger_down = !!(packet[2] & 2);
int z = packet[5];
input_report_abs(idev, ABS_PRESSURE, z);
if (tpdebug)
hgpk_dbg(psmouse, "pd=%d fd=%d z=%d",
pt_down, finger_down, z);
} else {
/*
* PenTablet mode does not report pressure, so we don't
* report it here
*/
if (tpdebug)
hgpk_dbg(psmouse, "pd=%d ", down);
}
if (tpdebug)
hgpk_dbg(psmouse, "l=%d r=%d x=%d y=%d\n", left, right, x, y);
input_report_key(idev, BTN_TOUCH, down);
input_report_key(idev, BTN_LEFT, left);
input_report_key(idev, BTN_RIGHT, right);
/*
* If this packet says that the finger was removed, reset our position
* tracking so that we don't erroneously detect a jump on next press.
*/
if (!down) {
hgpk_reset_hack_state(psmouse);
goto done;
}
/*
* Weed out duplicate packets (we get quite a few, and they mess up
* our jump detection)
*/
if (x == priv->abs_x && y == priv->abs_y) {
if (++priv->dupe_count > SPEW_WATCH_COUNT) {
if (tpdebug)
hgpk_dbg(psmouse, "hard spew detected\n");
priv->spew_flag = RECALIBRATING;
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(spew_delay));
}
goto done;
}
/* not a duplicate, continue with position reporting */
priv->dupe_count = 0;
/* Don't apply hacks in PT mode, it seems reliable */
if (priv->mode != HGPK_MODE_PENTABLET && priv->abs_x != -1) {
int x_diff = priv->abs_x - x;
int y_diff = priv->abs_y - y;
if (hgpk_discard_decay_hack(psmouse, x_diff, y_diff)) {
if (tpdebug)
hgpk_dbg(psmouse, "discarding\n");
goto done;
}
hgpk_spewing_hack(psmouse, left, right, x_diff, y_diff);
}
input_report_abs(idev, ABS_X, x);
input_report_abs(idev, ABS_Y, y);
priv->abs_x = x;
priv->abs_y = y;
done:
input_sync(idev);
}
static void hgpk_process_simple_packet(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
unsigned char *packet = psmouse->packet;
int left = packet[0] & 1;
int right = (packet[0] >> 1) & 1;
int x = packet[1] - ((packet[0] << 4) & 0x100);
int y = ((packet[0] << 3) & 0x100) - packet[2];
if (packet[0] & 0xc0)
hgpk_dbg(psmouse,
"overflow -- 0x%02x 0x%02x 0x%02x\n",
packet[0], packet[1], packet[2]);
if (hgpk_discard_decay_hack(psmouse, x, y)) {
if (tpdebug)
hgpk_dbg(psmouse, "discarding\n");
return;
}
hgpk_spewing_hack(psmouse, left, right, x, y);
if (tpdebug)
hgpk_dbg(psmouse, "l=%d r=%d x=%d y=%d\n", left, right, x, y);
input_report_key(dev, BTN_LEFT, left);
input_report_key(dev, BTN_RIGHT, right);
input_report_rel(dev, REL_X, x);
input_report_rel(dev, REL_Y, y);
input_sync(dev);
}
static psmouse_ret_t hgpk_process_byte(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
if (!hgpk_is_byte_valid(psmouse, psmouse->packet))
return PSMOUSE_BAD_DATA;
if (psmouse->pktcnt >= psmouse->pktsize) {
if (priv->mode == HGPK_MODE_MOUSE)
hgpk_process_simple_packet(psmouse);
else
hgpk_process_advanced_packet(psmouse);
return PSMOUSE_FULL_PACKET;
}
if (priv->recalib_window) {
if (time_before(jiffies, priv->recalib_window)) {
/*
* ugh, got a packet inside our recalibration
* window, schedule another recalibration.
*/
hgpk_dbg(psmouse,
"packet inside calibration window, "
"queueing another recalibration\n");
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(post_interrupt_delay));
}
priv->recalib_window = 0;
}
return PSMOUSE_GOOD_DATA;
}
static int hgpk_select_mode(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
struct hgpk_data *priv = psmouse->private;
int i;
int cmd;
/*
* 4 disables to enable advanced mode
* then 3 0xf2 bytes as the preamble for GS/PT selection
*/
const int advanced_init[] = {
PSMOUSE_CMD_DISABLE, PSMOUSE_CMD_DISABLE,
PSMOUSE_CMD_DISABLE, PSMOUSE_CMD_DISABLE,
0xf2, 0xf2, 0xf2,
};
switch (priv->mode) {
case HGPK_MODE_MOUSE:
psmouse->pktsize = 3;
break;
case HGPK_MODE_GLIDESENSOR:
case HGPK_MODE_PENTABLET:
psmouse->pktsize = 6;
/* Switch to 'Advanced mode.', four disables in a row. */
for (i = 0; i < ARRAY_SIZE(advanced_init); i++)
if (ps2_command(ps2dev, NULL, advanced_init[i]))
return -EIO;
/* select between GlideSensor (mouse) or PenTablet */
cmd = priv->mode == HGPK_MODE_GLIDESENSOR ?
PSMOUSE_CMD_SETSCALE11 : PSMOUSE_CMD_SETSCALE21;
if (ps2_command(ps2dev, NULL, cmd))
return -EIO;
break;
default:
return -EINVAL;
}
return 0;
}
static void hgpk_setup_input_device(struct input_dev *input,
struct input_dev *old_input,
enum hgpk_mode mode)
{
if (old_input) {
input->name = old_input->name;
input->phys = old_input->phys;
input->id = old_input->id;
input->dev.parent = old_input->dev.parent;
}
memset(input->evbit, 0, sizeof(input->evbit));
memset(input->relbit, 0, sizeof(input->relbit));
memset(input->keybit, 0, sizeof(input->keybit));
/* All modes report left and right buttons */
__set_bit(EV_KEY, input->evbit);
__set_bit(BTN_LEFT, input->keybit);
__set_bit(BTN_RIGHT, input->keybit);
switch (mode) {
case HGPK_MODE_MOUSE:
__set_bit(EV_REL, input->evbit);
__set_bit(REL_X, input->relbit);
__set_bit(REL_Y, input->relbit);
break;
case HGPK_MODE_GLIDESENSOR:
__set_bit(BTN_TOUCH, input->keybit);
__set_bit(BTN_TOOL_FINGER, input->keybit);
__set_bit(EV_ABS, input->evbit);
/* GlideSensor has pressure sensor, PenTablet does not */
input_set_abs_params(input, ABS_PRESSURE, 0, 15, 0, 0);
/* From device specs */
input_set_abs_params(input, ABS_X, 0, 399, 0, 0);
input_set_abs_params(input, ABS_Y, 0, 290, 0, 0);
/* Calculated by hand based on usable size (52mm x 38mm) */
input_abs_set_res(input, ABS_X, 8);
input_abs_set_res(input, ABS_Y, 8);
break;
case HGPK_MODE_PENTABLET:
__set_bit(BTN_TOUCH, input->keybit);
__set_bit(BTN_TOOL_FINGER, input->keybit);
__set_bit(EV_ABS, input->evbit);
/* From device specs */
input_set_abs_params(input, ABS_X, 0, 999, 0, 0);
input_set_abs_params(input, ABS_Y, 5, 239, 0, 0);
/* Calculated by hand based on usable size (156mm x 38mm) */
input_abs_set_res(input, ABS_X, 6);
input_abs_set_res(input, ABS_Y, 8);
break;
default:
BUG();
}
}
static int hgpk_reset_device(struct psmouse *psmouse, bool recalibrate)
{
int err;
psmouse_reset(psmouse);
if (recalibrate) {
struct ps2dev *ps2dev = &psmouse->ps2dev;
/* send the recalibrate request */
if (ps2_command(ps2dev, NULL, 0xf5) ||
ps2_command(ps2dev, NULL, 0xf5) ||
ps2_command(ps2dev, NULL, 0xe6) ||
ps2_command(ps2dev, NULL, 0xf5)) {
return -1;
}
/* according to ALPS, 150mS is required for recalibration */
msleep(150);
}
err = hgpk_select_mode(psmouse);
if (err) {
hgpk_err(psmouse, "failed to select mode\n");
return err;
}
hgpk_reset_hack_state(psmouse);
return 0;
}
static int hgpk_force_recalibrate(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
struct hgpk_data *priv = psmouse->private;
int err;
/* C-series touchpads added the recalibrate command */
if (psmouse->model < HGPK_MODEL_C)
return 0;
if (!autorecal) {
hgpk_dbg(psmouse, "recalibrations disabled, ignoring\n");
return 0;
}
hgpk_dbg(psmouse, "recalibrating touchpad..\n");
/* we don't want to race with the irq handler, nor with resyncs */
psmouse_set_state(psmouse, PSMOUSE_INITIALIZING);
/* start by resetting the device */
err = hgpk_reset_device(psmouse, true);
if (err)
return err;
/*
* XXX: If a finger is down during this delay, recalibration will
* detect capacitance incorrectly. This is a hardware bug, and
* we don't have a good way to deal with it. The 2s window stuff
* (below) is our best option for now.
*/
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_ENABLE))
return -1;
psmouse_set_state(psmouse, PSMOUSE_ACTIVATED);
if (tpdebug)
hgpk_dbg(psmouse, "touchpad reactivated\n");
/*
* If we get packets right away after recalibrating, it's likely
* that a finger was on the touchpad. If so, it's probably
* miscalibrated, so we optionally schedule another.
*/
if (recal_guard_time)
priv->recalib_window = jiffies +
msecs_to_jiffies(recal_guard_time);
return 0;
}
/*
* This puts the touchpad in a power saving mode; according to ALPS, current
* consumption goes down to 50uA after running this. To turn power back on,
* we drive MS-DAT low. Measuring with a 1mA resolution ammeter says that
* the current on the SUS_3.3V rail drops from 3mA or 4mA to 0 when we do this.
*
* We have no formal spec that details this operation -- the low-power
* sequence came from a long-lost email trail.
*/
static int hgpk_toggle_powersave(struct psmouse *psmouse, int enable)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
int timeo;
int err;
/* Added on D-series touchpads */
if (psmouse->model < HGPK_MODEL_D)
return 0;
if (enable) {
psmouse_set_state(psmouse, PSMOUSE_INITIALIZING);
/*
* Sending a byte will drive MS-DAT low; this will wake up
* the controller. Once we get an ACK back from it, it
* means we can continue with the touchpad re-init. ALPS
* tells us that 1s should be long enough, so set that as
* the upper bound. (in practice, it takes about 3 loops.)
*/
for (timeo = 20; timeo > 0; timeo--) {
if (!ps2_sendbyte(&psmouse->ps2dev,
PSMOUSE_CMD_DISABLE, 20))
break;
msleep(25);
}
err = hgpk_reset_device(psmouse, false);
if (err) {
hgpk_err(psmouse, "Failed to reset device!\n");
return err;
}
/* should be all set, enable the touchpad */
ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_ENABLE);
psmouse_set_state(psmouse, PSMOUSE_ACTIVATED);
hgpk_dbg(psmouse, "Touchpad powered up.\n");
} else {
hgpk_dbg(psmouse, "Powering off touchpad.\n");
if (ps2_command(ps2dev, NULL, 0xec) ||
ps2_command(ps2dev, NULL, 0xec) ||
ps2_command(ps2dev, NULL, 0xea)) {
return -1;
}
psmouse_set_state(psmouse, PSMOUSE_IGNORE);
/* probably won't see an ACK, the touchpad will be off */
ps2_sendbyte(&psmouse->ps2dev, 0xec, 20);
}
return 0;
}
static int hgpk_poll(struct psmouse *psmouse)
{
/* We can't poll, so always return failure. */
return -1;
}
static int hgpk_reconnect(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
/*
* During suspend/resume the ps2 rails remain powered. We don't want
* to do a reset because it's flush data out of buffers; however,
* earlier prototypes (B1) had some brokenness that required a reset.
*/
if (olpc_board_at_least(olpc_board(0xb2)))
if (psmouse->ps2dev.serio->dev.power.power_state.event !=
PM_EVENT_ON)
return 0;
priv->powered = 1;
return hgpk_reset_device(psmouse, false);
}
static ssize_t hgpk_show_powered(struct psmouse *psmouse, void *data, char *buf)
{
struct hgpk_data *priv = psmouse->private;
return sprintf(buf, "%d\n", priv->powered);
}
static ssize_t hgpk_set_powered(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct hgpk_data *priv = psmouse->private;
unsigned long value;
int err;
err = strict_strtoul(buf, 10, &value);
if (err || value > 1)
return -EINVAL;
if (value != priv->powered) {
/*
* hgpk_toggle_power will deal w/ state so
* we're not racing w/ irq
*/
err = hgpk_toggle_powersave(psmouse, value);
if (!err)
priv->powered = value;
}
return err ? err : count;
}
__PSMOUSE_DEFINE_ATTR(powered, S_IWUSR | S_IRUGO, NULL,
hgpk_show_powered, hgpk_set_powered, false);
static ssize_t attr_show_mode(struct psmouse *psmouse, void *data, char *buf)
{
struct hgpk_data *priv = psmouse->private;
return sprintf(buf, "%s\n", hgpk_mode_names[priv->mode]);
}
static ssize_t attr_set_mode(struct psmouse *psmouse, void *data,
const char *buf, size_t len)
{
struct hgpk_data *priv = psmouse->private;
enum hgpk_mode old_mode = priv->mode;
enum hgpk_mode new_mode = hgpk_mode_from_name(buf, len);
struct input_dev *old_dev = psmouse->dev;
struct input_dev *new_dev;
int err;
if (new_mode == HGPK_MODE_INVALID)
return -EINVAL;
if (old_mode == new_mode)
return len;
new_dev = input_allocate_device();
if (!new_dev)
return -ENOMEM;
psmouse_set_state(psmouse, PSMOUSE_INITIALIZING);
/* Switch device into the new mode */
priv->mode = new_mode;
err = hgpk_reset_device(psmouse, false);
if (err)
goto err_try_restore;
hgpk_setup_input_device(new_dev, old_dev, new_mode);
psmouse_set_state(psmouse, PSMOUSE_CMD_MODE);
err = input_register_device(new_dev);
if (err)
goto err_try_restore;
psmouse->dev = new_dev;
input_unregister_device(old_dev);
return len;
err_try_restore:
input_free_device(new_dev);
priv->mode = old_mode;
hgpk_reset_device(psmouse, false);
return err;
}
PSMOUSE_DEFINE_ATTR(hgpk_mode, S_IWUSR | S_IRUGO, NULL,
attr_show_mode, attr_set_mode);
static ssize_t hgpk_trigger_recal_show(struct psmouse *psmouse,
void *data, char *buf)
{
return -EINVAL;
}
static ssize_t hgpk_trigger_recal(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct hgpk_data *priv = psmouse->private;
unsigned long value;
int err;
err = strict_strtoul(buf, 10, &value);
if (err || value != 1)
return -EINVAL;
/*
* We queue work instead of doing recalibration right here
* to avoid adding locking to to hgpk_force_recalibrate()
* since workqueue provides serialization.
*/
psmouse_queue_work(psmouse, &priv->recalib_wq, 0);
return count;
}
__PSMOUSE_DEFINE_ATTR(recalibrate, S_IWUSR | S_IRUGO, NULL,
hgpk_trigger_recal_show, hgpk_trigger_recal, false);
static void hgpk_disconnect(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_powered.dattr);
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_hgpk_mode.dattr);
if (psmouse->model >= HGPK_MODEL_C)
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_recalibrate.dattr);
psmouse_reset(psmouse);
kfree(priv);
}
static void hgpk_recalib_work(struct work_struct *work)
{
struct delayed_work *w = to_delayed_work(work);
struct hgpk_data *priv = container_of(w, struct hgpk_data, recalib_wq);
struct psmouse *psmouse = priv->psmouse;
if (hgpk_force_recalibrate(psmouse))
hgpk_err(psmouse, "recalibration failed!\n");
}
static int hgpk_register(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
int err;
/* register handlers */
psmouse->protocol_handler = hgpk_process_byte;
psmouse->poll = hgpk_poll;
psmouse->disconnect = hgpk_disconnect;
psmouse->reconnect = hgpk_reconnect;
/* Disable the idle resync. */
psmouse->resync_time = 0;
/* Reset after a lot of bad bytes. */
psmouse->resetafter = 1024;
hgpk_setup_input_device(psmouse->dev, NULL, priv->mode);
err = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_powered.dattr);
if (err) {
hgpk_err(psmouse, "Failed creating 'powered' sysfs node\n");
return err;
}
err = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_hgpk_mode.dattr);
if (err) {
hgpk_err(psmouse, "Failed creating 'hgpk_mode' sysfs node\n");
goto err_remove_powered;
}
/* C-series touchpads added the recalibrate command */
if (psmouse->model >= HGPK_MODEL_C) {
err = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_recalibrate.dattr);
if (err) {
hgpk_err(psmouse,
"Failed creating 'recalibrate' sysfs node\n");
goto err_remove_mode;
}
}
return 0;
err_remove_mode:
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_hgpk_mode.dattr);
err_remove_powered:
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_powered.dattr);
return err;
}
int hgpk_init(struct psmouse *psmouse)
{
struct hgpk_data *priv;
int err;
priv = kzalloc(sizeof(struct hgpk_data), GFP_KERNEL);
if (!priv) {
err = -ENOMEM;
goto alloc_fail;
}
psmouse->private = priv;
priv->psmouse = psmouse;
priv->powered = true;
priv->mode = hgpk_default_mode;
INIT_DELAYED_WORK(&priv->recalib_wq, hgpk_recalib_work);
err = hgpk_reset_device(psmouse, false);
if (err)
goto init_fail;
err = hgpk_register(psmouse);
if (err)
goto init_fail;
return 0;
init_fail:
kfree(priv);
alloc_fail:
return err;
}
static enum hgpk_model_t hgpk_get_model(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[3];
/* E7, E7, E7, E9 gets us a 3 byte identifier */
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO)) {
return -EIO;
}
hgpk_dbg(psmouse, "ID: %02x %02x %02x\n", param[0], param[1], param[2]);
/* HGPK signature: 0x67, 0x00, 0x<model> */
if (param[0] != 0x67 || param[1] != 0x00)
return -ENODEV;
hgpk_info(psmouse, "OLPC touchpad revision 0x%x\n", param[2]);
return param[2];
}
int hgpk_detect(struct psmouse *psmouse, bool set_properties)
{
int version;
version = hgpk_get_model(psmouse);
if (version < 0)
return version;
if (set_properties) {
psmouse->vendor = "ALPS";
psmouse->name = "HGPK";
psmouse->model = version;
}
return 0;
}
void hgpk_module_init(void)
{
hgpk_default_mode = hgpk_mode_from_name(hgpk_mode_name,
strlen(hgpk_mode_name));
if (hgpk_default_mode == HGPK_MODE_INVALID) {
hgpk_default_mode = HGPK_MODE_MOUSE;
strlcpy(hgpk_mode_name, hgpk_mode_names[HGPK_MODE_MOUSE],
sizeof(hgpk_mode_name));
}
}
| gpl-2.0 |
Xmister/endeavoru-jb-crc-3.1.10 | arch/arm/mach-at91/board-eb9200.c | 382 | 3281 | /*
* linux/arch/arm/mach-at91/board-eb9200.c
*
* Copyright (C) 2005 SAN People, adapted for ATEB9200 from Embest
* by Andrew Patrikalakis
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/types.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/device.h>
#include <mach/hardware.h>
#include <asm/setup.h>
#include <asm/mach-types.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <mach/board.h>
#include <mach/gpio.h>
#include "generic.h"
static void __init eb9200_init_early(void)
{
/* Initialize processor: 18.432 MHz crystal */
at91_initialize(18432000);
/* DBGU on ttyS0. (Rx & Tx only) */
at91_register_uart(0, 0, 0);
/* USART1 on ttyS1. (Rx, Tx, CTS, RTS, DTR, DSR, DCD, RI) */
at91_register_uart(AT91RM9200_ID_US1, 1, ATMEL_UART_CTS | ATMEL_UART_RTS
| ATMEL_UART_DTR | ATMEL_UART_DSR | ATMEL_UART_DCD
| ATMEL_UART_RI);
/* USART2 on ttyS2. (Rx, Tx) - IRDA */
at91_register_uart(AT91RM9200_ID_US2, 2, 0);
/* set serial console to ttyS0 (ie, DBGU) */
at91_set_serial_console(0);
}
static struct at91_eth_data __initdata eb9200_eth_data = {
.phy_irq_pin = AT91_PIN_PC4,
.is_rmii = 1,
};
static struct at91_usbh_data __initdata eb9200_usbh_data = {
.ports = 2,
};
static struct at91_udc_data __initdata eb9200_udc_data = {
.vbus_pin = AT91_PIN_PD4,
.pullup_pin = AT91_PIN_PD5,
};
static struct at91_cf_data __initdata eb9200_cf_data = {
.det_pin = AT91_PIN_PB0,
.rst_pin = AT91_PIN_PC5,
// .irq_pin = ... not connected
// .vcc_pin = ... always powered
};
static struct at91_mmc_data __initdata eb9200_mmc_data = {
.slot_b = 0,
.wire4 = 1,
};
static struct i2c_board_info __initdata eb9200_i2c_devices[] = {
{
I2C_BOARD_INFO("24c512", 0x50),
},
};
static void __init eb9200_board_init(void)
{
/* Serial */
at91_add_device_serial();
/* Ethernet */
at91_add_device_eth(&eb9200_eth_data);
/* USB Host */
at91_add_device_usbh(&eb9200_usbh_data);
/* USB Device */
at91_add_device_udc(&eb9200_udc_data);
/* I2C */
at91_add_device_i2c(eb9200_i2c_devices, ARRAY_SIZE(eb9200_i2c_devices));
/* Compact Flash */
at91_add_device_cf(&eb9200_cf_data);
/* SPI */
at91_add_device_spi(NULL, 0);
/* MMC */
/* only supports 1 or 4 bit interface, not wired through to SPI */
at91_add_device_mmc(0, &eb9200_mmc_data);
}
MACHINE_START(ATEB9200, "Embest ATEB9200")
.timer = &at91rm9200_timer,
.map_io = at91_map_io,
.init_early = eb9200_init_early,
.init_irq = at91_init_irq_default,
.init_machine = eb9200_board_init,
MACHINE_END
| gpl-2.0 |
rumirand/GalaxyPlayer5-kernel | arch/arm/kernel/ftrace.c | 894 | 2515 | /*
* Dynamic function tracing support.
*
* Copyright (C) 2008 Abhishek Sagar <sagar.abhishek@gmail.com>
*
* For licencing details, see COPYING.
*
* Defines low-level handling of mcount calls when the kernel
* is compiled with the -pg flag. When using dynamic ftrace, the
* mcount call-sites get patched lazily with NOP till they are
* enabled. All code mutation routines here take effect atomically.
*/
#include <linux/ftrace.h>
#include <asm/cacheflush.h>
#include <asm/ftrace.h>
#define PC_OFFSET 8
#define BL_OPCODE 0xeb000000
#define BL_OFFSET_MASK 0x00ffffff
static unsigned long bl_insn;
static const unsigned long NOP = 0xe1a00000; /* mov r0, r0 */
unsigned char *ftrace_nop_replace(void)
{
return (char *)&NOP;
}
/* construct a branch (BL) instruction to addr */
unsigned char *ftrace_call_replace(unsigned long pc, unsigned long addr)
{
long offset;
offset = (long)addr - (long)(pc + PC_OFFSET);
if (unlikely(offset < -33554432 || offset > 33554428)) {
/* Can't generate branches that far (from ARM ARM). Ftrace
* doesn't generate branches outside of kernel text.
*/
WARN_ON_ONCE(1);
return NULL;
}
offset = (offset >> 2) & BL_OFFSET_MASK;
bl_insn = BL_OPCODE | offset;
return (unsigned char *)&bl_insn;
}
int ftrace_modify_code(unsigned long pc, unsigned char *old_code,
unsigned char *new_code)
{
unsigned long err = 0, replaced = 0, old, new;
old = *(unsigned long *)old_code;
new = *(unsigned long *)new_code;
__asm__ __volatile__ (
"1: ldr %1, [%2] \n"
" cmp %1, %4 \n"
"2: streq %3, [%2] \n"
" cmpne %1, %3 \n"
" movne %0, #2 \n"
"3:\n"
".pushsection .fixup, \"ax\"\n"
"4: mov %0, #1 \n"
" b 3b \n"
".popsection\n"
".pushsection __ex_table, \"a\"\n"
" .long 1b, 4b \n"
" .long 2b, 4b \n"
".popsection\n"
: "=r"(err), "=r"(replaced)
: "r"(pc), "r"(new), "r"(old), "0"(err), "1"(replaced)
: "memory");
if (!err && (replaced == old))
flush_icache_range(pc, pc + MCOUNT_INSN_SIZE);
return err;
}
int ftrace_update_ftrace_func(ftrace_func_t func)
{
int ret;
unsigned long pc, old;
unsigned char *new;
pc = (unsigned long)&ftrace_call;
memcpy(&old, &ftrace_call, MCOUNT_INSN_SIZE);
new = ftrace_call_replace(pc, (unsigned long)func);
ret = ftrace_modify_code(pc, (unsigned char *)&old, new);
return ret;
}
/* run from ftrace_init with irqs disabled */
int __init ftrace_dyn_arch_init(void *data)
{
ftrace_mcount_set(data);
return 0;
}
| gpl-2.0 |
GuoqingJiang/linux | drivers/staging/comedi/drivers/dt2815.c | 894 | 6150 | /*
comedi/drivers/dt2815.c
Hardware driver for Data Translation DT2815
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1999 Anders Blomdell <anders.blomdell@control.lth.se>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
/*
Driver: dt2815
Description: Data Translation DT2815
Author: ds
Status: mostly complete, untested
Devices: [Data Translation] DT2815 (dt2815)
I'm not sure anyone has ever tested this board. If you have information
contrary, please update.
Configuration options:
[0] - I/O port base base address
[1] - IRQ (unused)
[2] - Voltage unipolar/bipolar configuration
0 == unipolar 5V (0V -- +5V)
1 == bipolar 5V (-5V -- +5V)
[3] - Current offset configuration
0 == disabled (0mA -- +32mAV)
1 == enabled (+4mA -- +20mAV)
[4] - Firmware program configuration
0 == program 1 (see manual table 5-4)
1 == program 2 (see manual table 5-4)
2 == program 3 (see manual table 5-4)
3 == program 4 (see manual table 5-4)
[5] - Analog output 0 range configuration
0 == voltage
1 == current
[6] - Analog output 1 range configuration (same options)
[7] - Analog output 2 range configuration (same options)
[8] - Analog output 3 range configuration (same options)
[9] - Analog output 4 range configuration (same options)
[10] - Analog output 5 range configuration (same options)
[11] - Analog output 6 range configuration (same options)
[12] - Analog output 7 range configuration (same options)
*/
#include <linux/module.h>
#include "../comedidev.h"
#include <linux/delay.h>
#define DT2815_DATA 0
#define DT2815_STATUS 1
struct dt2815_private {
const struct comedi_lrange *range_type_list[8];
unsigned int ao_readback[8];
};
static int dt2815_ao_status(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn,
unsigned long context)
{
unsigned int status;
status = inb(dev->iobase + DT2815_STATUS);
if (status == context)
return 0;
return -EBUSY;
}
static int dt2815_ao_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct dt2815_private *devpriv = dev->private;
int i;
int chan = CR_CHAN(insn->chanspec);
for (i = 0; i < insn->n; i++)
data[i] = devpriv->ao_readback[chan];
return i;
}
static int dt2815_ao_insn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
struct dt2815_private *devpriv = dev->private;
int i;
int chan = CR_CHAN(insn->chanspec);
unsigned int lo, hi;
int ret;
for (i = 0; i < insn->n; i++) {
lo = ((data[i] & 0x0f) << 4) | (chan << 1) | 0x01;
hi = (data[i] & 0xff0) >> 4;
ret = comedi_timeout(dev, s, insn, dt2815_ao_status, 0x00);
if (ret)
return ret;
outb(lo, dev->iobase + DT2815_DATA);
ret = comedi_timeout(dev, s, insn, dt2815_ao_status, 0x10);
if (ret)
return ret;
devpriv->ao_readback[chan] = data[i];
}
return i;
}
/*
options[0] Board base address
options[1] IRQ (not applicable)
options[2] Voltage unipolar/bipolar configuration
0 == unipolar 5V (0V -- +5V)
1 == bipolar 5V (-5V -- +5V)
options[3] Current offset configuration
0 == disabled (0mA -- +32mAV)
1 == enabled (+4mA -- +20mAV)
options[4] Firmware program configuration
0 == program 1 (see manual table 5-4)
1 == program 2 (see manual table 5-4)
2 == program 3 (see manual table 5-4)
3 == program 4 (see manual table 5-4)
options[5] Analog output 0 range configuration
0 == voltage
1 == current
options[6] Analog output 1 range configuration
...
options[12] Analog output 7 range configuration
0 == voltage
1 == current
*/
static int dt2815_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
struct dt2815_private *devpriv;
struct comedi_subdevice *s;
int i;
const struct comedi_lrange *current_range_type, *voltage_range_type;
int ret;
ret = comedi_request_region(dev, it->options[0], 0x2);
if (ret)
return ret;
ret = comedi_alloc_subdevices(dev, 1);
if (ret)
return ret;
devpriv = comedi_alloc_devpriv(dev, sizeof(*devpriv));
if (!devpriv)
return -ENOMEM;
s = &dev->subdevices[0];
/* ao subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE;
s->maxdata = 0xfff;
s->n_chan = 8;
s->insn_write = dt2815_ao_insn;
s->insn_read = dt2815_ao_insn_read;
s->range_table_list = devpriv->range_type_list;
current_range_type = (it->options[3])
? &range_4_20mA : &range_0_32mA;
voltage_range_type = (it->options[2])
? &range_bipolar5 : &range_unipolar5;
for (i = 0; i < 8; i++) {
devpriv->range_type_list[i] = (it->options[5 + i])
? current_range_type : voltage_range_type;
}
/* Init the 2815 */
outb(0x00, dev->iobase + DT2815_STATUS);
for (i = 0; i < 100; i++) {
/* This is incredibly slow (approx 20 ms) */
unsigned int status;
udelay(1000);
status = inb(dev->iobase + DT2815_STATUS);
if (status == 4) {
unsigned int program;
program = (it->options[4] & 0x3) << 3 | 0x7;
outb(program, dev->iobase + DT2815_DATA);
dev_dbg(dev->class_dev, "program: 0x%x (@t=%d)\n",
program, i);
break;
} else if (status != 0x00) {
dev_dbg(dev->class_dev,
"unexpected status 0x%x (@t=%d)\n",
status, i);
if (status & 0x60)
outb(0x00, dev->iobase + DT2815_STATUS);
}
}
return 0;
}
static struct comedi_driver dt2815_driver = {
.driver_name = "dt2815",
.module = THIS_MODULE,
.attach = dt2815_attach,
.detach = comedi_legacy_detach,
};
module_comedi_driver(dt2815_driver);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Evervolv/android_kernel_htc_msm7x30 | drivers/scsi/sd_dif.c | 1406 | 12662 | /*
* sd_dif.c - SCSI Data Integrity Field
*
* Copyright (C) 2007, 2008 Oracle Corporation
* Written by: Martin K. Petersen <martin.petersen@oracle.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; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139,
* USA.
*
*/
#include <linux/blkdev.h>
#include <linux/crc-t10dif.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_dbg.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_driver.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_ioctl.h>
#include <scsi/scsicam.h>
#include <net/checksum.h>
#include "sd.h"
typedef __u16 (csum_fn) (void *, unsigned int);
static __u16 sd_dif_crc_fn(void *data, unsigned int len)
{
return cpu_to_be16(crc_t10dif(data, len));
}
static __u16 sd_dif_ip_fn(void *data, unsigned int len)
{
return ip_compute_csum(data, len);
}
/*
* Type 1 and Type 2 protection use the same format: 16 bit guard tag,
* 16 bit app tag, 32 bit reference tag.
*/
static void sd_dif_type1_generate(struct blk_integrity_exchg *bix, csum_fn *fn)
{
void *buf = bix->data_buf;
struct sd_dif_tuple *sdt = bix->prot_buf;
sector_t sector = bix->sector;
unsigned int i;
for (i = 0 ; i < bix->data_size ; i += bix->sector_size, sdt++) {
sdt->guard_tag = fn(buf, bix->sector_size);
sdt->ref_tag = cpu_to_be32(sector & 0xffffffff);
sdt->app_tag = 0;
buf += bix->sector_size;
sector++;
}
}
static void sd_dif_type1_generate_crc(struct blk_integrity_exchg *bix)
{
sd_dif_type1_generate(bix, sd_dif_crc_fn);
}
static void sd_dif_type1_generate_ip(struct blk_integrity_exchg *bix)
{
sd_dif_type1_generate(bix, sd_dif_ip_fn);
}
static int sd_dif_type1_verify(struct blk_integrity_exchg *bix, csum_fn *fn)
{
void *buf = bix->data_buf;
struct sd_dif_tuple *sdt = bix->prot_buf;
sector_t sector = bix->sector;
unsigned int i;
__u16 csum;
for (i = 0 ; i < bix->data_size ; i += bix->sector_size, sdt++) {
/* Unwritten sectors */
if (sdt->app_tag == 0xffff)
return 0;
/* Bad ref tag received from disk */
if (sdt->ref_tag == 0xffffffff) {
printk(KERN_ERR
"%s: bad phys ref tag on sector %lu\n",
bix->disk_name, (unsigned long)sector);
return -EIO;
}
if (be32_to_cpu(sdt->ref_tag) != (sector & 0xffffffff)) {
printk(KERN_ERR
"%s: ref tag error on sector %lu (rcvd %u)\n",
bix->disk_name, (unsigned long)sector,
be32_to_cpu(sdt->ref_tag));
return -EIO;
}
csum = fn(buf, bix->sector_size);
if (sdt->guard_tag != csum) {
printk(KERN_ERR "%s: guard tag error on sector %lu " \
"(rcvd %04x, data %04x)\n", bix->disk_name,
(unsigned long)sector,
be16_to_cpu(sdt->guard_tag), be16_to_cpu(csum));
return -EIO;
}
buf += bix->sector_size;
sector++;
}
return 0;
}
static int sd_dif_type1_verify_crc(struct blk_integrity_exchg *bix)
{
return sd_dif_type1_verify(bix, sd_dif_crc_fn);
}
static int sd_dif_type1_verify_ip(struct blk_integrity_exchg *bix)
{
return sd_dif_type1_verify(bix, sd_dif_ip_fn);
}
/*
* Functions for interleaving and deinterleaving application tags
*/
static void sd_dif_type1_set_tag(void *prot, void *tag_buf, unsigned int sectors)
{
struct sd_dif_tuple *sdt = prot;
u8 *tag = tag_buf;
unsigned int i, j;
for (i = 0, j = 0 ; i < sectors ; i++, j += 2, sdt++) {
sdt->app_tag = tag[j] << 8 | tag[j+1];
BUG_ON(sdt->app_tag == 0xffff);
}
}
static void sd_dif_type1_get_tag(void *prot, void *tag_buf, unsigned int sectors)
{
struct sd_dif_tuple *sdt = prot;
u8 *tag = tag_buf;
unsigned int i, j;
for (i = 0, j = 0 ; i < sectors ; i++, j += 2, sdt++) {
tag[j] = (sdt->app_tag & 0xff00) >> 8;
tag[j+1] = sdt->app_tag & 0xff;
}
}
static struct blk_integrity dif_type1_integrity_crc = {
.name = "T10-DIF-TYPE1-CRC",
.generate_fn = sd_dif_type1_generate_crc,
.verify_fn = sd_dif_type1_verify_crc,
.get_tag_fn = sd_dif_type1_get_tag,
.set_tag_fn = sd_dif_type1_set_tag,
.tuple_size = sizeof(struct sd_dif_tuple),
.tag_size = 0,
};
static struct blk_integrity dif_type1_integrity_ip = {
.name = "T10-DIF-TYPE1-IP",
.generate_fn = sd_dif_type1_generate_ip,
.verify_fn = sd_dif_type1_verify_ip,
.get_tag_fn = sd_dif_type1_get_tag,
.set_tag_fn = sd_dif_type1_set_tag,
.tuple_size = sizeof(struct sd_dif_tuple),
.tag_size = 0,
};
/*
* Type 3 protection has a 16-bit guard tag and 16 + 32 bits of opaque
* tag space.
*/
static void sd_dif_type3_generate(struct blk_integrity_exchg *bix, csum_fn *fn)
{
void *buf = bix->data_buf;
struct sd_dif_tuple *sdt = bix->prot_buf;
unsigned int i;
for (i = 0 ; i < bix->data_size ; i += bix->sector_size, sdt++) {
sdt->guard_tag = fn(buf, bix->sector_size);
sdt->ref_tag = 0;
sdt->app_tag = 0;
buf += bix->sector_size;
}
}
static void sd_dif_type3_generate_crc(struct blk_integrity_exchg *bix)
{
sd_dif_type3_generate(bix, sd_dif_crc_fn);
}
static void sd_dif_type3_generate_ip(struct blk_integrity_exchg *bix)
{
sd_dif_type3_generate(bix, sd_dif_ip_fn);
}
static int sd_dif_type3_verify(struct blk_integrity_exchg *bix, csum_fn *fn)
{
void *buf = bix->data_buf;
struct sd_dif_tuple *sdt = bix->prot_buf;
sector_t sector = bix->sector;
unsigned int i;
__u16 csum;
for (i = 0 ; i < bix->data_size ; i += bix->sector_size, sdt++) {
/* Unwritten sectors */
if (sdt->app_tag == 0xffff && sdt->ref_tag == 0xffffffff)
return 0;
csum = fn(buf, bix->sector_size);
if (sdt->guard_tag != csum) {
printk(KERN_ERR "%s: guard tag error on sector %lu " \
"(rcvd %04x, data %04x)\n", bix->disk_name,
(unsigned long)sector,
be16_to_cpu(sdt->guard_tag), be16_to_cpu(csum));
return -EIO;
}
buf += bix->sector_size;
sector++;
}
return 0;
}
static int sd_dif_type3_verify_crc(struct blk_integrity_exchg *bix)
{
return sd_dif_type3_verify(bix, sd_dif_crc_fn);
}
static int sd_dif_type3_verify_ip(struct blk_integrity_exchg *bix)
{
return sd_dif_type3_verify(bix, sd_dif_ip_fn);
}
static void sd_dif_type3_set_tag(void *prot, void *tag_buf, unsigned int sectors)
{
struct sd_dif_tuple *sdt = prot;
u8 *tag = tag_buf;
unsigned int i, j;
for (i = 0, j = 0 ; i < sectors ; i++, j += 6, sdt++) {
sdt->app_tag = tag[j] << 8 | tag[j+1];
sdt->ref_tag = tag[j+2] << 24 | tag[j+3] << 16 |
tag[j+4] << 8 | tag[j+5];
}
}
static void sd_dif_type3_get_tag(void *prot, void *tag_buf, unsigned int sectors)
{
struct sd_dif_tuple *sdt = prot;
u8 *tag = tag_buf;
unsigned int i, j;
for (i = 0, j = 0 ; i < sectors ; i++, j += 2, sdt++) {
tag[j] = (sdt->app_tag & 0xff00) >> 8;
tag[j+1] = sdt->app_tag & 0xff;
tag[j+2] = (sdt->ref_tag & 0xff000000) >> 24;
tag[j+3] = (sdt->ref_tag & 0xff0000) >> 16;
tag[j+4] = (sdt->ref_tag & 0xff00) >> 8;
tag[j+5] = sdt->ref_tag & 0xff;
BUG_ON(sdt->app_tag == 0xffff || sdt->ref_tag == 0xffffffff);
}
}
static struct blk_integrity dif_type3_integrity_crc = {
.name = "T10-DIF-TYPE3-CRC",
.generate_fn = sd_dif_type3_generate_crc,
.verify_fn = sd_dif_type3_verify_crc,
.get_tag_fn = sd_dif_type3_get_tag,
.set_tag_fn = sd_dif_type3_set_tag,
.tuple_size = sizeof(struct sd_dif_tuple),
.tag_size = 0,
};
static struct blk_integrity dif_type3_integrity_ip = {
.name = "T10-DIF-TYPE3-IP",
.generate_fn = sd_dif_type3_generate_ip,
.verify_fn = sd_dif_type3_verify_ip,
.get_tag_fn = sd_dif_type3_get_tag,
.set_tag_fn = sd_dif_type3_set_tag,
.tuple_size = sizeof(struct sd_dif_tuple),
.tag_size = 0,
};
/*
* Configure exchange of protection information between OS and HBA.
*/
void sd_dif_config_host(struct scsi_disk *sdkp)
{
struct scsi_device *sdp = sdkp->device;
struct gendisk *disk = sdkp->disk;
u8 type = sdkp->protection_type;
int dif, dix;
dif = scsi_host_dif_capable(sdp->host, type);
dix = scsi_host_dix_capable(sdp->host, type);
if (!dix && scsi_host_dix_capable(sdp->host, 0)) {
dif = 0; dix = 1;
}
if (!dix)
return;
/* Enable DMA of protection information */
if (scsi_host_get_guard(sdkp->device->host) & SHOST_DIX_GUARD_IP)
if (type == SD_DIF_TYPE3_PROTECTION)
blk_integrity_register(disk, &dif_type3_integrity_ip);
else
blk_integrity_register(disk, &dif_type1_integrity_ip);
else
if (type == SD_DIF_TYPE3_PROTECTION)
blk_integrity_register(disk, &dif_type3_integrity_crc);
else
blk_integrity_register(disk, &dif_type1_integrity_crc);
sd_printk(KERN_NOTICE, sdkp,
"Enabling DIX %s protection\n", disk->integrity->name);
/* Signal to block layer that we support sector tagging */
if (dif && type && sdkp->ATO) {
if (type == SD_DIF_TYPE3_PROTECTION)
disk->integrity->tag_size = sizeof(u16) + sizeof(u32);
else
disk->integrity->tag_size = sizeof(u16);
sd_printk(KERN_NOTICE, sdkp, "DIF application tag size %u\n",
disk->integrity->tag_size);
}
}
/*
* The virtual start sector is the one that was originally submitted
* by the block layer. Due to partitioning, MD/DM cloning, etc. the
* actual physical start sector is likely to be different. Remap
* protection information to match the physical LBA.
*
* From a protocol perspective there's a slight difference between
* Type 1 and 2. The latter uses 32-byte CDBs exclusively, and the
* reference tag is seeded in the CDB. This gives us the potential to
* avoid virt->phys remapping during write. However, at read time we
* don't know whether the virt sector is the same as when we wrote it
* (we could be reading from real disk as opposed to MD/DM device. So
* we always remap Type 2 making it identical to Type 1.
*
* Type 3 does not have a reference tag so no remapping is required.
*/
int sd_dif_prepare(struct request *rq, sector_t hw_sector, unsigned int sector_sz)
{
const int tuple_sz = sizeof(struct sd_dif_tuple);
struct bio *bio;
struct scsi_disk *sdkp;
struct sd_dif_tuple *sdt;
unsigned int i, j;
u32 phys, virt;
/* Already remapped? */
if (rq->cmd_flags & REQ_INTEGRITY)
return 0;
sdkp = rq->bio->bi_bdev->bd_disk->private_data;
if (sdkp->protection_type == SD_DIF_TYPE3_PROTECTION)
return 0;
rq->cmd_flags |= REQ_INTEGRITY;
phys = hw_sector & 0xffffffff;
__rq_for_each_bio(bio, rq) {
struct bio_vec *iv;
virt = bio->bi_integrity->bip_sector & 0xffffffff;
bip_for_each_vec(iv, bio->bi_integrity, i) {
sdt = kmap_atomic(iv->bv_page, KM_USER0)
+ iv->bv_offset;
for (j = 0 ; j < iv->bv_len ; j += tuple_sz, sdt++) {
if (be32_to_cpu(sdt->ref_tag) != virt)
goto error;
sdt->ref_tag = cpu_to_be32(phys);
virt++;
phys++;
}
kunmap_atomic(sdt, KM_USER0);
}
}
return 0;
error:
kunmap_atomic(sdt, KM_USER0);
sd_printk(KERN_ERR, sdkp, "%s: virt %u, phys %u, ref %u, app %4x\n",
__func__, virt, phys, be32_to_cpu(sdt->ref_tag),
be16_to_cpu(sdt->app_tag));
return -EILSEQ;
}
/*
* Remap physical sector values in the reference tag to the virtual
* values expected by the block layer.
*/
void sd_dif_complete(struct scsi_cmnd *scmd, unsigned int good_bytes)
{
const int tuple_sz = sizeof(struct sd_dif_tuple);
struct scsi_disk *sdkp;
struct bio *bio;
struct sd_dif_tuple *sdt;
unsigned int i, j, sectors, sector_sz;
u32 phys, virt;
sdkp = scsi_disk(scmd->request->rq_disk);
if (sdkp->protection_type == SD_DIF_TYPE3_PROTECTION || good_bytes == 0)
return;
sector_sz = scmd->device->sector_size;
sectors = good_bytes / sector_sz;
phys = blk_rq_pos(scmd->request) & 0xffffffff;
if (sector_sz == 4096)
phys >>= 3;
__rq_for_each_bio(bio, scmd->request) {
struct bio_vec *iv;
virt = bio->bi_integrity->bip_sector & 0xffffffff;
bip_for_each_vec(iv, bio->bi_integrity, i) {
sdt = kmap_atomic(iv->bv_page, KM_USER0)
+ iv->bv_offset;
for (j = 0 ; j < iv->bv_len ; j += tuple_sz, sdt++) {
if (sectors == 0) {
kunmap_atomic(sdt, KM_USER0);
return;
}
if (be32_to_cpu(sdt->ref_tag) != phys &&
sdt->app_tag != 0xffff)
sdt->ref_tag = 0xffffffff; /* Bad ref */
else
sdt->ref_tag = cpu_to_be32(virt);
virt++;
phys++;
sectors--;
}
kunmap_atomic(sdt, KM_USER0);
}
}
}
| gpl-2.0 |
CyanogenMod/htc-kernel-doubleshot | arch/arm/mach-ixp4xx/dsmg600-pci.c | 2430 | 2058 | /*
* DSM-G600 board-level PCI initialization
*
* Copyright (C) 2006 Tower Technologies
* Author: Alessandro Zummo <a.zummo@towertech.it>
*
* based on ixdp425-pci.c:
* Copyright (C) 2002 Intel Corporation.
* Copyright (C) 2003-2004 MontaVista Software, Inc.
*
* Maintainer: http://www.nslu2-linux.org/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <asm/mach/pci.h>
#include <asm/mach-types.h>
#define MAX_DEV 4
#define IRQ_LINES 3
/* PCI controller GPIO to IRQ pin mappings */
#define INTA 11
#define INTB 10
#define INTC 9
#define INTD 8
#define INTE 7
#define INTF 6
void __init dsmg600_pci_preinit(void)
{
irq_set_irq_type(IXP4XX_GPIO_IRQ(INTA), IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(IXP4XX_GPIO_IRQ(INTB), IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(IXP4XX_GPIO_IRQ(INTC), IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(IXP4XX_GPIO_IRQ(INTD), IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(IXP4XX_GPIO_IRQ(INTE), IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(IXP4XX_GPIO_IRQ(INTF), IRQ_TYPE_LEVEL_LOW);
ixp4xx_pci_preinit();
}
static int __init dsmg600_map_irq(struct pci_dev *dev, u8 slot, u8 pin)
{
static int pci_irq_table[MAX_DEV][IRQ_LINES] = {
{ IXP4XX_GPIO_IRQ(INTE), -1, -1 },
{ IXP4XX_GPIO_IRQ(INTA), -1, -1 },
{ IXP4XX_GPIO_IRQ(INTB), IXP4XX_GPIO_IRQ(INTC),
IXP4XX_GPIO_IRQ(INTD) },
{ IXP4XX_GPIO_IRQ(INTF), -1, -1 },
};
if (slot >= 1 && slot <= MAX_DEV && pin >= 1 && pin <= IRQ_LINES)
return pci_irq_table[slot - 1][pin - 1];
return -1;
}
struct hw_pci __initdata dsmg600_pci = {
.nr_controllers = 1,
.preinit = dsmg600_pci_preinit,
.swizzle = pci_std_swizzle,
.setup = ixp4xx_setup,
.scan = ixp4xx_scan_bus,
.map_irq = dsmg600_map_irq,
};
int __init dsmg600_pci_init(void)
{
if (machine_is_dsmg600())
pci_common_init(&dsmg600_pci);
return 0;
}
subsys_initcall(dsmg600_pci_init);
| gpl-2.0 |
doslab/mool | arch/arm/mm/cache-feroceon-l2.c | 2686 | 8269 | /*
* arch/arm/mm/cache-feroceon-l2.c - Feroceon L2 cache controller support
*
* Copyright (C) 2008 Marvell Semiconductor
*
* 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.
*
* References:
* - Unified Layer 2 Cache for Feroceon CPU Cores,
* Document ID MV-S104858-00, Rev. A, October 23 2007.
*/
#include <linux/init.h>
#include <linux/highmem.h>
#include <asm/cacheflush.h>
#include <plat/cache-feroceon-l2.h>
/*
* Low-level cache maintenance operations.
*
* As well as the regular 'clean/invalidate/flush L2 cache line by
* MVA' instructions, the Feroceon L2 cache controller also features
* 'clean/invalidate L2 range by MVA' operations.
*
* Cache range operations are initiated by writing the start and
* end addresses to successive cp15 registers, and process every
* cache line whose first byte address lies in the inclusive range
* [start:end].
*
* The cache range operations stall the CPU pipeline until completion.
*
* The range operations require two successive cp15 writes, in
* between which we don't want to be preempted.
*/
static inline unsigned long l2_get_va(unsigned long paddr)
{
#ifdef CONFIG_HIGHMEM
/*
* Because range ops can't be done on physical addresses,
* we simply install a virtual mapping for it only for the
* TLB lookup to occur, hence no need to flush the untouched
* memory mapping afterwards (note: a cache flush may happen
* in some circumstances depending on the path taken in kunmap_atomic).
*/
void *vaddr = kmap_atomic_pfn(paddr >> PAGE_SHIFT);
return (unsigned long)vaddr + (paddr & ~PAGE_MASK);
#else
return __phys_to_virt(paddr);
#endif
}
static inline void l2_put_va(unsigned long vaddr)
{
#ifdef CONFIG_HIGHMEM
kunmap_atomic((void *)vaddr);
#endif
}
static inline void l2_clean_pa(unsigned long addr)
{
__asm__("mcr p15, 1, %0, c15, c9, 3" : : "r" (addr));
}
static inline void l2_clean_pa_range(unsigned long start, unsigned long end)
{
unsigned long va_start, va_end, flags;
/*
* Make sure 'start' and 'end' reference the same page, as
* L2 is PIPT and range operations only do a TLB lookup on
* the start address.
*/
BUG_ON((start ^ end) >> PAGE_SHIFT);
va_start = l2_get_va(start);
va_end = va_start + (end - start);
raw_local_irq_save(flags);
__asm__("mcr p15, 1, %0, c15, c9, 4\n\t"
"mcr p15, 1, %1, c15, c9, 5"
: : "r" (va_start), "r" (va_end));
raw_local_irq_restore(flags);
l2_put_va(va_start);
}
static inline void l2_clean_inv_pa(unsigned long addr)
{
__asm__("mcr p15, 1, %0, c15, c10, 3" : : "r" (addr));
}
static inline void l2_inv_pa(unsigned long addr)
{
__asm__("mcr p15, 1, %0, c15, c11, 3" : : "r" (addr));
}
static inline void l2_inv_pa_range(unsigned long start, unsigned long end)
{
unsigned long va_start, va_end, flags;
/*
* Make sure 'start' and 'end' reference the same page, as
* L2 is PIPT and range operations only do a TLB lookup on
* the start address.
*/
BUG_ON((start ^ end) >> PAGE_SHIFT);
va_start = l2_get_va(start);
va_end = va_start + (end - start);
raw_local_irq_save(flags);
__asm__("mcr p15, 1, %0, c15, c11, 4\n\t"
"mcr p15, 1, %1, c15, c11, 5"
: : "r" (va_start), "r" (va_end));
raw_local_irq_restore(flags);
l2_put_va(va_start);
}
static inline void l2_inv_all(void)
{
__asm__("mcr p15, 1, %0, c15, c11, 0" : : "r" (0));
}
/*
* Linux primitives.
*
* Note that the end addresses passed to Linux primitives are
* noninclusive, while the hardware cache range operations use
* inclusive start and end addresses.
*/
#define CACHE_LINE_SIZE 32
#define MAX_RANGE_SIZE 1024
static int l2_wt_override;
static unsigned long calc_range_end(unsigned long start, unsigned long end)
{
unsigned long range_end;
BUG_ON(start & (CACHE_LINE_SIZE - 1));
BUG_ON(end & (CACHE_LINE_SIZE - 1));
/*
* Try to process all cache lines between 'start' and 'end'.
*/
range_end = end;
/*
* Limit the number of cache lines processed at once,
* since cache range operations stall the CPU pipeline
* until completion.
*/
if (range_end > start + MAX_RANGE_SIZE)
range_end = start + MAX_RANGE_SIZE;
/*
* Cache range operations can't straddle a page boundary.
*/
if (range_end > (start | (PAGE_SIZE - 1)) + 1)
range_end = (start | (PAGE_SIZE - 1)) + 1;
return range_end;
}
static void feroceon_l2_inv_range(unsigned long start, unsigned long end)
{
/*
* Clean and invalidate partial first cache line.
*/
if (start & (CACHE_LINE_SIZE - 1)) {
l2_clean_inv_pa(start & ~(CACHE_LINE_SIZE - 1));
start = (start | (CACHE_LINE_SIZE - 1)) + 1;
}
/*
* Clean and invalidate partial last cache line.
*/
if (start < end && end & (CACHE_LINE_SIZE - 1)) {
l2_clean_inv_pa(end & ~(CACHE_LINE_SIZE - 1));
end &= ~(CACHE_LINE_SIZE - 1);
}
/*
* Invalidate all full cache lines between 'start' and 'end'.
*/
while (start < end) {
unsigned long range_end = calc_range_end(start, end);
l2_inv_pa_range(start, range_end - CACHE_LINE_SIZE);
start = range_end;
}
dsb();
}
static void feroceon_l2_clean_range(unsigned long start, unsigned long end)
{
/*
* If L2 is forced to WT, the L2 will always be clean and we
* don't need to do anything here.
*/
if (!l2_wt_override) {
start &= ~(CACHE_LINE_SIZE - 1);
end = (end + CACHE_LINE_SIZE - 1) & ~(CACHE_LINE_SIZE - 1);
while (start != end) {
unsigned long range_end = calc_range_end(start, end);
l2_clean_pa_range(start, range_end - CACHE_LINE_SIZE);
start = range_end;
}
}
dsb();
}
static void feroceon_l2_flush_range(unsigned long start, unsigned long end)
{
start &= ~(CACHE_LINE_SIZE - 1);
end = (end + CACHE_LINE_SIZE - 1) & ~(CACHE_LINE_SIZE - 1);
while (start != end) {
unsigned long range_end = calc_range_end(start, end);
if (!l2_wt_override)
l2_clean_pa_range(start, range_end - CACHE_LINE_SIZE);
l2_inv_pa_range(start, range_end - CACHE_LINE_SIZE);
start = range_end;
}
dsb();
}
/*
* Routines to disable and re-enable the D-cache and I-cache at run
* time. These are necessary because the L2 cache can only be enabled
* or disabled while the L1 Dcache and Icache are both disabled.
*/
static int __init flush_and_disable_dcache(void)
{
u32 cr;
cr = get_cr();
if (cr & CR_C) {
unsigned long flags;
raw_local_irq_save(flags);
flush_cache_all();
set_cr(cr & ~CR_C);
raw_local_irq_restore(flags);
return 1;
}
return 0;
}
static void __init enable_dcache(void)
{
u32 cr;
cr = get_cr();
set_cr(cr | CR_C);
}
static void __init __invalidate_icache(void)
{
__asm__("mcr p15, 0, %0, c7, c5, 0" : : "r" (0));
}
static int __init invalidate_and_disable_icache(void)
{
u32 cr;
cr = get_cr();
if (cr & CR_I) {
set_cr(cr & ~CR_I);
__invalidate_icache();
return 1;
}
return 0;
}
static void __init enable_icache(void)
{
u32 cr;
cr = get_cr();
set_cr(cr | CR_I);
}
static inline u32 read_extra_features(void)
{
u32 u;
__asm__("mrc p15, 1, %0, c15, c1, 0" : "=r" (u));
return u;
}
static inline void write_extra_features(u32 u)
{
__asm__("mcr p15, 1, %0, c15, c1, 0" : : "r" (u));
}
static void __init disable_l2_prefetch(void)
{
u32 u;
/*
* Read the CPU Extra Features register and verify that the
* Disable L2 Prefetch bit is set.
*/
u = read_extra_features();
if (!(u & 0x01000000)) {
printk(KERN_INFO "Feroceon L2: Disabling L2 prefetch.\n");
write_extra_features(u | 0x01000000);
}
}
static void __init enable_l2(void)
{
u32 u;
u = read_extra_features();
if (!(u & 0x00400000)) {
int i, d;
printk(KERN_INFO "Feroceon L2: Enabling L2\n");
d = flush_and_disable_dcache();
i = invalidate_and_disable_icache();
l2_inv_all();
write_extra_features(u | 0x00400000);
if (i)
enable_icache();
if (d)
enable_dcache();
}
}
void __init feroceon_l2_init(int __l2_wt_override)
{
l2_wt_override = __l2_wt_override;
disable_l2_prefetch();
outer_cache.inv_range = feroceon_l2_inv_range;
outer_cache.clean_range = feroceon_l2_clean_range;
outer_cache.flush_range = feroceon_l2_flush_range;
enable_l2();
printk(KERN_INFO "Feroceon L2: Cache support initialised%s.\n",
l2_wt_override ? ", in WT override mode" : "");
}
| gpl-2.0 |
roalex/sgs3-kernel | drivers/mtd/chips/cfi_cmdset_0020.c | 2942 | 38614 | /*
* Common Flash Interface support:
* ST Advanced Architecture Command Set (ID 0x0020)
*
* (C) 2000 Red Hat. GPL'd
*
* 10/10/2000 Nicolas Pitre <nico@fluxnic.net>
* - completely revamped method functions so they are aware and
* independent of the flash geometry (buswidth, interleave, etc.)
* - scalability vs code size is completely set at compile-time
* (see include/linux/mtd/cfi.h for selection)
* - optimized write buffer method
* 06/21/2002 Joern Engel <joern@wh.fh-wedel.de> and others
* - modified Intel Command Set 0x0001 to support ST Advanced Architecture
* (command set 0x0020)
* - added a writev function
* 07/13/2005 Joern Engel <joern@wh.fh-wedel.de>
* - Plugged memory leak in cfi_staa_writev().
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <asm/io.h>
#include <asm/byteorder.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/mtd/map.h>
#include <linux/mtd/cfi.h>
#include <linux/mtd/mtd.h>
static int cfi_staa_read(struct mtd_info *, loff_t, size_t, size_t *, u_char *);
static int cfi_staa_write_buffers(struct mtd_info *, loff_t, size_t, size_t *, const u_char *);
static int cfi_staa_writev(struct mtd_info *mtd, const struct kvec *vecs,
unsigned long count, loff_t to, size_t *retlen);
static int cfi_staa_erase_varsize(struct mtd_info *, struct erase_info *);
static void cfi_staa_sync (struct mtd_info *);
static int cfi_staa_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len);
static int cfi_staa_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len);
static int cfi_staa_suspend (struct mtd_info *);
static void cfi_staa_resume (struct mtd_info *);
static void cfi_staa_destroy(struct mtd_info *);
struct mtd_info *cfi_cmdset_0020(struct map_info *, int);
static struct mtd_info *cfi_staa_setup (struct map_info *);
static struct mtd_chip_driver cfi_staa_chipdrv = {
.probe = NULL, /* Not usable directly */
.destroy = cfi_staa_destroy,
.name = "cfi_cmdset_0020",
.module = THIS_MODULE
};
/* #define DEBUG_LOCK_BITS */
//#define DEBUG_CFI_FEATURES
#ifdef DEBUG_CFI_FEATURES
static void cfi_tell_features(struct cfi_pri_intelext *extp)
{
int i;
printk(" Feature/Command Support: %4.4X\n", extp->FeatureSupport);
printk(" - Chip Erase: %s\n", extp->FeatureSupport&1?"supported":"unsupported");
printk(" - Suspend Erase: %s\n", extp->FeatureSupport&2?"supported":"unsupported");
printk(" - Suspend Program: %s\n", extp->FeatureSupport&4?"supported":"unsupported");
printk(" - Legacy Lock/Unlock: %s\n", extp->FeatureSupport&8?"supported":"unsupported");
printk(" - Queued Erase: %s\n", extp->FeatureSupport&16?"supported":"unsupported");
printk(" - Instant block lock: %s\n", extp->FeatureSupport&32?"supported":"unsupported");
printk(" - Protection Bits: %s\n", extp->FeatureSupport&64?"supported":"unsupported");
printk(" - Page-mode read: %s\n", extp->FeatureSupport&128?"supported":"unsupported");
printk(" - Synchronous read: %s\n", extp->FeatureSupport&256?"supported":"unsupported");
for (i=9; i<32; i++) {
if (extp->FeatureSupport & (1<<i))
printk(" - Unknown Bit %X: supported\n", i);
}
printk(" Supported functions after Suspend: %2.2X\n", extp->SuspendCmdSupport);
printk(" - Program after Erase Suspend: %s\n", extp->SuspendCmdSupport&1?"supported":"unsupported");
for (i=1; i<8; i++) {
if (extp->SuspendCmdSupport & (1<<i))
printk(" - Unknown Bit %X: supported\n", i);
}
printk(" Block Status Register Mask: %4.4X\n", extp->BlkStatusRegMask);
printk(" - Lock Bit Active: %s\n", extp->BlkStatusRegMask&1?"yes":"no");
printk(" - Valid Bit Active: %s\n", extp->BlkStatusRegMask&2?"yes":"no");
for (i=2; i<16; i++) {
if (extp->BlkStatusRegMask & (1<<i))
printk(" - Unknown Bit %X Active: yes\n",i);
}
printk(" Vcc Logic Supply Optimum Program/Erase Voltage: %d.%d V\n",
extp->VccOptimal >> 8, extp->VccOptimal & 0xf);
if (extp->VppOptimal)
printk(" Vpp Programming Supply Optimum Program/Erase Voltage: %d.%d V\n",
extp->VppOptimal >> 8, extp->VppOptimal & 0xf);
}
#endif
/* This routine is made available to other mtd code via
* inter_module_register. It must only be accessed through
* inter_module_get which will bump the use count of this module. The
* addresses passed back in cfi are valid as long as the use count of
* this module is non-zero, i.e. between inter_module_get and
* inter_module_put. Keith Owens <kaos@ocs.com.au> 29 Oct 2000.
*/
struct mtd_info *cfi_cmdset_0020(struct map_info *map, int primary)
{
struct cfi_private *cfi = map->fldrv_priv;
int i;
if (cfi->cfi_mode) {
/*
* It's a real CFI chip, not one for which the probe
* routine faked a CFI structure. So we read the feature
* table from it.
*/
__u16 adr = primary?cfi->cfiq->P_ADR:cfi->cfiq->A_ADR;
struct cfi_pri_intelext *extp;
extp = (struct cfi_pri_intelext*)cfi_read_pri(map, adr, sizeof(*extp), "ST Microelectronics");
if (!extp)
return NULL;
if (extp->MajorVersion != '1' ||
(extp->MinorVersion < '0' || extp->MinorVersion > '3')) {
printk(KERN_ERR " Unknown ST Microelectronics"
" Extended Query version %c.%c.\n",
extp->MajorVersion, extp->MinorVersion);
kfree(extp);
return NULL;
}
/* Do some byteswapping if necessary */
extp->FeatureSupport = cfi32_to_cpu(extp->FeatureSupport);
extp->BlkStatusRegMask = cfi32_to_cpu(extp->BlkStatusRegMask);
#ifdef DEBUG_CFI_FEATURES
/* Tell the user about it in lots of lovely detail */
cfi_tell_features(extp);
#endif
/* Install our own private info structure */
cfi->cmdset_priv = extp;
}
for (i=0; i< cfi->numchips; i++) {
cfi->chips[i].word_write_time = 128;
cfi->chips[i].buffer_write_time = 128;
cfi->chips[i].erase_time = 1024;
cfi->chips[i].ref_point_counter = 0;
init_waitqueue_head(&(cfi->chips[i].wq));
}
return cfi_staa_setup(map);
}
EXPORT_SYMBOL_GPL(cfi_cmdset_0020);
static struct mtd_info *cfi_staa_setup(struct map_info *map)
{
struct cfi_private *cfi = map->fldrv_priv;
struct mtd_info *mtd;
unsigned long offset = 0;
int i,j;
unsigned long devsize = (1<<cfi->cfiq->DevSize) * cfi->interleave;
mtd = kzalloc(sizeof(*mtd), GFP_KERNEL);
//printk(KERN_DEBUG "number of CFI chips: %d\n", cfi->numchips);
if (!mtd) {
printk(KERN_ERR "Failed to allocate memory for MTD device\n");
kfree(cfi->cmdset_priv);
return NULL;
}
mtd->priv = map;
mtd->type = MTD_NORFLASH;
mtd->size = devsize * cfi->numchips;
mtd->numeraseregions = cfi->cfiq->NumEraseRegions * cfi->numchips;
mtd->eraseregions = kmalloc(sizeof(struct mtd_erase_region_info)
* mtd->numeraseregions, GFP_KERNEL);
if (!mtd->eraseregions) {
printk(KERN_ERR "Failed to allocate memory for MTD erase region info\n");
kfree(cfi->cmdset_priv);
kfree(mtd);
return NULL;
}
for (i=0; i<cfi->cfiq->NumEraseRegions; i++) {
unsigned long ernum, ersize;
ersize = ((cfi->cfiq->EraseRegionInfo[i] >> 8) & ~0xff) * cfi->interleave;
ernum = (cfi->cfiq->EraseRegionInfo[i] & 0xffff) + 1;
if (mtd->erasesize < ersize) {
mtd->erasesize = ersize;
}
for (j=0; j<cfi->numchips; j++) {
mtd->eraseregions[(j*cfi->cfiq->NumEraseRegions)+i].offset = (j*devsize)+offset;
mtd->eraseregions[(j*cfi->cfiq->NumEraseRegions)+i].erasesize = ersize;
mtd->eraseregions[(j*cfi->cfiq->NumEraseRegions)+i].numblocks = ernum;
}
offset += (ersize * ernum);
}
if (offset != devsize) {
/* Argh */
printk(KERN_WARNING "Sum of regions (%lx) != total size of set of interleaved chips (%lx)\n", offset, devsize);
kfree(mtd->eraseregions);
kfree(cfi->cmdset_priv);
kfree(mtd);
return NULL;
}
for (i=0; i<mtd->numeraseregions;i++){
printk(KERN_DEBUG "%d: offset=0x%llx,size=0x%x,blocks=%d\n",
i, (unsigned long long)mtd->eraseregions[i].offset,
mtd->eraseregions[i].erasesize,
mtd->eraseregions[i].numblocks);
}
/* Also select the correct geometry setup too */
mtd->erase = cfi_staa_erase_varsize;
mtd->read = cfi_staa_read;
mtd->write = cfi_staa_write_buffers;
mtd->writev = cfi_staa_writev;
mtd->sync = cfi_staa_sync;
mtd->lock = cfi_staa_lock;
mtd->unlock = cfi_staa_unlock;
mtd->suspend = cfi_staa_suspend;
mtd->resume = cfi_staa_resume;
mtd->flags = MTD_CAP_NORFLASH & ~MTD_BIT_WRITEABLE;
mtd->writesize = 8; /* FIXME: Should be 0 for STMicro flashes w/out ECC */
mtd->writebufsize = cfi_interleave(cfi) << cfi->cfiq->MaxBufWriteSize;
map->fldrv = &cfi_staa_chipdrv;
__module_get(THIS_MODULE);
mtd->name = map->name;
return mtd;
}
static inline int do_read_onechip(struct map_info *map, struct flchip *chip, loff_t adr, size_t len, u_char *buf)
{
map_word status, status_OK;
unsigned long timeo;
DECLARE_WAITQUEUE(wait, current);
int suspended = 0;
unsigned long cmd_addr;
struct cfi_private *cfi = map->fldrv_priv;
adr += chip->start;
/* Ensure cmd read/writes are aligned. */
cmd_addr = adr & ~(map_bankwidth(map)-1);
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
mutex_lock(&chip->mutex);
/* Check that the chip's ready to talk to us.
* If it's in FL_ERASING state, suspend it and make it talk now.
*/
switch (chip->state) {
case FL_ERASING:
if (!(((struct cfi_pri_intelext *)cfi->cmdset_priv)->FeatureSupport & 2))
goto sleep; /* We don't support erase suspend */
map_write (map, CMD(0xb0), cmd_addr);
/* If the flash has finished erasing, then 'erase suspend'
* appears to make some (28F320) flash devices switch to
* 'read' mode. Make sure that we switch to 'read status'
* mode so we get the right data. --rmk
*/
map_write(map, CMD(0x70), cmd_addr);
chip->oldstate = FL_ERASING;
chip->state = FL_ERASE_SUSPENDING;
// printk("Erase suspending at 0x%lx\n", cmd_addr);
for (;;) {
status = map_read(map, cmd_addr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
if (time_after(jiffies, timeo)) {
/* Urgh */
map_write(map, CMD(0xd0), cmd_addr);
/* make sure we're in 'read status' mode */
map_write(map, CMD(0x70), cmd_addr);
chip->state = FL_ERASING;
wake_up(&chip->wq);
mutex_unlock(&chip->mutex);
printk(KERN_ERR "Chip not ready after erase "
"suspended: status = 0x%lx\n", status.x[0]);
return -EIO;
}
mutex_unlock(&chip->mutex);
cfi_udelay(1);
mutex_lock(&chip->mutex);
}
suspended = 1;
map_write(map, CMD(0xff), cmd_addr);
chip->state = FL_READY;
break;
#if 0
case FL_WRITING:
/* Not quite yet */
#endif
case FL_READY:
break;
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
map_write(map, CMD(0x70), cmd_addr);
chip->state = FL_STATUS;
case FL_STATUS:
status = map_read(map, cmd_addr);
if (map_word_andequal(map, status, status_OK, status_OK)) {
map_write(map, CMD(0xff), cmd_addr);
chip->state = FL_READY;
break;
}
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
mutex_unlock(&chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in read. WSM status = %lx\n", status.x[0]);
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
mutex_unlock(&chip->mutex);
cfi_udelay(1);
goto retry;
default:
sleep:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&chip->wq, &wait);
mutex_unlock(&chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
map_copy_from(map, buf, adr, len);
if (suspended) {
chip->state = chip->oldstate;
/* What if one interleaved chip has finished and the
other hasn't? The old code would leave the finished
one in READY mode. That's bad, and caused -EROFS
errors to be returned from do_erase_oneblock because
that's the only bit it checked for at the time.
As the state machine appears to explicitly allow
sending the 0x70 (Read Status) command to an erasing
chip and expecting it to be ignored, that's what we
do. */
map_write(map, CMD(0xd0), cmd_addr);
map_write(map, CMD(0x70), cmd_addr);
}
wake_up(&chip->wq);
mutex_unlock(&chip->mutex);
return 0;
}
static int cfi_staa_read (struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
unsigned long ofs;
int chipnum;
int ret = 0;
/* ofs: offset within the first chip that the first read should start */
chipnum = (from >> cfi->chipshift);
ofs = from - (chipnum << cfi->chipshift);
*retlen = 0;
while (len) {
unsigned long thislen;
if (chipnum >= cfi->numchips)
break;
if ((len + ofs -1) >> cfi->chipshift)
thislen = (1<<cfi->chipshift) - ofs;
else
thislen = len;
ret = do_read_onechip(map, &cfi->chips[chipnum], ofs, thislen, buf);
if (ret)
break;
*retlen += thislen;
len -= thislen;
buf += thislen;
ofs = 0;
chipnum++;
}
return ret;
}
static inline int do_write_buffer(struct map_info *map, struct flchip *chip,
unsigned long adr, const u_char *buf, int len)
{
struct cfi_private *cfi = map->fldrv_priv;
map_word status, status_OK;
unsigned long cmd_adr, timeo;
DECLARE_WAITQUEUE(wait, current);
int wbufsize, z;
/* M58LW064A requires bus alignment for buffer wriets -- saw */
if (adr & (map_bankwidth(map)-1))
return -EINVAL;
wbufsize = cfi_interleave(cfi) << cfi->cfiq->MaxBufWriteSize;
adr += chip->start;
cmd_adr = adr & ~(wbufsize-1);
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
#ifdef DEBUG_CFI_FEATURES
printk("%s: chip->state[%d]\n", __func__, chip->state);
#endif
mutex_lock(&chip->mutex);
/* Check that the chip's ready to talk to us.
* Later, we can actually think about interrupting it
* if it's in FL_ERASING state.
* Not just yet, though.
*/
switch (chip->state) {
case FL_READY:
break;
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
map_write(map, CMD(0x70), cmd_adr);
chip->state = FL_STATUS;
#ifdef DEBUG_CFI_FEATURES
printk("%s: 1 status[%x]\n", __func__, map_read(map, cmd_adr));
#endif
case FL_STATUS:
status = map_read(map, cmd_adr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
mutex_unlock(&chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in buffer write Xstatus = %lx, status = %lx\n",
status.x[0], map_read(map, cmd_adr).x[0]);
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
mutex_unlock(&chip->mutex);
cfi_udelay(1);
goto retry;
default:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&chip->wq, &wait);
mutex_unlock(&chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
ENABLE_VPP(map);
map_write(map, CMD(0xe8), cmd_adr);
chip->state = FL_WRITING_TO_BUFFER;
z = 0;
for (;;) {
status = map_read(map, cmd_adr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
mutex_unlock(&chip->mutex);
cfi_udelay(1);
mutex_lock(&chip->mutex);
if (++z > 100) {
/* Argh. Not ready for write to buffer */
DISABLE_VPP(map);
map_write(map, CMD(0x70), cmd_adr);
chip->state = FL_STATUS;
mutex_unlock(&chip->mutex);
printk(KERN_ERR "Chip not ready for buffer write. Xstatus = %lx\n", status.x[0]);
return -EIO;
}
}
/* Write length of data to come */
map_write(map, CMD(len/map_bankwidth(map)-1), cmd_adr );
/* Write data */
for (z = 0; z < len;
z += map_bankwidth(map), buf += map_bankwidth(map)) {
map_word d;
d = map_word_load(map, buf);
map_write(map, d, adr+z);
}
/* GO GO GO */
map_write(map, CMD(0xd0), cmd_adr);
chip->state = FL_WRITING;
mutex_unlock(&chip->mutex);
cfi_udelay(chip->buffer_write_time);
mutex_lock(&chip->mutex);
timeo = jiffies + (HZ/2);
z = 0;
for (;;) {
if (chip->state != FL_WRITING) {
/* Someone's suspended the write. Sleep */
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&chip->wq, &wait);
mutex_unlock(&chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + (HZ / 2); /* FIXME */
mutex_lock(&chip->mutex);
continue;
}
status = map_read(map, cmd_adr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
/* OK Still waiting */
if (time_after(jiffies, timeo)) {
/* clear status */
map_write(map, CMD(0x50), cmd_adr);
/* put back into read status register mode */
map_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
DISABLE_VPP(map);
mutex_unlock(&chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in bufwrite\n");
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
mutex_unlock(&chip->mutex);
cfi_udelay(1);
z++;
mutex_lock(&chip->mutex);
}
if (!z) {
chip->buffer_write_time--;
if (!chip->buffer_write_time)
chip->buffer_write_time++;
}
if (z > 1)
chip->buffer_write_time++;
/* Done and happy. */
DISABLE_VPP(map);
chip->state = FL_STATUS;
/* check for errors: 'lock bit', 'VPP', 'dead cell'/'unerased cell' or 'incorrect cmd' -- saw */
if (map_word_bitsset(map, status, CMD(0x3a))) {
#ifdef DEBUG_CFI_FEATURES
printk("%s: 2 status[%lx]\n", __func__, status.x[0]);
#endif
/* clear status */
map_write(map, CMD(0x50), cmd_adr);
/* put back into read status register mode */
map_write(map, CMD(0x70), adr);
wake_up(&chip->wq);
mutex_unlock(&chip->mutex);
return map_word_bitsset(map, status, CMD(0x02)) ? -EROFS : -EIO;
}
wake_up(&chip->wq);
mutex_unlock(&chip->mutex);
return 0;
}
static int cfi_staa_write_buffers (struct mtd_info *mtd, loff_t to,
size_t len, size_t *retlen, const u_char *buf)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
int wbufsize = cfi_interleave(cfi) << cfi->cfiq->MaxBufWriteSize;
int ret = 0;
int chipnum;
unsigned long ofs;
*retlen = 0;
if (!len)
return 0;
chipnum = to >> cfi->chipshift;
ofs = to - (chipnum << cfi->chipshift);
#ifdef DEBUG_CFI_FEATURES
printk("%s: map_bankwidth(map)[%x]\n", __func__, map_bankwidth(map));
printk("%s: chipnum[%x] wbufsize[%x]\n", __func__, chipnum, wbufsize);
printk("%s: ofs[%x] len[%x]\n", __func__, ofs, len);
#endif
/* Write buffer is worth it only if more than one word to write... */
while (len > 0) {
/* We must not cross write block boundaries */
int size = wbufsize - (ofs & (wbufsize-1));
if (size > len)
size = len;
ret = do_write_buffer(map, &cfi->chips[chipnum],
ofs, buf, size);
if (ret)
return ret;
ofs += size;
buf += size;
(*retlen) += size;
len -= size;
if (ofs >> cfi->chipshift) {
chipnum ++;
ofs = 0;
if (chipnum == cfi->numchips)
return 0;
}
}
return 0;
}
/*
* Writev for ECC-Flashes is a little more complicated. We need to maintain
* a small buffer for this.
* XXX: If the buffer size is not a multiple of 2, this will break
*/
#define ECCBUF_SIZE (mtd->writesize)
#define ECCBUF_DIV(x) ((x) & ~(ECCBUF_SIZE - 1))
#define ECCBUF_MOD(x) ((x) & (ECCBUF_SIZE - 1))
static int
cfi_staa_writev(struct mtd_info *mtd, const struct kvec *vecs,
unsigned long count, loff_t to, size_t *retlen)
{
unsigned long i;
size_t totlen = 0, thislen;
int ret = 0;
size_t buflen = 0;
static char *buffer;
if (!ECCBUF_SIZE) {
/* We should fall back to a general writev implementation.
* Until that is written, just break.
*/
return -EIO;
}
buffer = kmalloc(ECCBUF_SIZE, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
for (i=0; i<count; i++) {
size_t elem_len = vecs[i].iov_len;
void *elem_base = vecs[i].iov_base;
if (!elem_len) /* FIXME: Might be unnecessary. Check that */
continue;
if (buflen) { /* cut off head */
if (buflen + elem_len < ECCBUF_SIZE) { /* just accumulate */
memcpy(buffer+buflen, elem_base, elem_len);
buflen += elem_len;
continue;
}
memcpy(buffer+buflen, elem_base, ECCBUF_SIZE-buflen);
ret = mtd->write(mtd, to, ECCBUF_SIZE, &thislen, buffer);
totlen += thislen;
if (ret || thislen != ECCBUF_SIZE)
goto write_error;
elem_len -= thislen-buflen;
elem_base += thislen-buflen;
to += ECCBUF_SIZE;
}
if (ECCBUF_DIV(elem_len)) { /* write clean aligned data */
ret = mtd->write(mtd, to, ECCBUF_DIV(elem_len), &thislen, elem_base);
totlen += thislen;
if (ret || thislen != ECCBUF_DIV(elem_len))
goto write_error;
to += thislen;
}
buflen = ECCBUF_MOD(elem_len); /* cut off tail */
if (buflen) {
memset(buffer, 0xff, ECCBUF_SIZE);
memcpy(buffer, elem_base + thislen, buflen);
}
}
if (buflen) { /* flush last page, even if not full */
/* This is sometimes intended behaviour, really */
ret = mtd->write(mtd, to, buflen, &thislen, buffer);
totlen += thislen;
if (ret || thislen != ECCBUF_SIZE)
goto write_error;
}
write_error:
if (retlen)
*retlen = totlen;
kfree(buffer);
return ret;
}
static inline int do_erase_oneblock(struct map_info *map, struct flchip *chip, unsigned long adr)
{
struct cfi_private *cfi = map->fldrv_priv;
map_word status, status_OK;
unsigned long timeo;
int retries = 3;
DECLARE_WAITQUEUE(wait, current);
int ret = 0;
adr += chip->start;
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
mutex_lock(&chip->mutex);
/* Check that the chip's ready to talk to us. */
switch (chip->state) {
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
case FL_READY:
map_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
case FL_STATUS:
status = map_read(map, adr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
mutex_unlock(&chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in erase\n");
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
mutex_unlock(&chip->mutex);
cfi_udelay(1);
goto retry;
default:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&chip->wq, &wait);
mutex_unlock(&chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
ENABLE_VPP(map);
/* Clear the status register first */
map_write(map, CMD(0x50), adr);
/* Now erase */
map_write(map, CMD(0x20), adr);
map_write(map, CMD(0xD0), adr);
chip->state = FL_ERASING;
mutex_unlock(&chip->mutex);
msleep(1000);
mutex_lock(&chip->mutex);
/* FIXME. Use a timer to check this, and return immediately. */
/* Once the state machine's known to be working I'll do that */
timeo = jiffies + (HZ*20);
for (;;) {
if (chip->state != FL_ERASING) {
/* Someone's suspended the erase. Sleep */
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&chip->wq, &wait);
mutex_unlock(&chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + (HZ*20); /* FIXME */
mutex_lock(&chip->mutex);
continue;
}
status = map_read(map, adr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
/* OK Still waiting */
if (time_after(jiffies, timeo)) {
map_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
printk(KERN_ERR "waiting for erase to complete timed out. Xstatus = %lx, status = %lx.\n", status.x[0], map_read(map, adr).x[0]);
DISABLE_VPP(map);
mutex_unlock(&chip->mutex);
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
mutex_unlock(&chip->mutex);
cfi_udelay(1);
mutex_lock(&chip->mutex);
}
DISABLE_VPP(map);
ret = 0;
/* We've broken this before. It doesn't hurt to be safe */
map_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
status = map_read(map, adr);
/* check for lock bit */
if (map_word_bitsset(map, status, CMD(0x3a))) {
unsigned char chipstatus = status.x[0];
if (!map_word_equal(map, status, CMD(chipstatus))) {
int i, w;
for (w=0; w<map_words(map); w++) {
for (i = 0; i<cfi_interleave(cfi); i++) {
chipstatus |= status.x[w] >> (cfi->device_type * 8);
}
}
printk(KERN_WARNING "Status is not identical for all chips: 0x%lx. Merging to give 0x%02x\n",
status.x[0], chipstatus);
}
/* Reset the error bits */
map_write(map, CMD(0x50), adr);
map_write(map, CMD(0x70), adr);
if ((chipstatus & 0x30) == 0x30) {
printk(KERN_NOTICE "Chip reports improper command sequence: status 0x%x\n", chipstatus);
ret = -EIO;
} else if (chipstatus & 0x02) {
/* Protection bit set */
ret = -EROFS;
} else if (chipstatus & 0x8) {
/* Voltage */
printk(KERN_WARNING "Chip reports voltage low on erase: status 0x%x\n", chipstatus);
ret = -EIO;
} else if (chipstatus & 0x20) {
if (retries--) {
printk(KERN_DEBUG "Chip erase failed at 0x%08lx: status 0x%x. Retrying...\n", adr, chipstatus);
timeo = jiffies + HZ;
chip->state = FL_STATUS;
mutex_unlock(&chip->mutex);
goto retry;
}
printk(KERN_DEBUG "Chip erase failed at 0x%08lx: status 0x%x\n", adr, chipstatus);
ret = -EIO;
}
}
wake_up(&chip->wq);
mutex_unlock(&chip->mutex);
return ret;
}
static int cfi_staa_erase_varsize(struct mtd_info *mtd,
struct erase_info *instr)
{ struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
unsigned long adr, len;
int chipnum, ret = 0;
int i, first;
struct mtd_erase_region_info *regions = mtd->eraseregions;
if (instr->addr > mtd->size)
return -EINVAL;
if ((instr->len + instr->addr) > mtd->size)
return -EINVAL;
/* Check that both start and end of the requested erase are
* aligned with the erasesize at the appropriate addresses.
*/
i = 0;
/* Skip all erase regions which are ended before the start of
the requested erase. Actually, to save on the calculations,
we skip to the first erase region which starts after the
start of the requested erase, and then go back one.
*/
while (i < mtd->numeraseregions && instr->addr >= regions[i].offset)
i++;
i--;
/* OK, now i is pointing at the erase region in which this
erase request starts. Check the start of the requested
erase range is aligned with the erase size which is in
effect here.
*/
if (instr->addr & (regions[i].erasesize-1))
return -EINVAL;
/* Remember the erase region we start on */
first = i;
/* Next, check that the end of the requested erase is aligned
* with the erase region at that address.
*/
while (i<mtd->numeraseregions && (instr->addr + instr->len) >= regions[i].offset)
i++;
/* As before, drop back one to point at the region in which
the address actually falls
*/
i--;
if ((instr->addr + instr->len) & (regions[i].erasesize-1))
return -EINVAL;
chipnum = instr->addr >> cfi->chipshift;
adr = instr->addr - (chipnum << cfi->chipshift);
len = instr->len;
i=first;
while(len) {
ret = do_erase_oneblock(map, &cfi->chips[chipnum], adr);
if (ret)
return ret;
adr += regions[i].erasesize;
len -= regions[i].erasesize;
if (adr % (1<< cfi->chipshift) == (((unsigned long)regions[i].offset + (regions[i].erasesize * regions[i].numblocks)) %( 1<< cfi->chipshift)))
i++;
if (adr >> cfi->chipshift) {
adr = 0;
chipnum++;
if (chipnum >= cfi->numchips)
break;
}
}
instr->state = MTD_ERASE_DONE;
mtd_erase_callback(instr);
return 0;
}
static void cfi_staa_sync (struct mtd_info *mtd)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
int i;
struct flchip *chip;
int ret = 0;
DECLARE_WAITQUEUE(wait, current);
for (i=0; !ret && i<cfi->numchips; i++) {
chip = &cfi->chips[i];
retry:
mutex_lock(&chip->mutex);
switch(chip->state) {
case FL_READY:
case FL_STATUS:
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
chip->oldstate = chip->state;
chip->state = FL_SYNCING;
/* No need to wake_up() on this state change -
* as the whole point is that nobody can do anything
* with the chip now anyway.
*/
case FL_SYNCING:
mutex_unlock(&chip->mutex);
break;
default:
/* Not an idle state */
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&chip->wq, &wait);
mutex_unlock(&chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
goto retry;
}
}
/* Unlock the chips again */
for (i--; i >=0; i--) {
chip = &cfi->chips[i];
mutex_lock(&chip->mutex);
if (chip->state == FL_SYNCING) {
chip->state = chip->oldstate;
wake_up(&chip->wq);
}
mutex_unlock(&chip->mutex);
}
}
static inline int do_lock_oneblock(struct map_info *map, struct flchip *chip, unsigned long adr)
{
struct cfi_private *cfi = map->fldrv_priv;
map_word status, status_OK;
unsigned long timeo = jiffies + HZ;
DECLARE_WAITQUEUE(wait, current);
adr += chip->start;
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
mutex_lock(&chip->mutex);
/* Check that the chip's ready to talk to us. */
switch (chip->state) {
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
case FL_READY:
map_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
case FL_STATUS:
status = map_read(map, adr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
mutex_unlock(&chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in lock\n");
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
mutex_unlock(&chip->mutex);
cfi_udelay(1);
goto retry;
default:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&chip->wq, &wait);
mutex_unlock(&chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
ENABLE_VPP(map);
map_write(map, CMD(0x60), adr);
map_write(map, CMD(0x01), adr);
chip->state = FL_LOCKING;
mutex_unlock(&chip->mutex);
msleep(1000);
mutex_lock(&chip->mutex);
/* FIXME. Use a timer to check this, and return immediately. */
/* Once the state machine's known to be working I'll do that */
timeo = jiffies + (HZ*2);
for (;;) {
status = map_read(map, adr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
/* OK Still waiting */
if (time_after(jiffies, timeo)) {
map_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
printk(KERN_ERR "waiting for lock to complete timed out. Xstatus = %lx, status = %lx.\n", status.x[0], map_read(map, adr).x[0]);
DISABLE_VPP(map);
mutex_unlock(&chip->mutex);
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
mutex_unlock(&chip->mutex);
cfi_udelay(1);
mutex_lock(&chip->mutex);
}
/* Done and happy. */
chip->state = FL_STATUS;
DISABLE_VPP(map);
wake_up(&chip->wq);
mutex_unlock(&chip->mutex);
return 0;
}
static int cfi_staa_lock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
unsigned long adr;
int chipnum, ret = 0;
#ifdef DEBUG_LOCK_BITS
int ofs_factor = cfi->interleave * cfi->device_type;
#endif
if (ofs & (mtd->erasesize - 1))
return -EINVAL;
if (len & (mtd->erasesize -1))
return -EINVAL;
if ((len + ofs) > mtd->size)
return -EINVAL;
chipnum = ofs >> cfi->chipshift;
adr = ofs - (chipnum << cfi->chipshift);
while(len) {
#ifdef DEBUG_LOCK_BITS
cfi_send_gen_cmd(0x90, 0x55, 0, map, cfi, cfi->device_type, NULL);
printk("before lock: block status register is %x\n",cfi_read_query(map, adr+(2*ofs_factor)));
cfi_send_gen_cmd(0xff, 0x55, 0, map, cfi, cfi->device_type, NULL);
#endif
ret = do_lock_oneblock(map, &cfi->chips[chipnum], adr);
#ifdef DEBUG_LOCK_BITS
cfi_send_gen_cmd(0x90, 0x55, 0, map, cfi, cfi->device_type, NULL);
printk("after lock: block status register is %x\n",cfi_read_query(map, adr+(2*ofs_factor)));
cfi_send_gen_cmd(0xff, 0x55, 0, map, cfi, cfi->device_type, NULL);
#endif
if (ret)
return ret;
adr += mtd->erasesize;
len -= mtd->erasesize;
if (adr >> cfi->chipshift) {
adr = 0;
chipnum++;
if (chipnum >= cfi->numchips)
break;
}
}
return 0;
}
static inline int do_unlock_oneblock(struct map_info *map, struct flchip *chip, unsigned long adr)
{
struct cfi_private *cfi = map->fldrv_priv;
map_word status, status_OK;
unsigned long timeo = jiffies + HZ;
DECLARE_WAITQUEUE(wait, current);
adr += chip->start;
/* Let's determine this according to the interleave only once */
status_OK = CMD(0x80);
timeo = jiffies + HZ;
retry:
mutex_lock(&chip->mutex);
/* Check that the chip's ready to talk to us. */
switch (chip->state) {
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
case FL_READY:
map_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
case FL_STATUS:
status = map_read(map, adr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
/* Urgh. Chip not yet ready to talk to us. */
if (time_after(jiffies, timeo)) {
mutex_unlock(&chip->mutex);
printk(KERN_ERR "waiting for chip to be ready timed out in unlock\n");
return -EIO;
}
/* Latency issues. Drop the lock, wait a while and retry */
mutex_unlock(&chip->mutex);
cfi_udelay(1);
goto retry;
default:
/* Stick ourselves on a wait queue to be woken when
someone changes the status */
set_current_state(TASK_UNINTERRUPTIBLE);
add_wait_queue(&chip->wq, &wait);
mutex_unlock(&chip->mutex);
schedule();
remove_wait_queue(&chip->wq, &wait);
timeo = jiffies + HZ;
goto retry;
}
ENABLE_VPP(map);
map_write(map, CMD(0x60), adr);
map_write(map, CMD(0xD0), adr);
chip->state = FL_UNLOCKING;
mutex_unlock(&chip->mutex);
msleep(1000);
mutex_lock(&chip->mutex);
/* FIXME. Use a timer to check this, and return immediately. */
/* Once the state machine's known to be working I'll do that */
timeo = jiffies + (HZ*2);
for (;;) {
status = map_read(map, adr);
if (map_word_andequal(map, status, status_OK, status_OK))
break;
/* OK Still waiting */
if (time_after(jiffies, timeo)) {
map_write(map, CMD(0x70), adr);
chip->state = FL_STATUS;
printk(KERN_ERR "waiting for unlock to complete timed out. Xstatus = %lx, status = %lx.\n", status.x[0], map_read(map, adr).x[0]);
DISABLE_VPP(map);
mutex_unlock(&chip->mutex);
return -EIO;
}
/* Latency issues. Drop the unlock, wait a while and retry */
mutex_unlock(&chip->mutex);
cfi_udelay(1);
mutex_lock(&chip->mutex);
}
/* Done and happy. */
chip->state = FL_STATUS;
DISABLE_VPP(map);
wake_up(&chip->wq);
mutex_unlock(&chip->mutex);
return 0;
}
static int cfi_staa_unlock(struct mtd_info *mtd, loff_t ofs, uint64_t len)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
unsigned long adr;
int chipnum, ret = 0;
#ifdef DEBUG_LOCK_BITS
int ofs_factor = cfi->interleave * cfi->device_type;
#endif
chipnum = ofs >> cfi->chipshift;
adr = ofs - (chipnum << cfi->chipshift);
#ifdef DEBUG_LOCK_BITS
{
unsigned long temp_adr = adr;
unsigned long temp_len = len;
cfi_send_gen_cmd(0x90, 0x55, 0, map, cfi, cfi->device_type, NULL);
while (temp_len) {
printk("before unlock %x: block status register is %x\n",temp_adr,cfi_read_query(map, temp_adr+(2*ofs_factor)));
temp_adr += mtd->erasesize;
temp_len -= mtd->erasesize;
}
cfi_send_gen_cmd(0xff, 0x55, 0, map, cfi, cfi->device_type, NULL);
}
#endif
ret = do_unlock_oneblock(map, &cfi->chips[chipnum], adr);
#ifdef DEBUG_LOCK_BITS
cfi_send_gen_cmd(0x90, 0x55, 0, map, cfi, cfi->device_type, NULL);
printk("after unlock: block status register is %x\n",cfi_read_query(map, adr+(2*ofs_factor)));
cfi_send_gen_cmd(0xff, 0x55, 0, map, cfi, cfi->device_type, NULL);
#endif
return ret;
}
static int cfi_staa_suspend(struct mtd_info *mtd)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
int i;
struct flchip *chip;
int ret = 0;
for (i=0; !ret && i<cfi->numchips; i++) {
chip = &cfi->chips[i];
mutex_lock(&chip->mutex);
switch(chip->state) {
case FL_READY:
case FL_STATUS:
case FL_CFI_QUERY:
case FL_JEDEC_QUERY:
chip->oldstate = chip->state;
chip->state = FL_PM_SUSPENDED;
/* No need to wake_up() on this state change -
* as the whole point is that nobody can do anything
* with the chip now anyway.
*/
case FL_PM_SUSPENDED:
break;
default:
ret = -EAGAIN;
break;
}
mutex_unlock(&chip->mutex);
}
/* Unlock the chips again */
if (ret) {
for (i--; i >=0; i--) {
chip = &cfi->chips[i];
mutex_lock(&chip->mutex);
if (chip->state == FL_PM_SUSPENDED) {
/* No need to force it into a known state here,
because we're returning failure, and it didn't
get power cycled */
chip->state = chip->oldstate;
wake_up(&chip->wq);
}
mutex_unlock(&chip->mutex);
}
}
return ret;
}
static void cfi_staa_resume(struct mtd_info *mtd)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
int i;
struct flchip *chip;
for (i=0; i<cfi->numchips; i++) {
chip = &cfi->chips[i];
mutex_lock(&chip->mutex);
/* Go to known state. Chip may have been power cycled */
if (chip->state == FL_PM_SUSPENDED) {
map_write(map, CMD(0xFF), 0);
chip->state = FL_READY;
wake_up(&chip->wq);
}
mutex_unlock(&chip->mutex);
}
}
static void cfi_staa_destroy(struct mtd_info *mtd)
{
struct map_info *map = mtd->priv;
struct cfi_private *cfi = map->fldrv_priv;
kfree(cfi->cmdset_priv);
kfree(cfi);
}
MODULE_LICENSE("GPL");
| gpl-2.0 |
AD5GB/google_kernel_hammerhead | arch/x86/xen/spinlock.c | 3198 | 11287 | /*
* Split spinlock implementation out into its own file, so it can be
* compiled in a FTRACE-compatible way.
*/
#include <linux/kernel_stat.h>
#include <linux/spinlock.h>
#include <linux/debugfs.h>
#include <linux/log2.h>
#include <linux/gfp.h>
#include <asm/paravirt.h>
#include <xen/interface/xen.h>
#include <xen/events.h>
#include "xen-ops.h"
#include "debugfs.h"
#ifdef CONFIG_XEN_DEBUG_FS
static struct xen_spinlock_stats
{
u64 taken;
u32 taken_slow;
u32 taken_slow_nested;
u32 taken_slow_pickup;
u32 taken_slow_spurious;
u32 taken_slow_irqenable;
u64 released;
u32 released_slow;
u32 released_slow_kicked;
#define HISTO_BUCKETS 30
u32 histo_spin_total[HISTO_BUCKETS+1];
u32 histo_spin_spinning[HISTO_BUCKETS+1];
u32 histo_spin_blocked[HISTO_BUCKETS+1];
u64 time_total;
u64 time_spinning;
u64 time_blocked;
} spinlock_stats;
static u8 zero_stats;
static unsigned lock_timeout = 1 << 10;
#define TIMEOUT lock_timeout
static inline void check_zero(void)
{
if (unlikely(zero_stats)) {
memset(&spinlock_stats, 0, sizeof(spinlock_stats));
zero_stats = 0;
}
}
#define ADD_STATS(elem, val) \
do { check_zero(); spinlock_stats.elem += (val); } while(0)
static inline u64 spin_time_start(void)
{
return xen_clocksource_read();
}
static void __spin_time_accum(u64 delta, u32 *array)
{
unsigned index = ilog2(delta);
check_zero();
if (index < HISTO_BUCKETS)
array[index]++;
else
array[HISTO_BUCKETS]++;
}
static inline void spin_time_accum_spinning(u64 start)
{
u32 delta = xen_clocksource_read() - start;
__spin_time_accum(delta, spinlock_stats.histo_spin_spinning);
spinlock_stats.time_spinning += delta;
}
static inline void spin_time_accum_total(u64 start)
{
u32 delta = xen_clocksource_read() - start;
__spin_time_accum(delta, spinlock_stats.histo_spin_total);
spinlock_stats.time_total += delta;
}
static inline void spin_time_accum_blocked(u64 start)
{
u32 delta = xen_clocksource_read() - start;
__spin_time_accum(delta, spinlock_stats.histo_spin_blocked);
spinlock_stats.time_blocked += delta;
}
#else /* !CONFIG_XEN_DEBUG_FS */
#define TIMEOUT (1 << 10)
#define ADD_STATS(elem, val) do { (void)(val); } while(0)
static inline u64 spin_time_start(void)
{
return 0;
}
static inline void spin_time_accum_total(u64 start)
{
}
static inline void spin_time_accum_spinning(u64 start)
{
}
static inline void spin_time_accum_blocked(u64 start)
{
}
#endif /* CONFIG_XEN_DEBUG_FS */
/*
* Size struct xen_spinlock so it's the same as arch_spinlock_t.
*/
#if NR_CPUS < 256
typedef u8 xen_spinners_t;
# define inc_spinners(xl) \
asm(LOCK_PREFIX " incb %0" : "+m" ((xl)->spinners) : : "memory");
# define dec_spinners(xl) \
asm(LOCK_PREFIX " decb %0" : "+m" ((xl)->spinners) : : "memory");
#else
typedef u16 xen_spinners_t;
# define inc_spinners(xl) \
asm(LOCK_PREFIX " incw %0" : "+m" ((xl)->spinners) : : "memory");
# define dec_spinners(xl) \
asm(LOCK_PREFIX " decw %0" : "+m" ((xl)->spinners) : : "memory");
#endif
struct xen_spinlock {
unsigned char lock; /* 0 -> free; 1 -> locked */
xen_spinners_t spinners; /* count of waiting cpus */
};
static int xen_spin_is_locked(struct arch_spinlock *lock)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
return xl->lock != 0;
}
static int xen_spin_is_contended(struct arch_spinlock *lock)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
/* Not strictly true; this is only the count of contended
lock-takers entering the slow path. */
return xl->spinners != 0;
}
static int xen_spin_trylock(struct arch_spinlock *lock)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
u8 old = 1;
asm("xchgb %b0,%1"
: "+q" (old), "+m" (xl->lock) : : "memory");
return old == 0;
}
static DEFINE_PER_CPU(int, lock_kicker_irq) = -1;
static DEFINE_PER_CPU(struct xen_spinlock *, lock_spinners);
/*
* Mark a cpu as interested in a lock. Returns the CPU's previous
* lock of interest, in case we got preempted by an interrupt.
*/
static inline struct xen_spinlock *spinning_lock(struct xen_spinlock *xl)
{
struct xen_spinlock *prev;
prev = __this_cpu_read(lock_spinners);
__this_cpu_write(lock_spinners, xl);
wmb(); /* set lock of interest before count */
inc_spinners(xl);
return prev;
}
/*
* Mark a cpu as no longer interested in a lock. Restores previous
* lock of interest (NULL for none).
*/
static inline void unspinning_lock(struct xen_spinlock *xl, struct xen_spinlock *prev)
{
dec_spinners(xl);
wmb(); /* decrement count before restoring lock */
__this_cpu_write(lock_spinners, prev);
}
static noinline int xen_spin_lock_slow(struct arch_spinlock *lock, bool irq_enable)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
struct xen_spinlock *prev;
int irq = __this_cpu_read(lock_kicker_irq);
int ret;
u64 start;
/* If kicker interrupts not initialized yet, just spin */
if (irq == -1)
return 0;
start = spin_time_start();
/* announce we're spinning */
prev = spinning_lock(xl);
ADD_STATS(taken_slow, 1);
ADD_STATS(taken_slow_nested, prev != NULL);
do {
unsigned long flags;
/* clear pending */
xen_clear_irq_pending(irq);
/* check again make sure it didn't become free while
we weren't looking */
ret = xen_spin_trylock(lock);
if (ret) {
ADD_STATS(taken_slow_pickup, 1);
/*
* If we interrupted another spinlock while it
* was blocking, make sure it doesn't block
* without rechecking the lock.
*/
if (prev != NULL)
xen_set_irq_pending(irq);
goto out;
}
flags = arch_local_save_flags();
if (irq_enable) {
ADD_STATS(taken_slow_irqenable, 1);
raw_local_irq_enable();
}
/*
* Block until irq becomes pending. If we're
* interrupted at this point (after the trylock but
* before entering the block), then the nested lock
* handler guarantees that the irq will be left
* pending if there's any chance the lock became free;
* xen_poll_irq() returns immediately if the irq is
* pending.
*/
xen_poll_irq(irq);
raw_local_irq_restore(flags);
ADD_STATS(taken_slow_spurious, !xen_test_irq_pending(irq));
} while (!xen_test_irq_pending(irq)); /* check for spurious wakeups */
kstat_incr_irqs_this_cpu(irq, irq_to_desc(irq));
out:
unspinning_lock(xl, prev);
spin_time_accum_blocked(start);
return ret;
}
static inline void __xen_spin_lock(struct arch_spinlock *lock, bool irq_enable)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
unsigned timeout;
u8 oldval;
u64 start_spin;
ADD_STATS(taken, 1);
start_spin = spin_time_start();
do {
u64 start_spin_fast = spin_time_start();
timeout = TIMEOUT;
asm("1: xchgb %1,%0\n"
" testb %1,%1\n"
" jz 3f\n"
"2: rep;nop\n"
" cmpb $0,%0\n"
" je 1b\n"
" dec %2\n"
" jnz 2b\n"
"3:\n"
: "+m" (xl->lock), "=q" (oldval), "+r" (timeout)
: "1" (1)
: "memory");
spin_time_accum_spinning(start_spin_fast);
} while (unlikely(oldval != 0 &&
(TIMEOUT == ~0 || !xen_spin_lock_slow(lock, irq_enable))));
spin_time_accum_total(start_spin);
}
static void xen_spin_lock(struct arch_spinlock *lock)
{
__xen_spin_lock(lock, false);
}
static void xen_spin_lock_flags(struct arch_spinlock *lock, unsigned long flags)
{
__xen_spin_lock(lock, !raw_irqs_disabled_flags(flags));
}
static noinline void xen_spin_unlock_slow(struct xen_spinlock *xl)
{
int cpu;
ADD_STATS(released_slow, 1);
for_each_online_cpu(cpu) {
/* XXX should mix up next cpu selection */
if (per_cpu(lock_spinners, cpu) == xl) {
ADD_STATS(released_slow_kicked, 1);
xen_send_IPI_one(cpu, XEN_SPIN_UNLOCK_VECTOR);
break;
}
}
}
static void xen_spin_unlock(struct arch_spinlock *lock)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
ADD_STATS(released, 1);
smp_wmb(); /* make sure no writes get moved after unlock */
xl->lock = 0; /* release lock */
/*
* Make sure unlock happens before checking for waiting
* spinners. We need a strong barrier to enforce the
* write-read ordering to different memory locations, as the
* CPU makes no implied guarantees about their ordering.
*/
mb();
if (unlikely(xl->spinners))
xen_spin_unlock_slow(xl);
}
static irqreturn_t dummy_handler(int irq, void *dev_id)
{
BUG();
return IRQ_HANDLED;
}
void __cpuinit xen_init_lock_cpu(int cpu)
{
int irq;
const char *name;
name = kasprintf(GFP_KERNEL, "spinlock%d", cpu);
irq = bind_ipi_to_irqhandler(XEN_SPIN_UNLOCK_VECTOR,
cpu,
dummy_handler,
IRQF_DISABLED|IRQF_PERCPU|IRQF_NOBALANCING,
name,
NULL);
if (irq >= 0) {
disable_irq(irq); /* make sure it's never delivered */
per_cpu(lock_kicker_irq, cpu) = irq;
}
printk("cpu %d spinlock event irq %d\n", cpu, irq);
}
void xen_uninit_lock_cpu(int cpu)
{
unbind_from_irqhandler(per_cpu(lock_kicker_irq, cpu), NULL);
}
void __init xen_init_spinlocks(void)
{
BUILD_BUG_ON(sizeof(struct xen_spinlock) > sizeof(arch_spinlock_t));
pv_lock_ops.spin_is_locked = xen_spin_is_locked;
pv_lock_ops.spin_is_contended = xen_spin_is_contended;
pv_lock_ops.spin_lock = xen_spin_lock;
pv_lock_ops.spin_lock_flags = xen_spin_lock_flags;
pv_lock_ops.spin_trylock = xen_spin_trylock;
pv_lock_ops.spin_unlock = xen_spin_unlock;
}
#ifdef CONFIG_XEN_DEBUG_FS
static struct dentry *d_spin_debug;
static int __init xen_spinlock_debugfs(void)
{
struct dentry *d_xen = xen_init_debugfs();
if (d_xen == NULL)
return -ENOMEM;
d_spin_debug = debugfs_create_dir("spinlocks", d_xen);
debugfs_create_u8("zero_stats", 0644, d_spin_debug, &zero_stats);
debugfs_create_u32("timeout", 0644, d_spin_debug, &lock_timeout);
debugfs_create_u64("taken", 0444, d_spin_debug, &spinlock_stats.taken);
debugfs_create_u32("taken_slow", 0444, d_spin_debug,
&spinlock_stats.taken_slow);
debugfs_create_u32("taken_slow_nested", 0444, d_spin_debug,
&spinlock_stats.taken_slow_nested);
debugfs_create_u32("taken_slow_pickup", 0444, d_spin_debug,
&spinlock_stats.taken_slow_pickup);
debugfs_create_u32("taken_slow_spurious", 0444, d_spin_debug,
&spinlock_stats.taken_slow_spurious);
debugfs_create_u32("taken_slow_irqenable", 0444, d_spin_debug,
&spinlock_stats.taken_slow_irqenable);
debugfs_create_u64("released", 0444, d_spin_debug, &spinlock_stats.released);
debugfs_create_u32("released_slow", 0444, d_spin_debug,
&spinlock_stats.released_slow);
debugfs_create_u32("released_slow_kicked", 0444, d_spin_debug,
&spinlock_stats.released_slow_kicked);
debugfs_create_u64("time_spinning", 0444, d_spin_debug,
&spinlock_stats.time_spinning);
debugfs_create_u64("time_blocked", 0444, d_spin_debug,
&spinlock_stats.time_blocked);
debugfs_create_u64("time_total", 0444, d_spin_debug,
&spinlock_stats.time_total);
xen_debugfs_create_u32_array("histo_total", 0444, d_spin_debug,
spinlock_stats.histo_spin_total, HISTO_BUCKETS + 1);
xen_debugfs_create_u32_array("histo_spinning", 0444, d_spin_debug,
spinlock_stats.histo_spin_spinning, HISTO_BUCKETS + 1);
xen_debugfs_create_u32_array("histo_blocked", 0444, d_spin_debug,
spinlock_stats.histo_spin_blocked, HISTO_BUCKETS + 1);
return 0;
}
fs_initcall(xen_spinlock_debugfs);
#endif /* CONFIG_XEN_DEBUG_FS */
| gpl-2.0 |
pacerom/kernel_google_msm | arch/x86/xen/spinlock.c | 3198 | 11287 | /*
* Split spinlock implementation out into its own file, so it can be
* compiled in a FTRACE-compatible way.
*/
#include <linux/kernel_stat.h>
#include <linux/spinlock.h>
#include <linux/debugfs.h>
#include <linux/log2.h>
#include <linux/gfp.h>
#include <asm/paravirt.h>
#include <xen/interface/xen.h>
#include <xen/events.h>
#include "xen-ops.h"
#include "debugfs.h"
#ifdef CONFIG_XEN_DEBUG_FS
static struct xen_spinlock_stats
{
u64 taken;
u32 taken_slow;
u32 taken_slow_nested;
u32 taken_slow_pickup;
u32 taken_slow_spurious;
u32 taken_slow_irqenable;
u64 released;
u32 released_slow;
u32 released_slow_kicked;
#define HISTO_BUCKETS 30
u32 histo_spin_total[HISTO_BUCKETS+1];
u32 histo_spin_spinning[HISTO_BUCKETS+1];
u32 histo_spin_blocked[HISTO_BUCKETS+1];
u64 time_total;
u64 time_spinning;
u64 time_blocked;
} spinlock_stats;
static u8 zero_stats;
static unsigned lock_timeout = 1 << 10;
#define TIMEOUT lock_timeout
static inline void check_zero(void)
{
if (unlikely(zero_stats)) {
memset(&spinlock_stats, 0, sizeof(spinlock_stats));
zero_stats = 0;
}
}
#define ADD_STATS(elem, val) \
do { check_zero(); spinlock_stats.elem += (val); } while(0)
static inline u64 spin_time_start(void)
{
return xen_clocksource_read();
}
static void __spin_time_accum(u64 delta, u32 *array)
{
unsigned index = ilog2(delta);
check_zero();
if (index < HISTO_BUCKETS)
array[index]++;
else
array[HISTO_BUCKETS]++;
}
static inline void spin_time_accum_spinning(u64 start)
{
u32 delta = xen_clocksource_read() - start;
__spin_time_accum(delta, spinlock_stats.histo_spin_spinning);
spinlock_stats.time_spinning += delta;
}
static inline void spin_time_accum_total(u64 start)
{
u32 delta = xen_clocksource_read() - start;
__spin_time_accum(delta, spinlock_stats.histo_spin_total);
spinlock_stats.time_total += delta;
}
static inline void spin_time_accum_blocked(u64 start)
{
u32 delta = xen_clocksource_read() - start;
__spin_time_accum(delta, spinlock_stats.histo_spin_blocked);
spinlock_stats.time_blocked += delta;
}
#else /* !CONFIG_XEN_DEBUG_FS */
#define TIMEOUT (1 << 10)
#define ADD_STATS(elem, val) do { (void)(val); } while(0)
static inline u64 spin_time_start(void)
{
return 0;
}
static inline void spin_time_accum_total(u64 start)
{
}
static inline void spin_time_accum_spinning(u64 start)
{
}
static inline void spin_time_accum_blocked(u64 start)
{
}
#endif /* CONFIG_XEN_DEBUG_FS */
/*
* Size struct xen_spinlock so it's the same as arch_spinlock_t.
*/
#if NR_CPUS < 256
typedef u8 xen_spinners_t;
# define inc_spinners(xl) \
asm(LOCK_PREFIX " incb %0" : "+m" ((xl)->spinners) : : "memory");
# define dec_spinners(xl) \
asm(LOCK_PREFIX " decb %0" : "+m" ((xl)->spinners) : : "memory");
#else
typedef u16 xen_spinners_t;
# define inc_spinners(xl) \
asm(LOCK_PREFIX " incw %0" : "+m" ((xl)->spinners) : : "memory");
# define dec_spinners(xl) \
asm(LOCK_PREFIX " decw %0" : "+m" ((xl)->spinners) : : "memory");
#endif
struct xen_spinlock {
unsigned char lock; /* 0 -> free; 1 -> locked */
xen_spinners_t spinners; /* count of waiting cpus */
};
static int xen_spin_is_locked(struct arch_spinlock *lock)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
return xl->lock != 0;
}
static int xen_spin_is_contended(struct arch_spinlock *lock)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
/* Not strictly true; this is only the count of contended
lock-takers entering the slow path. */
return xl->spinners != 0;
}
static int xen_spin_trylock(struct arch_spinlock *lock)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
u8 old = 1;
asm("xchgb %b0,%1"
: "+q" (old), "+m" (xl->lock) : : "memory");
return old == 0;
}
static DEFINE_PER_CPU(int, lock_kicker_irq) = -1;
static DEFINE_PER_CPU(struct xen_spinlock *, lock_spinners);
/*
* Mark a cpu as interested in a lock. Returns the CPU's previous
* lock of interest, in case we got preempted by an interrupt.
*/
static inline struct xen_spinlock *spinning_lock(struct xen_spinlock *xl)
{
struct xen_spinlock *prev;
prev = __this_cpu_read(lock_spinners);
__this_cpu_write(lock_spinners, xl);
wmb(); /* set lock of interest before count */
inc_spinners(xl);
return prev;
}
/*
* Mark a cpu as no longer interested in a lock. Restores previous
* lock of interest (NULL for none).
*/
static inline void unspinning_lock(struct xen_spinlock *xl, struct xen_spinlock *prev)
{
dec_spinners(xl);
wmb(); /* decrement count before restoring lock */
__this_cpu_write(lock_spinners, prev);
}
static noinline int xen_spin_lock_slow(struct arch_spinlock *lock, bool irq_enable)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
struct xen_spinlock *prev;
int irq = __this_cpu_read(lock_kicker_irq);
int ret;
u64 start;
/* If kicker interrupts not initialized yet, just spin */
if (irq == -1)
return 0;
start = spin_time_start();
/* announce we're spinning */
prev = spinning_lock(xl);
ADD_STATS(taken_slow, 1);
ADD_STATS(taken_slow_nested, prev != NULL);
do {
unsigned long flags;
/* clear pending */
xen_clear_irq_pending(irq);
/* check again make sure it didn't become free while
we weren't looking */
ret = xen_spin_trylock(lock);
if (ret) {
ADD_STATS(taken_slow_pickup, 1);
/*
* If we interrupted another spinlock while it
* was blocking, make sure it doesn't block
* without rechecking the lock.
*/
if (prev != NULL)
xen_set_irq_pending(irq);
goto out;
}
flags = arch_local_save_flags();
if (irq_enable) {
ADD_STATS(taken_slow_irqenable, 1);
raw_local_irq_enable();
}
/*
* Block until irq becomes pending. If we're
* interrupted at this point (after the trylock but
* before entering the block), then the nested lock
* handler guarantees that the irq will be left
* pending if there's any chance the lock became free;
* xen_poll_irq() returns immediately if the irq is
* pending.
*/
xen_poll_irq(irq);
raw_local_irq_restore(flags);
ADD_STATS(taken_slow_spurious, !xen_test_irq_pending(irq));
} while (!xen_test_irq_pending(irq)); /* check for spurious wakeups */
kstat_incr_irqs_this_cpu(irq, irq_to_desc(irq));
out:
unspinning_lock(xl, prev);
spin_time_accum_blocked(start);
return ret;
}
static inline void __xen_spin_lock(struct arch_spinlock *lock, bool irq_enable)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
unsigned timeout;
u8 oldval;
u64 start_spin;
ADD_STATS(taken, 1);
start_spin = spin_time_start();
do {
u64 start_spin_fast = spin_time_start();
timeout = TIMEOUT;
asm("1: xchgb %1,%0\n"
" testb %1,%1\n"
" jz 3f\n"
"2: rep;nop\n"
" cmpb $0,%0\n"
" je 1b\n"
" dec %2\n"
" jnz 2b\n"
"3:\n"
: "+m" (xl->lock), "=q" (oldval), "+r" (timeout)
: "1" (1)
: "memory");
spin_time_accum_spinning(start_spin_fast);
} while (unlikely(oldval != 0 &&
(TIMEOUT == ~0 || !xen_spin_lock_slow(lock, irq_enable))));
spin_time_accum_total(start_spin);
}
static void xen_spin_lock(struct arch_spinlock *lock)
{
__xen_spin_lock(lock, false);
}
static void xen_spin_lock_flags(struct arch_spinlock *lock, unsigned long flags)
{
__xen_spin_lock(lock, !raw_irqs_disabled_flags(flags));
}
static noinline void xen_spin_unlock_slow(struct xen_spinlock *xl)
{
int cpu;
ADD_STATS(released_slow, 1);
for_each_online_cpu(cpu) {
/* XXX should mix up next cpu selection */
if (per_cpu(lock_spinners, cpu) == xl) {
ADD_STATS(released_slow_kicked, 1);
xen_send_IPI_one(cpu, XEN_SPIN_UNLOCK_VECTOR);
break;
}
}
}
static void xen_spin_unlock(struct arch_spinlock *lock)
{
struct xen_spinlock *xl = (struct xen_spinlock *)lock;
ADD_STATS(released, 1);
smp_wmb(); /* make sure no writes get moved after unlock */
xl->lock = 0; /* release lock */
/*
* Make sure unlock happens before checking for waiting
* spinners. We need a strong barrier to enforce the
* write-read ordering to different memory locations, as the
* CPU makes no implied guarantees about their ordering.
*/
mb();
if (unlikely(xl->spinners))
xen_spin_unlock_slow(xl);
}
static irqreturn_t dummy_handler(int irq, void *dev_id)
{
BUG();
return IRQ_HANDLED;
}
void __cpuinit xen_init_lock_cpu(int cpu)
{
int irq;
const char *name;
name = kasprintf(GFP_KERNEL, "spinlock%d", cpu);
irq = bind_ipi_to_irqhandler(XEN_SPIN_UNLOCK_VECTOR,
cpu,
dummy_handler,
IRQF_DISABLED|IRQF_PERCPU|IRQF_NOBALANCING,
name,
NULL);
if (irq >= 0) {
disable_irq(irq); /* make sure it's never delivered */
per_cpu(lock_kicker_irq, cpu) = irq;
}
printk("cpu %d spinlock event irq %d\n", cpu, irq);
}
void xen_uninit_lock_cpu(int cpu)
{
unbind_from_irqhandler(per_cpu(lock_kicker_irq, cpu), NULL);
}
void __init xen_init_spinlocks(void)
{
BUILD_BUG_ON(sizeof(struct xen_spinlock) > sizeof(arch_spinlock_t));
pv_lock_ops.spin_is_locked = xen_spin_is_locked;
pv_lock_ops.spin_is_contended = xen_spin_is_contended;
pv_lock_ops.spin_lock = xen_spin_lock;
pv_lock_ops.spin_lock_flags = xen_spin_lock_flags;
pv_lock_ops.spin_trylock = xen_spin_trylock;
pv_lock_ops.spin_unlock = xen_spin_unlock;
}
#ifdef CONFIG_XEN_DEBUG_FS
static struct dentry *d_spin_debug;
static int __init xen_spinlock_debugfs(void)
{
struct dentry *d_xen = xen_init_debugfs();
if (d_xen == NULL)
return -ENOMEM;
d_spin_debug = debugfs_create_dir("spinlocks", d_xen);
debugfs_create_u8("zero_stats", 0644, d_spin_debug, &zero_stats);
debugfs_create_u32("timeout", 0644, d_spin_debug, &lock_timeout);
debugfs_create_u64("taken", 0444, d_spin_debug, &spinlock_stats.taken);
debugfs_create_u32("taken_slow", 0444, d_spin_debug,
&spinlock_stats.taken_slow);
debugfs_create_u32("taken_slow_nested", 0444, d_spin_debug,
&spinlock_stats.taken_slow_nested);
debugfs_create_u32("taken_slow_pickup", 0444, d_spin_debug,
&spinlock_stats.taken_slow_pickup);
debugfs_create_u32("taken_slow_spurious", 0444, d_spin_debug,
&spinlock_stats.taken_slow_spurious);
debugfs_create_u32("taken_slow_irqenable", 0444, d_spin_debug,
&spinlock_stats.taken_slow_irqenable);
debugfs_create_u64("released", 0444, d_spin_debug, &spinlock_stats.released);
debugfs_create_u32("released_slow", 0444, d_spin_debug,
&spinlock_stats.released_slow);
debugfs_create_u32("released_slow_kicked", 0444, d_spin_debug,
&spinlock_stats.released_slow_kicked);
debugfs_create_u64("time_spinning", 0444, d_spin_debug,
&spinlock_stats.time_spinning);
debugfs_create_u64("time_blocked", 0444, d_spin_debug,
&spinlock_stats.time_blocked);
debugfs_create_u64("time_total", 0444, d_spin_debug,
&spinlock_stats.time_total);
xen_debugfs_create_u32_array("histo_total", 0444, d_spin_debug,
spinlock_stats.histo_spin_total, HISTO_BUCKETS + 1);
xen_debugfs_create_u32_array("histo_spinning", 0444, d_spin_debug,
spinlock_stats.histo_spin_spinning, HISTO_BUCKETS + 1);
xen_debugfs_create_u32_array("histo_blocked", 0444, d_spin_debug,
spinlock_stats.histo_spin_blocked, HISTO_BUCKETS + 1);
return 0;
}
fs_initcall(xen_spinlock_debugfs);
#endif /* CONFIG_XEN_DEBUG_FS */
| gpl-2.0 |
futranbg/ef40s-4.0-kernel | drivers/staging/wlags49_h2/wl_pci.c | 3198 | 52753 | /*******************************************************************************
* Agere Systems Inc.
* Wireless device driver for Linux (wlags49).
*
* Copyright (c) 1998-2003 Agere Systems Inc.
* All rights reserved.
* http://www.agere.com
*
* Initially developed by TriplePoint, Inc.
* http://www.triplepoint.com
*
*------------------------------------------------------------------------------
*
* This file contains processing and initialization specific to PCI/miniPCI
* devices.
*
*------------------------------------------------------------------------------
*
* SOFTWARE LICENSE
*
* This software is provided subject to the following terms and conditions,
* which you should read carefully before using the software. Using this
* software indicates your acceptance of these terms and conditions. If you do
* not agree with these terms and conditions, do not use the software.
*
* Copyright © 2003 Agere Systems Inc.
* All rights reserved.
*
* Redistribution and use in source or binary forms, with or without
* modifications, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following Disclaimer as comments in the code as
* well as in the documentation and/or other materials provided with the
* distribution.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following Disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name of Agere Systems Inc. nor the names of the contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Disclaimer
*
* THIS SOFTWARE IS PROVIDED AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, INFRINGEMENT AND THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ANY
* USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE IS SOLELY AT THE USERS OWN
* RISK. IN NO EVENT SHALL AGERE SYSTEMS INC. OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, INCLUDING, BUT NOT LIMITED TO, CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
******************************************************************************/
/*******************************************************************************
* include files
******************************************************************************/
#include <wireless/wl_version.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/ptrace.h>
#include <linux/ctype.h>
#include <linux/string.h>
//#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/in.h>
#include <linux/delay.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/bitops.h>
#include <asm/uaccess.h>
#include <linux/ethtool.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/ioport.h>
#include <hcf/debug.h>
#include <hcf.h>
#include <dhf.h>
#include <hcfdef.h>
#include <wireless/wl_if.h>
#include <wireless/wl_internal.h>
#include <wireless/wl_util.h>
#include <wireless/wl_main.h>
#include <wireless/wl_netdev.h>
#include <wireless/wl_pci.h>
/*******************************************************************************
* global variables
******************************************************************************/
#if DBG
extern dbg_info_t *DbgInfo;
#endif // DBG
/* define the PCI device Table Cardname and id tables */
enum hermes_pci_versions {
CH_Agere_Systems_Mini_PCI_V1 = 0,
};
static struct pci_device_id wl_pci_tbl[] __devinitdata = {
{ PCI_VENDOR_ID_WL_LKM, PCI_DEVICE_ID_WL_LKM_0,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Agere_Systems_Mini_PCI_V1 },
{ PCI_VENDOR_ID_WL_LKM, PCI_DEVICE_ID_WL_LKM_1,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Agere_Systems_Mini_PCI_V1 },
{ PCI_VENDOR_ID_WL_LKM, PCI_DEVICE_ID_WL_LKM_2,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, CH_Agere_Systems_Mini_PCI_V1 },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(pci, wl_pci_tbl);
/*******************************************************************************
* function prototypes
******************************************************************************/
int __devinit wl_pci_probe( struct pci_dev *pdev,
const struct pci_device_id *ent );
void __devexit wl_pci_remove(struct pci_dev *pdev);
int wl_pci_setup( struct pci_dev *pdev );
void wl_pci_enable_cardbus_interrupts( struct pci_dev *pdev );
#ifdef ENABLE_DMA
int wl_pci_dma_alloc( struct pci_dev *pdev, struct wl_private *lp );
int wl_pci_dma_free( struct pci_dev *pdev, struct wl_private *lp );
int wl_pci_dma_alloc_tx_packet( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc );
int wl_pci_dma_free_tx_packet( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc );
int wl_pci_dma_alloc_rx_packet( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc );
int wl_pci_dma_free_rx_packet( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc );
int wl_pci_dma_alloc_desc_and_buf( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc, int size );
int wl_pci_dma_free_desc_and_buf( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc );
int wl_pci_dma_alloc_desc( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc );
int wl_pci_dma_free_desc( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc );
int wl_pci_dma_alloc_buf( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT *desc, int size );
int wl_pci_dma_free_buf( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT *desc );
void wl_pci_dma_hcf_reclaim_rx( struct wl_private *lp );
#endif // ENABLE_DMA
/*******************************************************************************
* PCI module function registration
******************************************************************************/
static struct pci_driver wl_driver =
{
name: MODULE_NAME,
id_table: wl_pci_tbl,
probe: wl_pci_probe,
remove: __devexit_p(wl_pci_remove),
suspend: NULL,
resume: NULL,
};
/*******************************************************************************
* wl_adapter_init_module()
*******************************************************************************
*
* DESCRIPTION:
*
* Called by init_module() to perform PCI-specific driver initialization.
*
* PARAMETERS:
*
* N/A
*
* RETURNS:
*
* 0
*
******************************************************************************/
int wl_adapter_init_module( void )
{
int result;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_adapter_init_module()" );
DBG_ENTER( DbgInfo );
DBG_TRACE( DbgInfo, "wl_adapter_init_module() -- PCI\n" );
result = pci_register_driver( &wl_driver ); //;?replace with pci_module_init, Rubini pg 490
//;? why not do something with the result
DBG_LEAVE( DbgInfo );
return 0;
} // wl_adapter_init_module
/*============================================================================*/
/*******************************************************************************
* wl_adapter_cleanup_module()
*******************************************************************************
*
* DESCRIPTION:
*
* Called by cleanup_module() to perform PCI-specific driver cleanup.
*
* PARAMETERS:
*
* N/A
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_adapter_cleanup_module( void )
{
//;?how comes wl_adapter_cleanup_module is located in a seemingly pci specific module
DBG_FUNC( "wl_adapter_cleanup_module" );
DBG_ENTER( DbgInfo );
//;?DBG_TRACE below feels like nearly redundant in the light of DBG_ENTER above
DBG_TRACE( DbgInfo, "wl_adapter_cleanup_module() -- PCI\n" );
pci_unregister_driver( &wl_driver );
DBG_LEAVE( DbgInfo );
return;
} // wl_adapter_cleanup_module
/*============================================================================*/
/*******************************************************************************
* wl_adapter_insert()
*******************************************************************************
*
* DESCRIPTION:
*
* Called by wl_pci_probe() to continue the process of device insertion.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure
*
* RETURNS:
*
* TRUE or FALSE
*
******************************************************************************/
int wl_adapter_insert( struct net_device *dev )
{
int result = FALSE;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_adapter_insert" );
DBG_ENTER( DbgInfo );
DBG_TRACE( DbgInfo, "wl_adapter_insert() -- PCI\n" );
if( dev == NULL ) {
DBG_ERROR( DbgInfo, "net_device pointer is NULL!!!\n" );
} else if( dev->priv == NULL ) {
DBG_ERROR( DbgInfo, "wl_private pointer is NULL!!!\n" );
} else if( wl_insert( dev ) ) { /* Perform remaining device initialization */
result = TRUE;
} else {
DBG_TRACE( DbgInfo, "wl_insert() FAILED\n" );
}
DBG_LEAVE( DbgInfo );
return result;
} // wl_adapter_insert
/*============================================================================*/
/*******************************************************************************
* wl_adapter_open()
*******************************************************************************
*
* DESCRIPTION:
*
* Open the device.
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure
*
* RETURNS:
*
* an HCF status code
*
******************************************************************************/
int wl_adapter_open( struct net_device *dev )
{
int result = 0;
int hcf_status = HCF_SUCCESS;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_adapter_open" );
DBG_ENTER( DbgInfo );
DBG_TRACE( DbgInfo, "wl_adapter_open() -- PCI\n" );
hcf_status = wl_open( dev );
if( hcf_status != HCF_SUCCESS ) {
result = -ENODEV;
}
DBG_LEAVE( DbgInfo );
return result;
} // wl_adapter_open
/*============================================================================*/
/*******************************************************************************
* wl_adapter_close()
*******************************************************************************
*
* DESCRIPTION:
*
* Close the device
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure
*
* RETURNS:
*
* 0
*
******************************************************************************/
int wl_adapter_close( struct net_device *dev )
{
DBG_FUNC( "wl_adapter_close" );
DBG_ENTER( DbgInfo );
DBG_TRACE( DbgInfo, "wl_adapter_close() -- PCI\n" );
DBG_TRACE( DbgInfo, "%s: Shutting down adapter.\n", dev->name );
wl_close( dev );
DBG_LEAVE( DbgInfo );
return 0;
} // wl_adapter_close
/*============================================================================*/
/*******************************************************************************
* wl_adapter_is_open()
*******************************************************************************
*
* DESCRIPTION:
*
* Check whether this device is open. Returns
*
* PARAMETERS:
*
* dev - a pointer to the device's net_device structure
*
* RETURNS:
*
* nonzero if device is open.
*
******************************************************************************/
int wl_adapter_is_open( struct net_device *dev )
{
/* This function is used in PCMCIA to check the status of the 'open' field
in the dev_link_t structure associated with a network device. There
doesn't seem to be an analog to this for PCI, and checking the status
contained in the net_device structure doesn't have the same effect.
For now, return TRUE, but find out if this is necessary for PCI. */
return TRUE;
} // wl_adapter_is_open
/*============================================================================*/
/*******************************************************************************
* wl_pci_probe()
*******************************************************************************
*
* DESCRIPTION:
*
* Registered in the pci_driver structure, this function is called when the
* PCI subsystem finds a new PCI device which matches the infomation contained
* in the pci_device_id table.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* ent - this device's entry in the pci_device_id table
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int __devinit wl_pci_probe( struct pci_dev *pdev,
const struct pci_device_id *ent )
{
int result;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_probe" );
DBG_ENTER( DbgInfo );
DBG_PRINT( "%s\n", VERSION_INFO );
result = wl_pci_setup( pdev );
DBG_LEAVE( DbgInfo );
return result;
} // wl_pci_probe
/*============================================================================*/
/*******************************************************************************
* wl_pci_remove()
*******************************************************************************
*
* DESCRIPTION:
*
* Registered in the pci_driver structure, this function is called when the
* PCI subsystem detects that a PCI device which matches the infomation
* contained in the pci_device_id table has been removed.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void __devexit wl_pci_remove(struct pci_dev *pdev)
{
struct net_device *dev = NULL;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_remove" );
DBG_ENTER( DbgInfo );
/* Make sure the pci_dev pointer passed in is valid */
if( pdev == NULL ) {
DBG_ERROR( DbgInfo, "PCI subsys passed in an invalid pci_dev pointer\n" );
return;
}
dev = pci_get_drvdata( pdev );
if( dev == NULL ) {
DBG_ERROR( DbgInfo, "Could not retrieve net_device structure\n" );
return;
}
/* Perform device cleanup */
wl_remove( dev );
free_irq( dev->irq, dev );
#ifdef ENABLE_DMA
wl_pci_dma_free( pdev, dev->priv );
#endif
wl_device_dealloc( dev );
DBG_LEAVE( DbgInfo );
return;
} // wl_pci_remove
/*============================================================================*/
/*******************************************************************************
* wl_pci_setup()
*******************************************************************************
*
* DESCRIPTION:
*
* Called by wl_pci_probe() to begin a device's initialization process.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_setup( struct pci_dev *pdev )
{
int result = 0;
struct net_device *dev = NULL;
struct wl_private *lp = NULL;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_setup" );
DBG_ENTER( DbgInfo );
/* Make sure the pci_dev pointer passed in is valid */
if( pdev == NULL ) {
DBG_ERROR( DbgInfo, "PCI subsys passed in an invalid pci_dev pointer\n" );
return -ENODEV;
}
result = pci_enable_device( pdev );
if( result != 0 ) {
DBG_ERROR( DbgInfo, "pci_enable_device() failed\n" );
DBG_LEAVE( DbgInfo );
return result;
}
/* We found our device! Let's register it with the system */
DBG_TRACE( DbgInfo, "Found our device, now registering\n" );
dev = wl_device_alloc( );
if( dev == NULL ) {
DBG_ERROR( DbgInfo, "Could not register device!!!\n" );
DBG_LEAVE( DbgInfo );
return -ENOMEM;
}
/* Make sure that space was allocated for our private adapter struct */
if( dev->priv == NULL ) {
DBG_ERROR( DbgInfo, "Private adapter struct was not allocated!!!\n" );
DBG_LEAVE( DbgInfo );
return -ENOMEM;
}
#ifdef ENABLE_DMA
/* Allocate DMA Descriptors */
if( wl_pci_dma_alloc( pdev, dev->priv ) < 0 ) {
DBG_ERROR( DbgInfo, "Could not allocate DMA descriptor memory!!!\n" );
DBG_LEAVE( DbgInfo );
return -ENOMEM;
}
#endif
/* Register our private adapter structure with PCI */
pci_set_drvdata( pdev, dev );
/* Fill out bus specific information in the net_device struct */
dev->irq = pdev->irq;
SET_MODULE_OWNER( dev );
DBG_TRACE( DbgInfo, "Device Base Address: %#03lx\n", pdev->resource[0].start );
dev->base_addr = pdev->resource[0].start;
/* Initialize our device here */
if( !wl_adapter_insert( dev )) {
DBG_ERROR( DbgInfo, "wl_adapter_insert() FAILED!!!\n" );
wl_device_dealloc( dev );
DBG_LEAVE( DbgInfo );
return -EINVAL;
}
/* Register our ISR */
DBG_TRACE( DbgInfo, "Registering ISR...\n" );
result = request_irq(dev->irq, wl_isr, SA_SHIRQ, dev->name, dev);
if( result ) {
DBG_WARNING( DbgInfo, "Could not register ISR!!!\n" );
DBG_LEAVE( DbgInfo );
return result;
}
/* Make sure interrupts are enabled properly for CardBus */
lp = dev->priv;
if( lp->hcfCtx.IFB_BusType == CFG_NIC_BUS_TYPE_CARDBUS ||
lp->hcfCtx.IFB_BusType == CFG_NIC_BUS_TYPE_PCI ) {
DBG_TRACE( DbgInfo, "This is a PCI/CardBus card, enable interrupts\n" );
wl_pci_enable_cardbus_interrupts( pdev );
}
/* Enable bus mastering */
pci_set_master( pdev );
DBG_LEAVE( DbgInfo );
return 0;
} // wl_pci_setup
/*============================================================================*/
/*******************************************************************************
* wl_pci_enable_cardbus_interrupts()
*******************************************************************************
*
* DESCRIPTION:
*
* Called by wl_pci_setup() to enable interrupts on a CardBus device. This
* is done by writing bit 15 to the function event mask register. This
* CardBus-specific register is located in BAR2 (counting from BAR0), in memory
* space at byte offset 1f4 (7f4 for WARP).
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_pci_enable_cardbus_interrupts( struct pci_dev *pdev )
{
u32 bar2_reg;
u32 mem_addr_bus;
u32 func_evt_mask_reg;
void *mem_addr_kern = NULL;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_enable_cardbus_interrupts" );
DBG_ENTER( DbgInfo );
/* Initialize to known bad values */
bar2_reg = 0xdeadbeef;
mem_addr_bus = 0xdeadbeef;
/* Read the BAR2 register; this register contains the base address of the
memory region where the function event mask register lives */
pci_read_config_dword( pdev, PCI_BASE_ADDRESS_2, &bar2_reg );
mem_addr_bus = bar2_reg & PCI_BASE_ADDRESS_MEM_MASK;
/* Once the base address is obtained, remap the memory region to kernel
space so we can retrieve the register */
mem_addr_kern = ioremap( mem_addr_bus, 0x200 );
#ifdef HERMES25
#define REG_OFFSET 0x07F4
#else
#define REG_OFFSET 0x01F4
#endif // HERMES25
#define BIT15 0x8000
/* Retrieve the functional event mask register, enable interrupts by
setting Bit 15, and write back the value */
func_evt_mask_reg = *(u32 *)( mem_addr_kern + REG_OFFSET );
func_evt_mask_reg |= BIT15;
*(u32 *)( mem_addr_kern + REG_OFFSET ) = func_evt_mask_reg;
/* Once complete, unmap the region and exit */
iounmap( mem_addr_kern );
DBG_LEAVE( DbgInfo );
return;
} // wl_pci_enable_cardbus_interrupts
/*============================================================================*/
#ifdef ENABLE_DMA
/*******************************************************************************
* wl_pci_dma_alloc()
*******************************************************************************
*
* DESCRIPTION:
*
* Allocates all resources needed for PCI/CardBus DMA operation
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_alloc( struct pci_dev *pdev, struct wl_private *lp )
{
int i;
int status = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_dma_alloc" );
DBG_ENTER( DbgInfo );
// lp->dma.tx_rsc_ind = lp->dma.rx_rsc_ind = 0;
//
// /* Alloc for the Tx chain and its reclaim descriptor */
// for( i = 0; i < NUM_TX_DESC; i++ ) {
// status = wl_pci_dma_alloc_tx_packet( pdev, lp, &lp->dma.tx_packet[i] );
// if( status == 0 ) {
// DBG_PRINT( "lp->dma.tx_packet[%d] : 0x%p\n", i, lp->dma.tx_packet[i] );
// DBG_PRINT( "lp->dma.tx_packet[%d]->next_desc_addr : 0x%p\n", i, lp->dma.tx_packet[i]->next_desc_addr );
// lp->dma.tx_rsc_ind++;
// } else {
// DBG_ERROR( DbgInfo, "Could not alloc DMA Tx Packet\n" );
// break;
// }
// }
// if( status == 0 ) {
// status = wl_pci_dma_alloc_desc( pdev, lp, &lp->dma.tx_reclaim_desc );
// DBG_PRINT( "lp->dma.tx_reclaim_desc: 0x%p\n", lp->dma.tx_reclaim_desc );
// }
// /* Alloc for the Rx chain and its reclaim descriptor */
// if( status == 0 ) {
// for( i = 0; i < NUM_RX_DESC; i++ ) {
// status = wl_pci_dma_alloc_rx_packet( pdev, lp, &lp->dma.rx_packet[i] );
// if( status == 0 ) {
// DBG_PRINT( "lp->dma.rx_packet[%d] : 0x%p\n", i, lp->dma.rx_packet[i] );
// DBG_PRINT( "lp->dma.rx_packet[%d]->next_desc_addr : 0x%p\n", i, lp->dma.rx_packet[i]->next_desc_addr );
// lp->dma.rx_rsc_ind++;
// } else {
// DBG_ERROR( DbgInfo, "Could not alloc DMA Rx Packet\n" );
// break;
// }
// }
// }
// if( status == 0 ) {
// status = wl_pci_dma_alloc_desc( pdev, lp, &lp->dma.rx_reclaim_desc );
// DBG_PRINT( "lp->dma.rx_reclaim_desc: 0x%p\n", lp->dma.rx_reclaim_desc );
// }
// /* Store status, as host should not call HCF functions if this fails */
// lp->dma.status = status; //;?all useages of dma.status have been commented out
// DBG_LEAVE( DbgInfo );
return status;
} // wl_pci_dma_alloc
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_free()
*******************************************************************************
*
* DESCRIPTION:
*
* Deallocated all resources needed for PCI/CardBus DMA operation
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_free( struct pci_dev *pdev, struct wl_private *lp )
{
int i;
int status = 0;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_dma_free" );
DBG_ENTER( DbgInfo );
/* Reclaim all Rx packets that were handed over to the HCF */
/* Do I need to do this? Before this free is called, I've already disabled
the port which will call wl_pci_dma_hcf_reclaim */
//if( lp->dma.status == 0 )
//{
// wl_pci_dma_hcf_reclaim( lp );
//}
/* Free everything needed for DMA Rx */
for( i = 0; i < NUM_RX_DESC; i++ ) {
if( lp->dma.rx_packet[i] ) {
status = wl_pci_dma_free_rx_packet( pdev, lp, &lp->dma.rx_packet[i] );
if( status != 0 ) {
DBG_WARNING( DbgInfo, "Problem freeing Rx packet\n" );
}
}
}
lp->dma.rx_rsc_ind = 0;
if( lp->dma.rx_reclaim_desc ) {
status = wl_pci_dma_free_desc( pdev, lp, &lp->dma.rx_reclaim_desc );
if( status != 0 ) {
DBG_WARNING( DbgInfo, "Problem freeing Rx reclaim descriptor\n" );
}
}
/* Free everything needed for DMA Tx */
for( i = 0; i < NUM_TX_DESC; i++ ) {
if( lp->dma.tx_packet[i] ) {
status = wl_pci_dma_free_tx_packet( pdev, lp, &lp->dma.tx_packet[i] );
if( status != 0 ) {
DBG_WARNING( DbgInfo, "Problem freeing Tx packet\n" );
}
}
}
lp->dma.tx_rsc_ind = 0;
if( lp->dma.tx_reclaim_desc ) {
status = wl_pci_dma_free_desc( pdev, lp, &lp->dma.tx_reclaim_desc );
if( status != 0 ) {
DBG_WARNING( DbgInfo, "Problem freeing Tx reclaim descriptor\n" );
}
}
DBG_LEAVE( DbgInfo );
return status;
} // wl_pci_dma_free
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_alloc_tx_packet()
*******************************************************************************
*
* DESCRIPTION:
*
* Allocates a single Tx packet, consisting of several descriptors and
* buffers. Data to transmit is first copied into the 'payload' buffer
* before being transmitted.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
* desc - a pointer which will reference the descriptor to be alloc'd.
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_alloc_tx_packet( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc )
{
// int status = 0;
// /*------------------------------------------------------------------------*/
//
// if( desc == NULL ) {
// status = -EFAULT;
// }
// if( status == 0 ) {
// status = wl_pci_dma_alloc_desc_and_buf( pdev, lp, desc,
// HCF_DMA_TX_BUF1_SIZE );
//
// if( status == 0 ) {
// status = wl_pci_dma_alloc_desc_and_buf( pdev, lp,
// &( (*desc)->next_desc_addr ),
// HCF_MAX_PACKET_SIZE );
// }
// }
// if( status == 0 ) {
// (*desc)->next_desc_phys_addr = (*desc)->next_desc_addr->desc_phys_addr;
// }
// return status;
} // wl_pci_dma_alloc_tx_packet
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_free_tx_packet()
*******************************************************************************
*
* DESCRIPTION:
*
* Frees a single Tx packet, described in the corresponding alloc function.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
* desc - a pointer which will reference the descriptor to be alloc'd.
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_free_tx_packet( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc )
{
int status = 0;
/*------------------------------------------------------------------------*/
if( *desc == NULL ) {
DBG_PRINT( "Null descriptor\n" );
status = -EFAULT;
}
//;?the "limited" NDIS strategy, assuming a frame consists ALWAYS out of 2
//descriptors, make this robust
if( status == 0 && (*desc)->next_desc_addr ) {
status = wl_pci_dma_free_desc_and_buf( pdev, lp, &(*desc)->next_desc_addr );
}
if( status == 0 ) {
status = wl_pci_dma_free_desc_and_buf( pdev, lp, desc );
}
return status;
} // wl_pci_dma_free_tx_packet
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_alloc_rx_packet()
*******************************************************************************
*
* DESCRIPTION:
*
* Allocates a single Rx packet, consisting of two descriptors and one
* contiguous buffer. THe buffer starts with the hermes-specific header.
* One descriptor points at the start, the other at offset 0x3a of the
* buffer.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
* desc - a pointer which will reference the descriptor to be alloc'd.
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_alloc_rx_packet( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc )
{
int status = 0;
DESC_STRCT *p;
/*------------------------------------------------------------------------*/
// if( desc == NULL ) {
// status = -EFAULT;
// }
// //;?the "limited" NDIS strategy, assuming a frame consists ALWAYS out of 2
// //descriptors, make this robust
// if( status == 0 ) {
// status = wl_pci_dma_alloc_desc( pdev, lp, desc );
// }
// if( status == 0 ) {
// status = wl_pci_dma_alloc_buf( pdev, lp, *desc, HCF_MAX_PACKET_SIZE );
// }
// if( status == 0 ) {
// status = wl_pci_dma_alloc_desc( pdev, lp, &p );
// }
// if( status == 0 ) {
// /* Size of 1st descriptor becomes 0x3a bytes */
// SET_BUF_SIZE( *desc, HCF_DMA_RX_BUF1_SIZE );
//
// /* Make 2nd descriptor point at offset 0x3a of the buffer */
// SET_BUF_SIZE( p, ( HCF_MAX_PACKET_SIZE - HCF_DMA_RX_BUF1_SIZE ));
// p->buf_addr = (*desc)->buf_addr + HCF_DMA_RX_BUF1_SIZE;
// p->buf_phys_addr = (*desc)->buf_phys_addr + HCF_DMA_RX_BUF1_SIZE;
// p->next_desc_addr = NULL;
//
// /* Chain 2nd descriptor to 1st descriptor */
// (*desc)->next_desc_addr = p;
// (*desc)->next_desc_phys_addr = p->desc_phys_addr;
// }
return status;
} // wl_pci_dma_alloc_rx_packet
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_free_rx_packet()
*******************************************************************************
*
* DESCRIPTION:
*
* Frees a single Rx packet, described in the corresponding alloc function.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
* desc - a pointer which will reference the descriptor to be alloc'd.
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_free_rx_packet( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc )
{
int status = 0;
DESC_STRCT *p;
/*------------------------------------------------------------------------*/
if( *desc == NULL ) {
status = -EFAULT;
}
if( status == 0 ) {
p = (*desc)->next_desc_addr;
/* Free the 2nd descriptor */
if( p != NULL ) {
p->buf_addr = NULL;
p->buf_phys_addr = 0;
status = wl_pci_dma_free_desc( pdev, lp, &p );
}
}
/* Free the buffer and 1st descriptor */
if( status == 0 ) {
SET_BUF_SIZE( *desc, HCF_MAX_PACKET_SIZE );
status = wl_pci_dma_free_desc_and_buf( pdev, lp, desc );
}
return status;
} // wl_pci_dma_free_rx_packet
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_alloc_desc_and_buf()
*******************************************************************************
*
* DESCRIPTION:
*
* Allocates a DMA descriptor and buffer, and associates them with one
* another.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
* desc - a pointer which will reference the descriptor to be alloc'd
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_alloc_desc_and_buf( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc, int size )
{
int status = 0;
/*------------------------------------------------------------------------*/
// if( desc == NULL ) {
// status = -EFAULT;
// }
// if( status == 0 ) {
// status = wl_pci_dma_alloc_desc( pdev, lp, desc );
//
// if( status == 0 ) {
// status = wl_pci_dma_alloc_buf( pdev, lp, *desc, size );
// }
// }
return status;
} // wl_pci_dma_alloc_desc_and_buf
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_free_desc_and_buf()
*******************************************************************************
*
* DESCRIPTION:
*
* Frees a DMA descriptor and associated buffer.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
* desc - a pointer which will reference the descriptor to be alloc'd
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_free_desc_and_buf( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc )
{
int status = 0;
/*------------------------------------------------------------------------*/
if( desc == NULL ) {
status = -EFAULT;
}
if( status == 0 && *desc == NULL ) {
status = -EFAULT;
}
if( status == 0 ) {
status = wl_pci_dma_free_buf( pdev, lp, *desc );
if( status == 0 ) {
status = wl_pci_dma_free_desc( pdev, lp, desc );
}
}
return status;
} // wl_pci_dma_free_desc_and_buf
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_alloc_desc()
*******************************************************************************
*
* DESCRIPTION:
*
* Allocates one DMA descriptor in cache coherent memory.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_alloc_desc( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc )
{
// int status = 0;
// dma_addr_t pa;
// /*------------------------------------------------------------------------*/
//
// DBG_FUNC( "wl_pci_dma_alloc_desc" );
// DBG_ENTER( DbgInfo );
//
// if( desc == NULL ) {
// status = -EFAULT;
// }
// if( status == 0 ) {
// *desc = pci_alloc_consistent( pdev, sizeof( DESC_STRCT ), &pa );
// }
// if( *desc == NULL ) {
// DBG_ERROR( DbgInfo, "pci_alloc_consistent() failed\n" );
// status = -ENOMEM;
// } else {
// memset( *desc, 0, sizeof( DESC_STRCT ));
// (*desc)->desc_phys_addr = cpu_to_le32( pa );
// }
// DBG_LEAVE( DbgInfo );
// return status;
} // wl_pci_dma_alloc_desc
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_free_desc()
*******************************************************************************
*
* DESCRIPTION:
*
* Frees one DMA descriptor in cache coherent memory.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_free_desc( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT **desc )
{
int status = 0;
/*------------------------------------------------------------------------*/
if( *desc == NULL ) {
status = -EFAULT;
}
if( status == 0 ) {
pci_free_consistent( pdev, sizeof( DESC_STRCT ), *desc,
(*desc)->desc_phys_addr );
}
*desc = NULL;
return status;
} // wl_pci_dma_free_desc
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_alloc_buf()
*******************************************************************************
*
* DESCRIPTION:
*
* Allocates one DMA buffer in cache coherent memory, and associates a DMA
* descriptor with this buffer.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_alloc_buf( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT *desc, int size )
{
int status = 0;
dma_addr_t pa;
/*------------------------------------------------------------------------*/
// DBG_FUNC( "wl_pci_dma_alloc_buf" );
// DBG_ENTER( DbgInfo );
//
// if( desc == NULL ) {
// status = -EFAULT;
// }
// if( status == 0 && desc->buf_addr != NULL ) {
// status = -EFAULT;
// }
// if( status == 0 ) {
// desc->buf_addr = pci_alloc_consistent( pdev, size, &pa );
// }
// if( desc->buf_addr == NULL ) {
// DBG_ERROR( DbgInfo, "pci_alloc_consistent() failed\n" );
// status = -ENOMEM;
// } else {
// desc->buf_phys_addr = cpu_to_le32( pa );
// SET_BUF_SIZE( desc, size );
// }
// DBG_LEAVE( DbgInfo );
return status;
} // wl_pci_dma_alloc_buf
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_free_buf()
*******************************************************************************
*
* DESCRIPTION:
*
* Allocates one DMA buffer in cache coherent memory, and associates a DMA
* descriptor with this buffer.
*
* PARAMETERS:
*
* pdev - a pointer to the device's pci_dev structure
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
int wl_pci_dma_free_buf( struct pci_dev *pdev, struct wl_private *lp,
DESC_STRCT *desc )
{
int status = 0;
/*------------------------------------------------------------------------*/
if( desc == NULL ) {
status = -EFAULT;
}
if( status == 0 && desc->buf_addr == NULL ) {
status = -EFAULT;
}
if( status == 0 ) {
pci_free_consistent( pdev, GET_BUF_SIZE( desc ), desc->buf_addr,
desc->buf_phys_addr );
desc->buf_addr = 0;
desc->buf_phys_addr = 0;
SET_BUF_SIZE( desc, 0 );
}
return status;
} // wl_pci_dma_free_buf
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_hcf_supply()
*******************************************************************************
*
* DESCRIPTION:
*
* Supply HCF with DMA-related resources. These consist of:
* - buffers and descriptors for receive purposes
* - one 'reclaim' descriptor for the transmit path, used to fulfill a
* certain H25 DMA engine requirement
* - one 'reclaim' descriptor for the receive path, used to fulfill a
* certain H25 DMA engine requirement
*
* This function is called at start-of-day or at re-initialization.
*
* PARAMETERS:
*
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
void wl_pci_dma_hcf_supply( struct wl_private *lp )
{
int i;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_dma_hcf_supply" );
DBG_ENTER( DbgInfo );
//if( lp->dma.status == 0 );
//{
/* Hand over the Rx/Tx reclaim descriptors to the HCF */
if( lp->dma.tx_reclaim_desc ) {
DBG_PRINT( "lp->dma.tx_reclaim_desc: 0x%p\n", lp->dma.tx_reclaim_desc );
hcf_dma_tx_put( &lp->hcfCtx, lp->dma.tx_reclaim_desc, 0 );
lp->dma.tx_reclaim_desc = NULL;
DBG_PRINT( "lp->dma.tx_reclaim_desc: 0x%p\n", lp->dma.tx_reclaim_desc );
}
if( lp->dma.rx_reclaim_desc ) {
DBG_PRINT( "lp->dma.rx_reclaim_desc: 0x%p\n", lp->dma.rx_reclaim_desc );
hcf_dma_rx_put( &lp->hcfCtx, lp->dma.rx_reclaim_desc );
lp->dma.rx_reclaim_desc = NULL;
DBG_PRINT( "lp->dma.rx_reclaim_desc: 0x%p\n", lp->dma.rx_reclaim_desc );
}
/* Hand over the Rx descriptor chain to the HCF */
for( i = 0; i < NUM_RX_DESC; i++ ) {
DBG_PRINT( "lp->dma.rx_packet[%d]: 0x%p\n", i, lp->dma.rx_packet[i] );
hcf_dma_rx_put( &lp->hcfCtx, lp->dma.rx_packet[i] );
lp->dma.rx_packet[i] = NULL;
DBG_PRINT( "lp->dma.rx_packet[%d]: 0x%p\n", i, lp->dma.rx_packet[i] );
}
//}
DBG_LEAVE( DbgInfo );
return;
} // wl_pci_dma_hcf_supply
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_hcf_reclaim()
*******************************************************************************
*
* DESCRIPTION:
*
* Return DMA-related resources from the HCF. These consist of:
* - buffers and descriptors for receive purposes
* - buffers and descriptors for transmit purposes
* - one 'reclaim' descriptor for the transmit path, used to fulfill a
* certain H25 DMA engine requirement
* - one 'reclaim' descriptor for the receive path, used to fulfill a
* certain H25 DMA engine requirement
*
* This function is called at end-of-day or at re-initialization.
*
* PARAMETERS:
*
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
void wl_pci_dma_hcf_reclaim( struct wl_private *lp )
{
int i;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_dma_hcf_reclaim" );
DBG_ENTER( DbgInfo );
wl_pci_dma_hcf_reclaim_rx( lp );
for( i = 0; i < NUM_RX_DESC; i++ ) {
DBG_PRINT( "rx_packet[%d] 0x%p\n", i, lp->dma.rx_packet[i] );
// if( lp->dma.rx_packet[i] == NULL ) {
// DBG_PRINT( "wl_pci_dma_hcf_reclaim: rx_packet[%d] NULL\n", i );
// }
}
wl_pci_dma_hcf_reclaim_tx( lp );
for( i = 0; i < NUM_TX_DESC; i++ ) {
DBG_PRINT( "tx_packet[%d] 0x%p\n", i, lp->dma.tx_packet[i] );
// if( lp->dma.tx_packet[i] == NULL ) {
// DBG_PRINT( "wl_pci_dma_hcf_reclaim: tx_packet[%d] NULL\n", i );
// }
}
DBG_LEAVE( DbgInfo );
return;
} // wl_pci_dma_hcf_reclaim
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_hcf_reclaim_rx()
*******************************************************************************
*
* DESCRIPTION:
*
* Reclaim Rx packets that have already been processed by the HCF.
*
* PARAMETERS:
*
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
void wl_pci_dma_hcf_reclaim_rx( struct wl_private *lp )
{
int i;
DESC_STRCT *p;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_dma_hcf_reclaim_rx" );
DBG_ENTER( DbgInfo );
//if( lp->dma.status == 0 )
//{
while ( ( p = hcf_dma_rx_get( &lp->hcfCtx ) ) != NULL ) {
if( p && p->buf_addr == NULL ) {
/* A reclaim descriptor is being given back by the HCF. Reclaim
descriptors have a NULL buf_addr */
lp->dma.rx_reclaim_desc = p;
DBG_PRINT( "reclaim_descriptor: 0x%p\n", p );
continue;
}
for( i = 0; i < NUM_RX_DESC; i++ ) {
if( lp->dma.rx_packet[i] == NULL ) {
break;
}
}
/* An Rx buffer descriptor is being given back by the HCF */
lp->dma.rx_packet[i] = p;
lp->dma.rx_rsc_ind++;
DBG_PRINT( "rx_packet[%d] 0x%p\n", i, lp->dma.rx_packet[i] );
}
//}
DBG_LEAVE( DbgInfo );
} // wl_pci_dma_hcf_reclaim_rx
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_get_tx_packet()
*******************************************************************************
*
* DESCRIPTION:
*
* Obtains a Tx descriptor from the chain to use for Tx.
*
* PARAMETERS:
*
* lp - a pointer to the device's wl_private structure.
*
* RETURNS:
*
* A pointer to the retrieved descriptor
*
******************************************************************************/
DESC_STRCT * wl_pci_dma_get_tx_packet( struct wl_private *lp )
{
int i;
DESC_STRCT *desc = NULL;
/*------------------------------------------------------------------------*/
for( i = 0; i < NUM_TX_DESC; i++ ) {
if( lp->dma.tx_packet[i] ) {
break;
}
}
if( i != NUM_TX_DESC ) {
desc = lp->dma.tx_packet[i];
lp->dma.tx_packet[i] = NULL;
lp->dma.tx_rsc_ind--;
memset( desc->buf_addr, 0, HCF_DMA_TX_BUF1_SIZE );
}
return desc;
} // wl_pci_dma_get_tx_packet
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_put_tx_packet()
*******************************************************************************
*
* DESCRIPTION:
*
* Returns a Tx descriptor to the chain.
*
* PARAMETERS:
*
* lp - a pointer to the device's wl_private structure.
* desc - a pointer to the descriptor to return.
*
* RETURNS:
*
* N/A
*
******************************************************************************/
void wl_pci_dma_put_tx_packet( struct wl_private *lp, DESC_STRCT *desc )
{
int i;
/*------------------------------------------------------------------------*/
for( i = 0; i < NUM_TX_DESC; i++ ) {
if( lp->dma.tx_packet[i] == NULL ) {
break;
}
}
if( i != NUM_TX_DESC ) {
lp->dma.tx_packet[i] = desc;
lp->dma.tx_rsc_ind++;
}
} // wl_pci_dma_put_tx_packet
/*============================================================================*/
/*******************************************************************************
* wl_pci_dma_hcf_reclaim_tx()
*******************************************************************************
*
* DESCRIPTION:
*
* Reclaim Tx packets that have either been processed by the HCF due to a
* port disable or a Tx completion.
*
* PARAMETERS:
*
* lp - the device's private adapter structure
*
* RETURNS:
*
* 0 on success
* errno value otherwise
*
******************************************************************************/
void wl_pci_dma_hcf_reclaim_tx( struct wl_private *lp )
{
int i;
DESC_STRCT *p;
/*------------------------------------------------------------------------*/
DBG_FUNC( "wl_pci_dma_hcf_reclaim_tx" );
DBG_ENTER( DbgInfo );
//if( lp->dma.status == 0 )
//{
while ( ( p = hcf_dma_tx_get( &lp->hcfCtx ) ) != NULL ) {
if( p != NULL && p->buf_addr == NULL ) {
/* A Reclaim descriptor is being given back by the HCF. Reclaim
descriptors have a NULL buf_addr */
lp->dma.tx_reclaim_desc = p;
DBG_PRINT( "reclaim_descriptor: 0x%p\n", p );
continue;
}
for( i = 0; i < NUM_TX_DESC; i++ ) {
if( lp->dma.tx_packet[i] == NULL ) {
break;
}
}
/* An Rx buffer descriptor is being given back by the HCF */
lp->dma.tx_packet[i] = p;
lp->dma.tx_rsc_ind++;
DBG_PRINT( "tx_packet[%d] 0x%p\n", i, lp->dma.tx_packet[i] );
}
//}
if( lp->netif_queue_on == FALSE ) {
netif_wake_queue( lp->dev );
WL_WDS_NETIF_WAKE_QUEUE( lp );
lp->netif_queue_on = TRUE;
}
DBG_LEAVE( DbgInfo );
return;
} // wl_pci_dma_hcf_reclaim_tx
/*============================================================================*/
#endif // ENABLE_DMA
| gpl-2.0 |
derekhe-hardware/huawei-g330d-u8825d-kernel | drivers/macintosh/ams/ams-core.c | 3198 | 6104 | /*
* Apple Motion Sensor driver
*
* Copyright (C) 2005 Stelian Pop (stelian@popies.net)
* Copyright (C) 2006 Michael Hanselmann (linux-kernel@hansmi.ch)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/of_platform.h>
#include <asm/pmac_pfunc.h>
#include "ams.h"
/* There is only one motion sensor per machine */
struct ams ams_info;
static unsigned int verbose;
module_param(verbose, bool, 0644);
MODULE_PARM_DESC(verbose, "Show free falls and shocks in kernel output");
/* Call with ams_info.lock held! */
void ams_sensors(s8 *x, s8 *y, s8 *z)
{
u32 orient = ams_info.vflag? ams_info.orient1 : ams_info.orient2;
if (orient & 0x80)
/* X and Y swapped */
ams_info.get_xyz(y, x, z);
else
ams_info.get_xyz(x, y, z);
if (orient & 0x04)
*z = ~(*z);
if (orient & 0x02)
*y = ~(*y);
if (orient & 0x01)
*x = ~(*x);
}
static ssize_t ams_show_current(struct device *dev,
struct device_attribute *attr, char *buf)
{
s8 x, y, z;
mutex_lock(&ams_info.lock);
ams_sensors(&x, &y, &z);
mutex_unlock(&ams_info.lock);
return snprintf(buf, PAGE_SIZE, "%d %d %d\n", x, y, z);
}
static DEVICE_ATTR(current, S_IRUGO, ams_show_current, NULL);
static void ams_handle_irq(void *data)
{
enum ams_irq irq = *((enum ams_irq *)data);
spin_lock(&ams_info.irq_lock);
ams_info.worker_irqs |= irq;
schedule_work(&ams_info.worker);
spin_unlock(&ams_info.irq_lock);
}
static enum ams_irq ams_freefall_irq_data = AMS_IRQ_FREEFALL;
static struct pmf_irq_client ams_freefall_client = {
.owner = THIS_MODULE,
.handler = ams_handle_irq,
.data = &ams_freefall_irq_data,
};
static enum ams_irq ams_shock_irq_data = AMS_IRQ_SHOCK;
static struct pmf_irq_client ams_shock_client = {
.owner = THIS_MODULE,
.handler = ams_handle_irq,
.data = &ams_shock_irq_data,
};
/* Once hard disk parking is implemented in the kernel, this function can
* trigger it.
*/
static void ams_worker(struct work_struct *work)
{
unsigned long flags;
u8 irqs_to_clear;
mutex_lock(&ams_info.lock);
spin_lock_irqsave(&ams_info.irq_lock, flags);
irqs_to_clear = ams_info.worker_irqs;
if (ams_info.worker_irqs & AMS_IRQ_FREEFALL) {
if (verbose)
printk(KERN_INFO "ams: freefall detected!\n");
ams_info.worker_irqs &= ~AMS_IRQ_FREEFALL;
}
if (ams_info.worker_irqs & AMS_IRQ_SHOCK) {
if (verbose)
printk(KERN_INFO "ams: shock detected!\n");
ams_info.worker_irqs &= ~AMS_IRQ_SHOCK;
}
spin_unlock_irqrestore(&ams_info.irq_lock, flags);
ams_info.clear_irq(irqs_to_clear);
mutex_unlock(&ams_info.lock);
}
/* Call with ams_info.lock held! */
int ams_sensor_attach(void)
{
int result;
const u32 *prop;
/* Get orientation */
prop = of_get_property(ams_info.of_node, "orientation", NULL);
if (!prop)
return -ENODEV;
ams_info.orient1 = *prop;
ams_info.orient2 = *(prop + 1);
/* Register freefall interrupt handler */
result = pmf_register_irq_client(ams_info.of_node,
"accel-int-1",
&ams_freefall_client);
if (result < 0)
return -ENODEV;
/* Reset saved irqs */
ams_info.worker_irqs = 0;
/* Register shock interrupt handler */
result = pmf_register_irq_client(ams_info.of_node,
"accel-int-2",
&ams_shock_client);
if (result < 0)
goto release_freefall;
/* Create device */
ams_info.of_dev = of_platform_device_create(ams_info.of_node, "ams", NULL);
if (!ams_info.of_dev) {
result = -ENODEV;
goto release_shock;
}
/* Create attributes */
result = device_create_file(&ams_info.of_dev->dev, &dev_attr_current);
if (result)
goto release_of;
ams_info.vflag = !!(ams_info.get_vendor() & 0x10);
/* Init input device */
result = ams_input_init();
if (result)
goto release_device_file;
return result;
release_device_file:
device_remove_file(&ams_info.of_dev->dev, &dev_attr_current);
release_of:
of_device_unregister(ams_info.of_dev);
release_shock:
pmf_unregister_irq_client(&ams_shock_client);
release_freefall:
pmf_unregister_irq_client(&ams_freefall_client);
return result;
}
int __init ams_init(void)
{
struct device_node *np;
spin_lock_init(&ams_info.irq_lock);
mutex_init(&ams_info.lock);
INIT_WORK(&ams_info.worker, ams_worker);
#ifdef CONFIG_SENSORS_AMS_I2C
np = of_find_node_by_name(NULL, "accelerometer");
if (np && of_device_is_compatible(np, "AAPL,accelerometer_1"))
/* Found I2C motion sensor */
return ams_i2c_init(np);
#endif
#ifdef CONFIG_SENSORS_AMS_PMU
np = of_find_node_by_name(NULL, "sms");
if (np && of_device_is_compatible(np, "sms"))
/* Found PMU motion sensor */
return ams_pmu_init(np);
#endif
return -ENODEV;
}
void ams_sensor_detach(void)
{
/* Remove input device */
ams_input_exit();
/* Remove attributes */
device_remove_file(&ams_info.of_dev->dev, &dev_attr_current);
/* Flush interrupt worker
*
* We do this after ams_info.exit(), because an interrupt might
* have arrived before disabling them.
*/
flush_work_sync(&ams_info.worker);
/* Remove device */
of_device_unregister(ams_info.of_dev);
/* Remove handler */
pmf_unregister_irq_client(&ams_shock_client);
pmf_unregister_irq_client(&ams_freefall_client);
}
static void __exit ams_exit(void)
{
/* Shut down implementation */
ams_info.exit();
}
MODULE_AUTHOR("Stelian Pop, Michael Hanselmann");
MODULE_DESCRIPTION("Apple Motion Sensor driver");
MODULE_LICENSE("GPL");
module_init(ams_init);
module_exit(ams_exit);
| gpl-2.0 |
Anonim47/android_kernel_lenovo_armani | arch/arm/mach-ep93xx/micro9.c | 4734 | 3564 | /*
* linux/arch/arm/mach-ep93xx/micro9.c
*
* Copyright (C) 2006 Contec Steuerungstechnik & Automation GmbH
* Manfred Gruber <m.gruber@tirol.com>
* Copyright (C) 2009 Contec Steuerungstechnik & Automation GmbH
* Hubert Feurstein <hubert.feurstein@contec.at>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/hardware/vic.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include "soc.h"
/*************************************************************************
* Micro9 NOR Flash
*
* Micro9-High has up to 64MB of 32-bit flash on CS1
* Micro9-Mid has up to 64MB of either 32-bit or 16-bit flash on CS1
* Micro9-Lite uses a separate MTD map driver for flash support
* Micro9-Slim has up to 64MB of either 32-bit or 16-bit flash on CS1
*************************************************************************/
static unsigned int __init micro9_detect_bootwidth(void)
{
u32 v;
/* Detect the bus width of the external flash memory */
v = __raw_readl(EP93XX_SYSCON_SYSCFG);
if (v & EP93XX_SYSCON_SYSCFG_LCSN7)
return 4; /* 32-bit */
else
return 2; /* 16-bit */
}
static void __init micro9_register_flash(void)
{
unsigned int width;
if (machine_is_micro9())
width = 4;
else if (machine_is_micro9m() || machine_is_micro9s())
width = micro9_detect_bootwidth();
else
width = 0;
if (width)
ep93xx_register_flash(width, EP93XX_CS1_PHYS_BASE, SZ_64M);
}
/*************************************************************************
* Micro9 Ethernet
*************************************************************************/
static struct ep93xx_eth_data __initdata micro9_eth_data = {
.phy_id = 0x1f,
};
static void __init micro9_init_machine(void)
{
ep93xx_init_devices();
ep93xx_register_eth(µ9_eth_data, 1);
micro9_register_flash();
}
#ifdef CONFIG_MACH_MICRO9H
MACHINE_START(MICRO9, "Contec Micro9-High")
/* Maintainer: Hubert Feurstein <hubert.feurstein@contec.at> */
.atag_offset = 0x100,
.map_io = ep93xx_map_io,
.init_irq = ep93xx_init_irq,
.handle_irq = vic_handle_irq,
.timer = &ep93xx_timer,
.init_machine = micro9_init_machine,
.restart = ep93xx_restart,
MACHINE_END
#endif
#ifdef CONFIG_MACH_MICRO9M
MACHINE_START(MICRO9M, "Contec Micro9-Mid")
/* Maintainer: Hubert Feurstein <hubert.feurstein@contec.at> */
.atag_offset = 0x100,
.map_io = ep93xx_map_io,
.init_irq = ep93xx_init_irq,
.handle_irq = vic_handle_irq,
.timer = &ep93xx_timer,
.init_machine = micro9_init_machine,
.restart = ep93xx_restart,
MACHINE_END
#endif
#ifdef CONFIG_MACH_MICRO9L
MACHINE_START(MICRO9L, "Contec Micro9-Lite")
/* Maintainer: Hubert Feurstein <hubert.feurstein@contec.at> */
.atag_offset = 0x100,
.map_io = ep93xx_map_io,
.init_irq = ep93xx_init_irq,
.handle_irq = vic_handle_irq,
.timer = &ep93xx_timer,
.init_machine = micro9_init_machine,
.restart = ep93xx_restart,
MACHINE_END
#endif
#ifdef CONFIG_MACH_MICRO9S
MACHINE_START(MICRO9S, "Contec Micro9-Slim")
/* Maintainer: Hubert Feurstein <hubert.feurstein@contec.at> */
.atag_offset = 0x100,
.map_io = ep93xx_map_io,
.init_irq = ep93xx_init_irq,
.handle_irq = vic_handle_irq,
.timer = &ep93xx_timer,
.init_machine = micro9_init_machine,
.restart = ep93xx_restart,
MACHINE_END
#endif
| gpl-2.0 |
Tab3/android_kernel_samsung_lt02 | arch/arm/mach-omap1/board-voiceblue.c | 4734 | 7402 | /*
* linux/arch/arm/mach-omap1/board-voiceblue.c
*
* Modified from board-generic.c
*
* Copyright (C) 2004 2N Telekomunikace, Ladislav Michl <michl@2n.cz>
*
* Code for OMAP5910 based VoiceBlue board (VoIP to GSM gateway).
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/mtd/physmap.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/serial_8250.h>
#include <linux/serial_reg.h>
#include <linux/smc91x.h>
#include <linux/export.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <plat/board-voiceblue.h>
#include <plat/flash.h>
#include <plat/mux.h>
#include <plat/tc.h>
#include <plat/usb.h>
#include <mach/hardware.h>
#include "common.h"
static struct plat_serial8250_port voiceblue_ports[] = {
{
.mapbase = (unsigned long)(OMAP_CS1_PHYS + 0x40000),
.flags = UPF_BOOT_AUTOCONF | UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 1,
.uartclk = 3686400,
},
{
.mapbase = (unsigned long)(OMAP_CS1_PHYS + 0x50000),
.flags = UPF_BOOT_AUTOCONF | UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 1,
.uartclk = 3686400,
},
{
.mapbase = (unsigned long)(OMAP_CS1_PHYS + 0x60000),
.flags = UPF_BOOT_AUTOCONF | UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 1,
.uartclk = 3686400,
},
{
.mapbase = (unsigned long)(OMAP_CS1_PHYS + 0x70000),
.flags = UPF_BOOT_AUTOCONF | UPF_IOREMAP,
.iotype = UPIO_MEM,
.regshift = 1,
.uartclk = 3686400,
},
{ },
};
static struct platform_device serial_device = {
.name = "serial8250",
.id = PLAT8250_DEV_PLATFORM1,
};
static int __init ext_uart_init(void)
{
if (!machine_is_voiceblue())
return -ENODEV;
voiceblue_ports[0].irq = gpio_to_irq(12);
voiceblue_ports[1].irq = gpio_to_irq(13);
voiceblue_ports[2].irq = gpio_to_irq(14);
voiceblue_ports[3].irq = gpio_to_irq(15);
serial_device.dev.platform_data = voiceblue_ports;
return platform_device_register(&serial_device);
}
arch_initcall(ext_uart_init);
static struct physmap_flash_data voiceblue_flash_data = {
.width = 2,
.set_vpp = omap1_set_vpp,
};
static struct resource voiceblue_flash_resource = {
.start = OMAP_CS0_PHYS,
.end = OMAP_CS0_PHYS + SZ_32M - 1,
.flags = IORESOURCE_MEM,
};
static struct platform_device voiceblue_flash_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &voiceblue_flash_data,
},
.num_resources = 1,
.resource = &voiceblue_flash_resource,
};
static struct smc91x_platdata voiceblue_smc91x_info = {
.flags = SMC91X_USE_16BIT | SMC91X_NOWAIT,
.leda = RPC_LED_100_10,
.ledb = RPC_LED_TX_RX,
};
static struct resource voiceblue_smc91x_resources[] = {
[0] = {
.start = OMAP_CS2_PHYS + 0x300,
.end = OMAP_CS2_PHYS + 0x300 + 16,
.flags = IORESOURCE_MEM,
},
[1] = {
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE,
},
};
static struct platform_device voiceblue_smc91x_device = {
.name = "smc91x",
.id = 0,
.dev = {
.platform_data = &voiceblue_smc91x_info,
},
.num_resources = ARRAY_SIZE(voiceblue_smc91x_resources),
.resource = voiceblue_smc91x_resources,
};
static struct platform_device *voiceblue_devices[] __initdata = {
&voiceblue_flash_device,
&voiceblue_smc91x_device,
};
static struct omap_usb_config voiceblue_usb_config __initdata = {
.hmc_mode = 3,
.register_host = 1,
.register_dev = 1,
.pins[0] = 2,
.pins[1] = 6,
.pins[2] = 6,
};
static struct omap_board_config_kernel voiceblue_config[] = {
};
#define MACHINE_PANICED 1
#define MACHINE_REBOOTING 2
#define MACHINE_REBOOT 4
static unsigned long machine_state;
static int panic_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
if (test_and_set_bit(MACHINE_PANICED, &machine_state))
return NOTIFY_DONE;
/* Flash power LED */
omap_writeb(0x78, OMAP_LPG1_LCR);
omap_writeb(0x01, OMAP_LPG1_PMR); /* Enable clock */
return NOTIFY_DONE;
}
static struct notifier_block panic_block = {
.notifier_call = panic_event,
};
static int __init voiceblue_setup(void)
{
if (!machine_is_voiceblue())
return -ENODEV;
/* Setup panic notifier */
atomic_notifier_chain_register(&panic_notifier_list, &panic_block);
return 0;
}
postcore_initcall(voiceblue_setup);
static int wdt_gpio_state;
void voiceblue_wdt_enable(void)
{
gpio_direction_output(0, 0);
gpio_set_value(0, 1);
gpio_set_value(0, 0);
wdt_gpio_state = 0;
}
void voiceblue_wdt_disable(void)
{
gpio_set_value(0, 0);
gpio_set_value(0, 1);
gpio_set_value(0, 0);
gpio_direction_input(0);
}
void voiceblue_wdt_ping(void)
{
if (test_bit(MACHINE_REBOOT, &machine_state))
return;
wdt_gpio_state = !wdt_gpio_state;
gpio_set_value(0, wdt_gpio_state);
}
static void voiceblue_restart(char mode, const char *cmd)
{
/*
* Workaround for 5912/1611b bug mentioned in sprz209d.pdf p. 28
* "Global Software Reset Affects Traffic Controller Frequency".
*/
if (cpu_is_omap5912()) {
omap_writew(omap_readw(DPLL_CTL) & ~(1 << 4), DPLL_CTL);
omap_writew(0x8, ARM_RSTCT1);
}
set_bit(MACHINE_REBOOT, &machine_state);
voiceblue_wdt_enable();
while (1) ;
}
EXPORT_SYMBOL(voiceblue_wdt_enable);
EXPORT_SYMBOL(voiceblue_wdt_disable);
EXPORT_SYMBOL(voiceblue_wdt_ping);
static void __init voiceblue_init(void)
{
/* mux pins for uarts */
omap_cfg_reg(UART1_TX);
omap_cfg_reg(UART1_RTS);
omap_cfg_reg(UART2_TX);
omap_cfg_reg(UART2_RTS);
omap_cfg_reg(UART3_TX);
omap_cfg_reg(UART3_RX);
/* Watchdog */
gpio_request(0, "Watchdog");
/* smc91x reset */
gpio_request(7, "SMC91x reset");
gpio_direction_output(7, 1);
udelay(2); /* wait at least 100ns */
gpio_set_value(7, 0);
mdelay(50); /* 50ms until PHY ready */
/* smc91x interrupt pin */
gpio_request(8, "SMC91x irq");
/* 16C554 reset*/
gpio_request(6, "16C554 reset");
gpio_direction_output(6, 0);
/* 16C554 interrupt pins */
gpio_request(12, "16C554 irq");
gpio_request(13, "16C554 irq");
gpio_request(14, "16C554 irq");
gpio_request(15, "16C554 irq");
irq_set_irq_type(gpio_to_irq(12), IRQ_TYPE_EDGE_RISING);
irq_set_irq_type(gpio_to_irq(13), IRQ_TYPE_EDGE_RISING);
irq_set_irq_type(gpio_to_irq(14), IRQ_TYPE_EDGE_RISING);
irq_set_irq_type(gpio_to_irq(15), IRQ_TYPE_EDGE_RISING);
voiceblue_smc91x_resources[1].start = gpio_to_irq(8);
voiceblue_smc91x_resources[1].end = gpio_to_irq(8);
platform_add_devices(voiceblue_devices, ARRAY_SIZE(voiceblue_devices));
omap_board_config = voiceblue_config;
omap_board_config_size = ARRAY_SIZE(voiceblue_config);
omap_serial_init();
omap1_usb_init(&voiceblue_usb_config);
omap_register_i2c_bus(1, 100, NULL, 0);
/* There is a good chance board is going up, so enable power LED
* (it is connected through invertor) */
omap_writeb(0x00, OMAP_LPG1_LCR);
omap_writeb(0x00, OMAP_LPG1_PMR); /* Disable clock */
}
MACHINE_START(VOICEBLUE, "VoiceBlue OMAP5910")
/* Maintainer: Ladislav Michl <michl@2n.cz> */
.atag_offset = 0x100,
.map_io = omap15xx_map_io,
.init_early = omap1_init_early,
.reserve = omap_reserve,
.init_irq = omap1_init_irq,
.init_machine = voiceblue_init,
.timer = &omap1_timer,
.restart = voiceblue_restart,
MACHINE_END
| gpl-2.0 |
pekaka/N900-Exynos-kernel-4.3 | arch/arm/mach-mxs/mach-m28evk.c | 4734 | 10650 | /*
* Copyright (C) 2011
* Stefano Babic, DENX Software Engineering, <sbabic@denx.de>
*
* based on: mach-mx28_evk.c
* Copyright 2010 Freescale Semiconductor, 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.
*/
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/leds.h>
#include <linux/irq.h>
#include <linux/clk.h>
#include <linux/i2c.h>
#include <linux/i2c/at24.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/mach/time.h>
#include <mach/common.h>
#include <mach/iomux-mx28.h>
#include "devices-mx28.h"
#define M28EVK_GPIO_USERLED1 MXS_GPIO_NR(3, 16)
#define M28EVK_GPIO_USERLED2 MXS_GPIO_NR(3, 17)
#define MX28EVK_BL_ENABLE MXS_GPIO_NR(3, 18)
#define M28EVK_LCD_ENABLE MXS_GPIO_NR(3, 28)
#define MX28EVK_MMC0_WRITE_PROTECT MXS_GPIO_NR(2, 12)
#define MX28EVK_MMC1_WRITE_PROTECT MXS_GPIO_NR(0, 28)
static const iomux_cfg_t m28evk_pads[] __initconst = {
/* duart */
MX28_PAD_AUART0_CTS__DUART_RX | MXS_PAD_CTRL,
MX28_PAD_AUART0_RTS__DUART_TX | MXS_PAD_CTRL,
/* auart0 */
MX28_PAD_AUART0_RX__AUART0_RX | MXS_PAD_CTRL,
MX28_PAD_AUART0_TX__AUART0_TX | MXS_PAD_CTRL,
/* auart3 */
MX28_PAD_AUART3_RX__AUART3_RX | MXS_PAD_CTRL,
MX28_PAD_AUART3_TX__AUART3_TX | MXS_PAD_CTRL,
MX28_PAD_AUART3_CTS__AUART3_CTS | MXS_PAD_CTRL,
MX28_PAD_AUART3_RTS__AUART3_RTS | MXS_PAD_CTRL,
#define MXS_PAD_FEC (MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP)
/* fec0 */
MX28_PAD_ENET0_MDC__ENET0_MDC | MXS_PAD_FEC,
MX28_PAD_ENET0_MDIO__ENET0_MDIO | MXS_PAD_FEC,
MX28_PAD_ENET0_RX_EN__ENET0_RX_EN | MXS_PAD_FEC,
MX28_PAD_ENET0_RXD0__ENET0_RXD0 | MXS_PAD_FEC,
MX28_PAD_ENET0_RXD1__ENET0_RXD1 | MXS_PAD_FEC,
MX28_PAD_ENET0_TX_EN__ENET0_TX_EN | MXS_PAD_FEC,
MX28_PAD_ENET0_TXD0__ENET0_TXD0 | MXS_PAD_FEC,
MX28_PAD_ENET0_TXD1__ENET0_TXD1 | MXS_PAD_FEC,
MX28_PAD_ENET_CLK__CLKCTRL_ENET | MXS_PAD_FEC,
/* fec1 */
MX28_PAD_ENET0_CRS__ENET1_RX_EN | MXS_PAD_FEC,
MX28_PAD_ENET0_RXD2__ENET1_RXD0 | MXS_PAD_FEC,
MX28_PAD_ENET0_RXD3__ENET1_RXD1 | MXS_PAD_FEC,
MX28_PAD_ENET0_COL__ENET1_TX_EN | MXS_PAD_FEC,
MX28_PAD_ENET0_TXD2__ENET1_TXD0 | MXS_PAD_FEC,
MX28_PAD_ENET0_TXD3__ENET1_TXD1 | MXS_PAD_FEC,
/* flexcan0 */
MX28_PAD_GPMI_RDY2__CAN0_TX,
MX28_PAD_GPMI_RDY3__CAN0_RX,
/* flexcan1 */
MX28_PAD_GPMI_CE2N__CAN1_TX,
MX28_PAD_GPMI_CE3N__CAN1_RX,
/* I2C */
MX28_PAD_I2C0_SCL__I2C0_SCL,
MX28_PAD_I2C0_SDA__I2C0_SDA,
/* mxsfb (lcdif) */
MX28_PAD_LCD_D00__LCD_D0 | MXS_PAD_CTRL,
MX28_PAD_LCD_D01__LCD_D1 | MXS_PAD_CTRL,
MX28_PAD_LCD_D02__LCD_D2 | MXS_PAD_CTRL,
MX28_PAD_LCD_D03__LCD_D3 | MXS_PAD_CTRL,
MX28_PAD_LCD_D04__LCD_D4 | MXS_PAD_CTRL,
MX28_PAD_LCD_D05__LCD_D5 | MXS_PAD_CTRL,
MX28_PAD_LCD_D06__LCD_D6 | MXS_PAD_CTRL,
MX28_PAD_LCD_D07__LCD_D7 | MXS_PAD_CTRL,
MX28_PAD_LCD_D08__LCD_D8 | MXS_PAD_CTRL,
MX28_PAD_LCD_D09__LCD_D9 | MXS_PAD_CTRL,
MX28_PAD_LCD_D10__LCD_D10 | MXS_PAD_CTRL,
MX28_PAD_LCD_D11__LCD_D11 | MXS_PAD_CTRL,
MX28_PAD_LCD_D12__LCD_D12 | MXS_PAD_CTRL,
MX28_PAD_LCD_D13__LCD_D13 | MXS_PAD_CTRL,
MX28_PAD_LCD_D14__LCD_D14 | MXS_PAD_CTRL,
MX28_PAD_LCD_D15__LCD_D15 | MXS_PAD_CTRL,
MX28_PAD_LCD_D16__LCD_D16 | MXS_PAD_CTRL,
MX28_PAD_LCD_D17__LCD_D17 | MXS_PAD_CTRL,
MX28_PAD_LCD_D18__LCD_D18 | MXS_PAD_CTRL,
MX28_PAD_LCD_D19__LCD_D19 | MXS_PAD_CTRL,
MX28_PAD_LCD_D20__LCD_D20 | MXS_PAD_CTRL,
MX28_PAD_LCD_D21__LCD_D21 | MXS_PAD_CTRL,
MX28_PAD_LCD_D22__LCD_D22 | MXS_PAD_CTRL,
MX28_PAD_LCD_D23__LCD_D23 | MXS_PAD_CTRL,
MX28_PAD_LCD_ENABLE__LCD_ENABLE | MXS_PAD_CTRL,
MX28_PAD_LCD_DOTCLK__LCD_DOTCLK | MXS_PAD_CTRL,
/* mmc0 */
MX28_PAD_SSP0_DATA0__SSP0_D0 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_SSP0_DATA1__SSP0_D1 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_SSP0_DATA2__SSP0_D2 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_SSP0_DATA3__SSP0_D3 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_SSP0_DATA4__SSP0_D4 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_SSP0_DATA5__SSP0_D5 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_SSP0_DATA6__SSP0_D6 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_SSP0_DATA7__SSP0_D7 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_SSP0_CMD__SSP0_CMD |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_SSP0_DETECT__SSP0_CARD_DETECT |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_NOPULL),
MX28_PAD_SSP0_SCK__SSP0_SCK |
(MXS_PAD_12MA | MXS_PAD_3V3 | MXS_PAD_NOPULL),
/* mmc1 */
MX28_PAD_GPMI_D00__SSP1_D0 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_D01__SSP1_D1 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_D02__SSP1_D2 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_D03__SSP1_D3 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_D04__SSP1_D4 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_D05__SSP1_D5 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_D06__SSP1_D6 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_D07__SSP1_D7 |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_RDY1__SSP1_CMD |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_RDY0__SSP1_CARD_DETECT |
(MXS_PAD_8MA | MXS_PAD_3V3 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_WRN__SSP1_SCK |
(MXS_PAD_12MA | MXS_PAD_3V3 | MXS_PAD_NOPULL),
/* write protect */
MX28_PAD_GPMI_RESETN__GPIO_0_28 |
(MXS_PAD_4MA | MXS_PAD_3V3 | MXS_PAD_NOPULL),
/* slot power enable */
MX28_PAD_PWM4__GPIO_3_29 |
(MXS_PAD_4MA | MXS_PAD_3V3 | MXS_PAD_NOPULL),
/* led */
MX28_PAD_PWM0__GPIO_3_16 | MXS_PAD_CTRL,
MX28_PAD_PWM1__GPIO_3_17 | MXS_PAD_CTRL,
/* nand */
MX28_PAD_GPMI_D00__GPMI_D0 |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_D01__GPMI_D1 |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_D02__GPMI_D2 |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_D03__GPMI_D3 |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_D04__GPMI_D4 |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_D05__GPMI_D5 |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_D06__GPMI_D6 |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_D07__GPMI_D7 |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_CE0N__GPMI_CE0N |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_RDY0__GPMI_READY0 |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_NOPULL),
MX28_PAD_GPMI_RDN__GPMI_RDN |
(MXS_PAD_12MA | MXS_PAD_1V8 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_WRN__GPMI_WRN |
(MXS_PAD_12MA | MXS_PAD_1V8 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_ALE__GPMI_ALE |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_CLE__GPMI_CLE |
(MXS_PAD_4MA | MXS_PAD_1V8 | MXS_PAD_PULLUP),
MX28_PAD_GPMI_RESETN__GPMI_RESETN |
(MXS_PAD_12MA | MXS_PAD_1V8 | MXS_PAD_PULLUP),
/* Backlight */
MX28_PAD_PWM3__GPIO_3_28 | MXS_PAD_CTRL,
};
/* led */
static const struct gpio_led m28evk_leds[] __initconst = {
{
.name = "user-led1",
.default_trigger = "heartbeat",
.gpio = M28EVK_GPIO_USERLED1,
},
{
.name = "user-led2",
.default_trigger = "heartbeat",
.gpio = M28EVK_GPIO_USERLED2,
},
};
static const struct gpio_led_platform_data m28evk_led_data __initconst = {
.leds = m28evk_leds,
.num_leds = ARRAY_SIZE(m28evk_leds),
};
static struct fec_platform_data mx28_fec_pdata[] __initdata = {
{
/* fec0 */
.phy = PHY_INTERFACE_MODE_RMII,
}, {
/* fec1 */
.phy = PHY_INTERFACE_MODE_RMII,
},
};
static int __init m28evk_fec_get_mac(void)
{
int i;
u32 val;
const u32 *ocotp = mxs_get_ocotp();
if (!ocotp)
return -ETIMEDOUT;
/*
* OCOTP only stores the last 4 octets for each mac address,
* so hard-code DENX OUI (C0:E5:4E) here.
*/
for (i = 0; i < 2; i++) {
val = ocotp[i];
mx28_fec_pdata[i].mac[0] = 0xC0;
mx28_fec_pdata[i].mac[1] = 0xE5;
mx28_fec_pdata[i].mac[2] = 0x4E;
mx28_fec_pdata[i].mac[3] = (val >> 16) & 0xff;
mx28_fec_pdata[i].mac[4] = (val >> 8) & 0xff;
mx28_fec_pdata[i].mac[5] = (val >> 0) & 0xff;
}
return 0;
}
/* mxsfb (lcdif) */
static struct fb_videomode m28evk_video_modes[] = {
{
.name = "Ampire AM-800480R2TMQW-T01H",
.refresh = 60,
.xres = 800,
.yres = 480,
.pixclock = 30066, /* picosecond (33.26 MHz) */
.left_margin = 0,
.right_margin = 256,
.upper_margin = 0,
.lower_margin = 45,
.hsync_len = 1,
.vsync_len = 1,
.sync = FB_SYNC_DATA_ENABLE_HIGH_ACT,
},
};
static const struct mxsfb_platform_data m28evk_mxsfb_pdata __initconst = {
.mode_list = m28evk_video_modes,
.mode_count = ARRAY_SIZE(m28evk_video_modes),
.default_bpp = 16,
.ld_intf_width = STMLCDIF_18BIT,
};
static struct at24_platform_data m28evk_eeprom = {
.byte_len = 16384,
.page_size = 32,
.flags = AT24_FLAG_ADDR16,
};
static struct i2c_board_info m28_stk5v3_i2c_boardinfo[] __initdata = {
{
I2C_BOARD_INFO("at24", 0x51), /* E0=1, E1=0, E2=0 */
.platform_data = &m28evk_eeprom,
},
};
static struct mxs_mmc_platform_data m28evk_mmc_pdata[] __initdata = {
{
/* mmc0 */
.wp_gpio = MX28EVK_MMC0_WRITE_PROTECT,
.flags = SLOTF_8_BIT_CAPABLE,
}, {
/* mmc1 */
.wp_gpio = MX28EVK_MMC1_WRITE_PROTECT,
.flags = SLOTF_8_BIT_CAPABLE,
},
};
static void __init m28evk_init(void)
{
mxs_iomux_setup_multiple_pads(m28evk_pads, ARRAY_SIZE(m28evk_pads));
mx28_add_duart();
mx28_add_auart0();
mx28_add_auart3();
if (!m28evk_fec_get_mac()) {
mx28_add_fec(0, &mx28_fec_pdata[0]);
mx28_add_fec(1, &mx28_fec_pdata[1]);
}
mx28_add_flexcan(0, NULL);
mx28_add_flexcan(1, NULL);
mx28_add_mxsfb(&m28evk_mxsfb_pdata);
mx28_add_mxs_mmc(0, &m28evk_mmc_pdata[0]);
mx28_add_mxs_mmc(1, &m28evk_mmc_pdata[1]);
gpio_led_register_device(0, &m28evk_led_data);
/* I2C */
mx28_add_mxs_i2c(0);
i2c_register_board_info(0, m28_stk5v3_i2c_boardinfo,
ARRAY_SIZE(m28_stk5v3_i2c_boardinfo));
}
static void __init m28evk_timer_init(void)
{
mx28_clocks_init();
}
static struct sys_timer m28evk_timer = {
.init = m28evk_timer_init,
};
MACHINE_START(M28EVK, "DENX M28 EVK")
.map_io = mx28_map_io,
.init_irq = mx28_init_irq,
.timer = &m28evk_timer,
.init_machine = m28evk_init,
.restart = mxs_restart,
MACHINE_END
| gpl-2.0 |
LibiSC/Smt520Test | drivers/isdn/hardware/mISDN/mISDNinfineon.c | 4990 | 27751 | /*
* mISDNinfineon.c
* Support for cards based on following Infineon ISDN chipsets
* - ISAC + HSCX
* - IPAC and IPAC-X
* - ISAC-SX + HSCX
*
* Supported cards:
* - Dialogic Diva 2.0
* - Dialogic Diva 2.0U
* - Dialogic Diva 2.01
* - Dialogic Diva 2.02
* - Sedlbauer Speedwin
* - HST Saphir3
* - Develo (former ELSA) Microlink PCI (Quickstep 1000)
* - Develo (former ELSA) Quickstep 3000
* - Berkom Scitel BRIX Quadro
* - Dr.Neuhaus (Sagem) Niccy
*
*
*
* Author Karsten Keil <keil@isdn4linux.de>
*
* Copyright 2009 by Karsten Keil <keil@isdn4linux.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.
*
* 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/interrupt.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/mISDNhw.h>
#include <linux/slab.h>
#include "ipac.h"
#define INFINEON_REV "1.0"
static int inf_cnt;
static u32 debug;
static u32 irqloops = 4;
enum inf_types {
INF_NONE,
INF_DIVA20,
INF_DIVA20U,
INF_DIVA201,
INF_DIVA202,
INF_SPEEDWIN,
INF_SAPHIR3,
INF_QS1000,
INF_QS3000,
INF_NICCY,
INF_SCT_1,
INF_SCT_2,
INF_SCT_3,
INF_SCT_4,
INF_GAZEL_R685,
INF_GAZEL_R753
};
enum addr_mode {
AM_NONE = 0,
AM_IO,
AM_MEMIO,
AM_IND_IO,
};
struct inf_cinfo {
enum inf_types typ;
const char *full;
const char *name;
enum addr_mode cfg_mode;
enum addr_mode addr_mode;
u8 cfg_bar;
u8 addr_bar;
void *irqfunc;
};
struct _ioaddr {
enum addr_mode mode;
union {
void __iomem *p;
struct _ioport io;
} a;
};
struct _iohandle {
enum addr_mode mode;
resource_size_t size;
resource_size_t start;
void __iomem *p;
};
struct inf_hw {
struct list_head list;
struct pci_dev *pdev;
const struct inf_cinfo *ci;
char name[MISDN_MAX_IDLEN];
u32 irq;
u32 irqcnt;
struct _iohandle cfg;
struct _iohandle addr;
struct _ioaddr isac;
struct _ioaddr hscx;
spinlock_t lock; /* HW access lock */
struct ipac_hw ipac;
struct inf_hw *sc[3]; /* slave cards */
};
#define PCI_SUBVENDOR_HST_SAPHIR3 0x52
#define PCI_SUBVENDOR_SEDLBAUER_PCI 0x53
#define PCI_SUB_ID_SEDLBAUER 0x01
static struct pci_device_id infineon_ids[] __devinitdata = {
{ PCI_VDEVICE(EICON, PCI_DEVICE_ID_EICON_DIVA20), INF_DIVA20 },
{ PCI_VDEVICE(EICON, PCI_DEVICE_ID_EICON_DIVA20_U), INF_DIVA20U },
{ PCI_VDEVICE(EICON, PCI_DEVICE_ID_EICON_DIVA201), INF_DIVA201 },
{ PCI_VDEVICE(EICON, PCI_DEVICE_ID_EICON_DIVA202), INF_DIVA202 },
{ PCI_VENDOR_ID_TIGERJET, PCI_DEVICE_ID_TIGERJET_100,
PCI_SUBVENDOR_SEDLBAUER_PCI, PCI_SUB_ID_SEDLBAUER, 0, 0,
INF_SPEEDWIN },
{ PCI_VENDOR_ID_TIGERJET, PCI_DEVICE_ID_TIGERJET_100,
PCI_SUBVENDOR_HST_SAPHIR3, PCI_SUB_ID_SEDLBAUER, 0, 0, INF_SAPHIR3 },
{ PCI_VDEVICE(ELSA, PCI_DEVICE_ID_ELSA_MICROLINK), INF_QS1000 },
{ PCI_VDEVICE(ELSA, PCI_DEVICE_ID_ELSA_QS3000), INF_QS3000 },
{ PCI_VDEVICE(SATSAGEM, PCI_DEVICE_ID_SATSAGEM_NICCY), INF_NICCY },
{ PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050,
PCI_VENDOR_ID_BERKOM, PCI_DEVICE_ID_BERKOM_SCITEL_QUADRO, 0, 0,
INF_SCT_1 },
{ PCI_VDEVICE(PLX, PCI_DEVICE_ID_PLX_R685), INF_GAZEL_R685 },
{ PCI_VDEVICE(PLX, PCI_DEVICE_ID_PLX_R753), INF_GAZEL_R753 },
{ PCI_VDEVICE(PLX, PCI_DEVICE_ID_PLX_DJINN_ITOO), INF_GAZEL_R753 },
{ PCI_VDEVICE(PLX, PCI_DEVICE_ID_PLX_OLITEC), INF_GAZEL_R753 },
{ }
};
MODULE_DEVICE_TABLE(pci, infineon_ids);
/* PCI interface specific defines */
/* Diva 2.0/2.0U */
#define DIVA_HSCX_PORT 0x00
#define DIVA_HSCX_ALE 0x04
#define DIVA_ISAC_PORT 0x08
#define DIVA_ISAC_ALE 0x0C
#define DIVA_PCI_CTRL 0x10
/* DIVA_PCI_CTRL bits */
#define DIVA_IRQ_BIT 0x01
#define DIVA_RESET_BIT 0x08
#define DIVA_EEPROM_CLK 0x40
#define DIVA_LED_A 0x10
#define DIVA_LED_B 0x20
#define DIVA_IRQ_CLR 0x80
/* Diva 2.01/2.02 */
/* Siemens PITA */
#define PITA_ICR_REG 0x00
#define PITA_INT0_STATUS 0x02
#define PITA_MISC_REG 0x1c
#define PITA_PARA_SOFTRESET 0x01000000
#define PITA_SER_SOFTRESET 0x02000000
#define PITA_PARA_MPX_MODE 0x04000000
#define PITA_INT0_ENABLE 0x00020000
/* TIGER 100 Registers */
#define TIGER_RESET_ADDR 0x00
#define TIGER_EXTERN_RESET 0x01
#define TIGER_AUX_CTRL 0x02
#define TIGER_AUX_DATA 0x03
#define TIGER_AUX_IRQMASK 0x05
#define TIGER_AUX_STATUS 0x07
/* Tiger AUX BITs */
#define TIGER_IOMASK 0xdd /* 1 and 5 are inputs */
#define TIGER_IRQ_BIT 0x02
#define TIGER_IPAC_ALE 0xC0
#define TIGER_IPAC_PORT 0xC8
/* ELSA (now Develo) PCI cards */
#define ELSA_IRQ_ADDR 0x4c
#define ELSA_IRQ_MASK 0x04
#define QS1000_IRQ_OFF 0x01
#define QS3000_IRQ_OFF 0x03
#define QS1000_IRQ_ON 0x41
#define QS3000_IRQ_ON 0x43
/* Dr Neuhaus/Sagem Niccy */
#define NICCY_ISAC_PORT 0x00
#define NICCY_HSCX_PORT 0x01
#define NICCY_ISAC_ALE 0x02
#define NICCY_HSCX_ALE 0x03
#define NICCY_IRQ_CTRL_REG 0x38
#define NICCY_IRQ_ENABLE 0x001f00
#define NICCY_IRQ_DISABLE 0xff0000
#define NICCY_IRQ_BIT 0x800000
/* Scitel PLX */
#define SCT_PLX_IRQ_ADDR 0x4c
#define SCT_PLX_RESET_ADDR 0x50
#define SCT_PLX_IRQ_ENABLE 0x41
#define SCT_PLX_RESET_BIT 0x04
/* Gazel */
#define GAZEL_IPAC_DATA_PORT 0x04
/* Gazel PLX */
#define GAZEL_CNTRL 0x50
#define GAZEL_RESET 0x04
#define GAZEL_RESET_9050 0x40000000
#define GAZEL_INCSR 0x4C
#define GAZEL_ISAC_EN 0x08
#define GAZEL_INT_ISAC 0x20
#define GAZEL_HSCX_EN 0x01
#define GAZEL_INT_HSCX 0x04
#define GAZEL_PCI_EN 0x40
#define GAZEL_IPAC_EN 0x03
static LIST_HEAD(Cards);
static DEFINE_RWLOCK(card_lock); /* protect Cards */
static void
_set_debug(struct inf_hw *card)
{
card->ipac.isac.dch.debug = debug;
card->ipac.hscx[0].bch.debug = debug;
card->ipac.hscx[1].bch.debug = debug;
}
static int
set_debug(const char *val, struct kernel_param *kp)
{
int ret;
struct inf_hw *card;
ret = param_set_uint(val, kp);
if (!ret) {
read_lock(&card_lock);
list_for_each_entry(card, &Cards, list)
_set_debug(card);
read_unlock(&card_lock);
}
return ret;
}
MODULE_AUTHOR("Karsten Keil");
MODULE_LICENSE("GPL v2");
MODULE_VERSION(INFINEON_REV);
module_param_call(debug, set_debug, param_get_uint, &debug, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "infineon debug mask");
module_param(irqloops, uint, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(irqloops, "infineon maximal irqloops (default 4)");
/* Interface functions */
IOFUNC_IO(ISAC, inf_hw, isac.a.io)
IOFUNC_IO(IPAC, inf_hw, hscx.a.io)
IOFUNC_IND(ISAC, inf_hw, isac.a.io)
IOFUNC_IND(IPAC, inf_hw, hscx.a.io)
IOFUNC_MEMIO(ISAC, inf_hw, u32, isac.a.p)
IOFUNC_MEMIO(IPAC, inf_hw, u32, hscx.a.p)
static irqreturn_t
diva_irq(int intno, void *dev_id)
{
struct inf_hw *hw = dev_id;
u8 val;
spin_lock(&hw->lock);
val = inb((u32)hw->cfg.start + DIVA_PCI_CTRL);
if (!(val & DIVA_IRQ_BIT)) { /* for us or shared ? */
spin_unlock(&hw->lock);
return IRQ_NONE; /* shared */
}
hw->irqcnt++;
mISDNipac_irq(&hw->ipac, irqloops);
spin_unlock(&hw->lock);
return IRQ_HANDLED;
}
static irqreturn_t
diva20x_irq(int intno, void *dev_id)
{
struct inf_hw *hw = dev_id;
u8 val;
spin_lock(&hw->lock);
val = readb(hw->cfg.p);
if (!(val & PITA_INT0_STATUS)) { /* for us or shared ? */
spin_unlock(&hw->lock);
return IRQ_NONE; /* shared */
}
hw->irqcnt++;
mISDNipac_irq(&hw->ipac, irqloops);
writeb(PITA_INT0_STATUS, hw->cfg.p); /* ACK PITA INT0 */
spin_unlock(&hw->lock);
return IRQ_HANDLED;
}
static irqreturn_t
tiger_irq(int intno, void *dev_id)
{
struct inf_hw *hw = dev_id;
u8 val;
spin_lock(&hw->lock);
val = inb((u32)hw->cfg.start + TIGER_AUX_STATUS);
if (val & TIGER_IRQ_BIT) { /* for us or shared ? */
spin_unlock(&hw->lock);
return IRQ_NONE; /* shared */
}
hw->irqcnt++;
mISDNipac_irq(&hw->ipac, irqloops);
spin_unlock(&hw->lock);
return IRQ_HANDLED;
}
static irqreturn_t
elsa_irq(int intno, void *dev_id)
{
struct inf_hw *hw = dev_id;
u8 val;
spin_lock(&hw->lock);
val = inb((u32)hw->cfg.start + ELSA_IRQ_ADDR);
if (!(val & ELSA_IRQ_MASK)) {
spin_unlock(&hw->lock);
return IRQ_NONE; /* shared */
}
hw->irqcnt++;
mISDNipac_irq(&hw->ipac, irqloops);
spin_unlock(&hw->lock);
return IRQ_HANDLED;
}
static irqreturn_t
niccy_irq(int intno, void *dev_id)
{
struct inf_hw *hw = dev_id;
u32 val;
spin_lock(&hw->lock);
val = inl((u32)hw->cfg.start + NICCY_IRQ_CTRL_REG);
if (!(val & NICCY_IRQ_BIT)) { /* for us or shared ? */
spin_unlock(&hw->lock);
return IRQ_NONE; /* shared */
}
outl(val, (u32)hw->cfg.start + NICCY_IRQ_CTRL_REG);
hw->irqcnt++;
mISDNipac_irq(&hw->ipac, irqloops);
spin_unlock(&hw->lock);
return IRQ_HANDLED;
}
static irqreturn_t
gazel_irq(int intno, void *dev_id)
{
struct inf_hw *hw = dev_id;
irqreturn_t ret;
spin_lock(&hw->lock);
ret = mISDNipac_irq(&hw->ipac, irqloops);
spin_unlock(&hw->lock);
return ret;
}
static irqreturn_t
ipac_irq(int intno, void *dev_id)
{
struct inf_hw *hw = dev_id;
u8 val;
spin_lock(&hw->lock);
val = hw->ipac.read_reg(hw, IPAC_ISTA);
if (!(val & 0x3f)) {
spin_unlock(&hw->lock);
return IRQ_NONE; /* shared */
}
hw->irqcnt++;
mISDNipac_irq(&hw->ipac, irqloops);
spin_unlock(&hw->lock);
return IRQ_HANDLED;
}
static void
enable_hwirq(struct inf_hw *hw)
{
u16 w;
u32 val;
switch (hw->ci->typ) {
case INF_DIVA201:
case INF_DIVA202:
writel(PITA_INT0_ENABLE, hw->cfg.p);
break;
case INF_SPEEDWIN:
case INF_SAPHIR3:
outb(TIGER_IRQ_BIT, (u32)hw->cfg.start + TIGER_AUX_IRQMASK);
break;
case INF_QS1000:
outb(QS1000_IRQ_ON, (u32)hw->cfg.start + ELSA_IRQ_ADDR);
break;
case INF_QS3000:
outb(QS3000_IRQ_ON, (u32)hw->cfg.start + ELSA_IRQ_ADDR);
break;
case INF_NICCY:
val = inl((u32)hw->cfg.start + NICCY_IRQ_CTRL_REG);
val |= NICCY_IRQ_ENABLE;
outl(val, (u32)hw->cfg.start + NICCY_IRQ_CTRL_REG);
break;
case INF_SCT_1:
w = inw((u32)hw->cfg.start + SCT_PLX_IRQ_ADDR);
w |= SCT_PLX_IRQ_ENABLE;
outw(w, (u32)hw->cfg.start + SCT_PLX_IRQ_ADDR);
break;
case INF_GAZEL_R685:
outb(GAZEL_ISAC_EN + GAZEL_HSCX_EN + GAZEL_PCI_EN,
(u32)hw->cfg.start + GAZEL_INCSR);
break;
case INF_GAZEL_R753:
outb(GAZEL_IPAC_EN + GAZEL_PCI_EN,
(u32)hw->cfg.start + GAZEL_INCSR);
break;
default:
break;
}
}
static void
disable_hwirq(struct inf_hw *hw)
{
u16 w;
u32 val;
switch (hw->ci->typ) {
case INF_DIVA201:
case INF_DIVA202:
writel(0, hw->cfg.p);
break;
case INF_SPEEDWIN:
case INF_SAPHIR3:
outb(0, (u32)hw->cfg.start + TIGER_AUX_IRQMASK);
break;
case INF_QS1000:
outb(QS1000_IRQ_OFF, (u32)hw->cfg.start + ELSA_IRQ_ADDR);
break;
case INF_QS3000:
outb(QS3000_IRQ_OFF, (u32)hw->cfg.start + ELSA_IRQ_ADDR);
break;
case INF_NICCY:
val = inl((u32)hw->cfg.start + NICCY_IRQ_CTRL_REG);
val &= NICCY_IRQ_DISABLE;
outl(val, (u32)hw->cfg.start + NICCY_IRQ_CTRL_REG);
break;
case INF_SCT_1:
w = inw((u32)hw->cfg.start + SCT_PLX_IRQ_ADDR);
w &= (~SCT_PLX_IRQ_ENABLE);
outw(w, (u32)hw->cfg.start + SCT_PLX_IRQ_ADDR);
break;
case INF_GAZEL_R685:
case INF_GAZEL_R753:
outb(0, (u32)hw->cfg.start + GAZEL_INCSR);
break;
default:
break;
}
}
static void
ipac_chip_reset(struct inf_hw *hw)
{
hw->ipac.write_reg(hw, IPAC_POTA2, 0x20);
mdelay(5);
hw->ipac.write_reg(hw, IPAC_POTA2, 0x00);
mdelay(5);
hw->ipac.write_reg(hw, IPAC_CONF, hw->ipac.conf);
hw->ipac.write_reg(hw, IPAC_MASK, 0xc0);
}
static void
reset_inf(struct inf_hw *hw)
{
u16 w;
u32 val;
if (debug & DEBUG_HW)
pr_notice("%s: resetting card\n", hw->name);
switch (hw->ci->typ) {
case INF_DIVA20:
case INF_DIVA20U:
outb(0, (u32)hw->cfg.start + DIVA_PCI_CTRL);
mdelay(10);
outb(DIVA_RESET_BIT, (u32)hw->cfg.start + DIVA_PCI_CTRL);
mdelay(10);
/* Workaround PCI9060 */
outb(9, (u32)hw->cfg.start + 0x69);
outb(DIVA_RESET_BIT | DIVA_LED_A,
(u32)hw->cfg.start + DIVA_PCI_CTRL);
break;
case INF_DIVA201:
writel(PITA_PARA_SOFTRESET | PITA_PARA_MPX_MODE,
hw->cfg.p + PITA_MISC_REG);
mdelay(1);
writel(PITA_PARA_MPX_MODE, hw->cfg.p + PITA_MISC_REG);
mdelay(10);
break;
case INF_DIVA202:
writel(PITA_PARA_SOFTRESET | PITA_PARA_MPX_MODE,
hw->cfg.p + PITA_MISC_REG);
mdelay(1);
writel(PITA_PARA_MPX_MODE | PITA_SER_SOFTRESET,
hw->cfg.p + PITA_MISC_REG);
mdelay(10);
break;
case INF_SPEEDWIN:
case INF_SAPHIR3:
ipac_chip_reset(hw);
hw->ipac.write_reg(hw, IPAC_ACFG, 0xff);
hw->ipac.write_reg(hw, IPAC_AOE, 0x00);
hw->ipac.write_reg(hw, IPAC_PCFG, 0x12);
break;
case INF_QS1000:
case INF_QS3000:
ipac_chip_reset(hw);
hw->ipac.write_reg(hw, IPAC_ACFG, 0x00);
hw->ipac.write_reg(hw, IPAC_AOE, 0x3c);
hw->ipac.write_reg(hw, IPAC_ATX, 0xff);
break;
case INF_NICCY:
break;
case INF_SCT_1:
w = inw((u32)hw->cfg.start + SCT_PLX_RESET_ADDR);
w &= (~SCT_PLX_RESET_BIT);
outw(w, (u32)hw->cfg.start + SCT_PLX_RESET_ADDR);
mdelay(10);
w = inw((u32)hw->cfg.start + SCT_PLX_RESET_ADDR);
w |= SCT_PLX_RESET_BIT;
outw(w, (u32)hw->cfg.start + SCT_PLX_RESET_ADDR);
mdelay(10);
break;
case INF_GAZEL_R685:
val = inl((u32)hw->cfg.start + GAZEL_CNTRL);
val |= (GAZEL_RESET_9050 + GAZEL_RESET);
outl(val, (u32)hw->cfg.start + GAZEL_CNTRL);
val &= ~(GAZEL_RESET_9050 + GAZEL_RESET);
mdelay(4);
outl(val, (u32)hw->cfg.start + GAZEL_CNTRL);
mdelay(10);
hw->ipac.isac.adf2 = 0x87;
hw->ipac.hscx[0].slot = 0x1f;
hw->ipac.hscx[1].slot = 0x23;
break;
case INF_GAZEL_R753:
val = inl((u32)hw->cfg.start + GAZEL_CNTRL);
val |= (GAZEL_RESET_9050 + GAZEL_RESET);
outl(val, (u32)hw->cfg.start + GAZEL_CNTRL);
val &= ~(GAZEL_RESET_9050 + GAZEL_RESET);
mdelay(4);
outl(val, (u32)hw->cfg.start + GAZEL_CNTRL);
mdelay(10);
ipac_chip_reset(hw);
hw->ipac.write_reg(hw, IPAC_ACFG, 0xff);
hw->ipac.write_reg(hw, IPAC_AOE, 0x00);
hw->ipac.conf = 0x01; /* IOM off */
break;
default:
return;
}
enable_hwirq(hw);
}
static int
inf_ctrl(struct inf_hw *hw, u32 cmd, u_long arg)
{
int ret = 0;
switch (cmd) {
case HW_RESET_REQ:
reset_inf(hw);
break;
default:
pr_info("%s: %s unknown command %x %lx\n",
hw->name, __func__, cmd, arg);
ret = -EINVAL;
break;
}
return ret;
}
static int __devinit
init_irq(struct inf_hw *hw)
{
int ret, cnt = 3;
u_long flags;
if (!hw->ci->irqfunc)
return -EINVAL;
ret = request_irq(hw->irq, hw->ci->irqfunc, IRQF_SHARED, hw->name, hw);
if (ret) {
pr_info("%s: couldn't get interrupt %d\n", hw->name, hw->irq);
return ret;
}
while (cnt--) {
spin_lock_irqsave(&hw->lock, flags);
reset_inf(hw);
ret = hw->ipac.init(&hw->ipac);
if (ret) {
spin_unlock_irqrestore(&hw->lock, flags);
pr_info("%s: ISAC init failed with %d\n",
hw->name, ret);
break;
}
spin_unlock_irqrestore(&hw->lock, flags);
msleep_interruptible(10);
if (debug & DEBUG_HW)
pr_notice("%s: IRQ %d count %d\n", hw->name,
hw->irq, hw->irqcnt);
if (!hw->irqcnt) {
pr_info("%s: IRQ(%d) got no requests during init %d\n",
hw->name, hw->irq, 3 - cnt);
} else
return 0;
}
free_irq(hw->irq, hw);
return -EIO;
}
static void
release_io(struct inf_hw *hw)
{
if (hw->cfg.mode) {
if (hw->cfg.p) {
release_mem_region(hw->cfg.start, hw->cfg.size);
iounmap(hw->cfg.p);
} else
release_region(hw->cfg.start, hw->cfg.size);
hw->cfg.mode = AM_NONE;
}
if (hw->addr.mode) {
if (hw->addr.p) {
release_mem_region(hw->addr.start, hw->addr.size);
iounmap(hw->addr.p);
} else
release_region(hw->addr.start, hw->addr.size);
hw->addr.mode = AM_NONE;
}
}
static int __devinit
setup_io(struct inf_hw *hw)
{
int err = 0;
if (hw->ci->cfg_mode) {
hw->cfg.start = pci_resource_start(hw->pdev, hw->ci->cfg_bar);
hw->cfg.size = pci_resource_len(hw->pdev, hw->ci->cfg_bar);
if (hw->ci->cfg_mode == AM_MEMIO) {
if (!request_mem_region(hw->cfg.start, hw->cfg.size,
hw->name))
err = -EBUSY;
} else {
if (!request_region(hw->cfg.start, hw->cfg.size,
hw->name))
err = -EBUSY;
}
if (err) {
pr_info("mISDN: %s config port %lx (%lu bytes)"
"already in use\n", hw->name,
(ulong)hw->cfg.start, (ulong)hw->cfg.size);
return err;
}
if (hw->ci->cfg_mode == AM_MEMIO)
hw->cfg.p = ioremap(hw->cfg.start, hw->cfg.size);
hw->cfg.mode = hw->ci->cfg_mode;
if (debug & DEBUG_HW)
pr_notice("%s: IO cfg %lx (%lu bytes) mode%d\n",
hw->name, (ulong)hw->cfg.start,
(ulong)hw->cfg.size, hw->ci->cfg_mode);
}
if (hw->ci->addr_mode) {
hw->addr.start = pci_resource_start(hw->pdev, hw->ci->addr_bar);
hw->addr.size = pci_resource_len(hw->pdev, hw->ci->addr_bar);
if (hw->ci->addr_mode == AM_MEMIO) {
if (!request_mem_region(hw->addr.start, hw->addr.size,
hw->name))
err = -EBUSY;
} else {
if (!request_region(hw->addr.start, hw->addr.size,
hw->name))
err = -EBUSY;
}
if (err) {
pr_info("mISDN: %s address port %lx (%lu bytes)"
"already in use\n", hw->name,
(ulong)hw->addr.start, (ulong)hw->addr.size);
return err;
}
if (hw->ci->addr_mode == AM_MEMIO)
hw->addr.p = ioremap(hw->addr.start, hw->addr.size);
hw->addr.mode = hw->ci->addr_mode;
if (debug & DEBUG_HW)
pr_notice("%s: IO addr %lx (%lu bytes) mode%d\n",
hw->name, (ulong)hw->addr.start,
(ulong)hw->addr.size, hw->ci->addr_mode);
}
switch (hw->ci->typ) {
case INF_DIVA20:
case INF_DIVA20U:
hw->ipac.type = IPAC_TYPE_ISAC | IPAC_TYPE_HSCX;
hw->isac.mode = hw->cfg.mode;
hw->isac.a.io.ale = (u32)hw->cfg.start + DIVA_ISAC_ALE;
hw->isac.a.io.port = (u32)hw->cfg.start + DIVA_ISAC_PORT;
hw->hscx.mode = hw->cfg.mode;
hw->hscx.a.io.ale = (u32)hw->cfg.start + DIVA_HSCX_ALE;
hw->hscx.a.io.port = (u32)hw->cfg.start + DIVA_HSCX_PORT;
break;
case INF_DIVA201:
hw->ipac.type = IPAC_TYPE_IPAC;
hw->ipac.isac.off = 0x80;
hw->isac.mode = hw->addr.mode;
hw->isac.a.p = hw->addr.p;
hw->hscx.mode = hw->addr.mode;
hw->hscx.a.p = hw->addr.p;
break;
case INF_DIVA202:
hw->ipac.type = IPAC_TYPE_IPACX;
hw->isac.mode = hw->addr.mode;
hw->isac.a.p = hw->addr.p;
hw->hscx.mode = hw->addr.mode;
hw->hscx.a.p = hw->addr.p;
break;
case INF_SPEEDWIN:
case INF_SAPHIR3:
hw->ipac.type = IPAC_TYPE_IPAC;
hw->ipac.isac.off = 0x80;
hw->isac.mode = hw->cfg.mode;
hw->isac.a.io.ale = (u32)hw->cfg.start + TIGER_IPAC_ALE;
hw->isac.a.io.port = (u32)hw->cfg.start + TIGER_IPAC_PORT;
hw->hscx.mode = hw->cfg.mode;
hw->hscx.a.io.ale = (u32)hw->cfg.start + TIGER_IPAC_ALE;
hw->hscx.a.io.port = (u32)hw->cfg.start + TIGER_IPAC_PORT;
outb(0xff, (ulong)hw->cfg.start);
mdelay(1);
outb(0x00, (ulong)hw->cfg.start);
mdelay(1);
outb(TIGER_IOMASK, (ulong)hw->cfg.start + TIGER_AUX_CTRL);
break;
case INF_QS1000:
case INF_QS3000:
hw->ipac.type = IPAC_TYPE_IPAC;
hw->ipac.isac.off = 0x80;
hw->isac.a.io.ale = (u32)hw->addr.start;
hw->isac.a.io.port = (u32)hw->addr.start + 1;
hw->isac.mode = hw->addr.mode;
hw->hscx.a.io.ale = (u32)hw->addr.start;
hw->hscx.a.io.port = (u32)hw->addr.start + 1;
hw->hscx.mode = hw->addr.mode;
break;
case INF_NICCY:
hw->ipac.type = IPAC_TYPE_ISAC | IPAC_TYPE_HSCX;
hw->isac.mode = hw->addr.mode;
hw->isac.a.io.ale = (u32)hw->addr.start + NICCY_ISAC_ALE;
hw->isac.a.io.port = (u32)hw->addr.start + NICCY_ISAC_PORT;
hw->hscx.mode = hw->addr.mode;
hw->hscx.a.io.ale = (u32)hw->addr.start + NICCY_HSCX_ALE;
hw->hscx.a.io.port = (u32)hw->addr.start + NICCY_HSCX_PORT;
break;
case INF_SCT_1:
hw->ipac.type = IPAC_TYPE_IPAC;
hw->ipac.isac.off = 0x80;
hw->isac.a.io.ale = (u32)hw->addr.start;
hw->isac.a.io.port = hw->isac.a.io.ale + 4;
hw->isac.mode = hw->addr.mode;
hw->hscx.a.io.ale = hw->isac.a.io.ale;
hw->hscx.a.io.port = hw->isac.a.io.port;
hw->hscx.mode = hw->addr.mode;
break;
case INF_SCT_2:
hw->ipac.type = IPAC_TYPE_IPAC;
hw->ipac.isac.off = 0x80;
hw->isac.a.io.ale = (u32)hw->addr.start + 0x08;
hw->isac.a.io.port = hw->isac.a.io.ale + 4;
hw->isac.mode = hw->addr.mode;
hw->hscx.a.io.ale = hw->isac.a.io.ale;
hw->hscx.a.io.port = hw->isac.a.io.port;
hw->hscx.mode = hw->addr.mode;
break;
case INF_SCT_3:
hw->ipac.type = IPAC_TYPE_IPAC;
hw->ipac.isac.off = 0x80;
hw->isac.a.io.ale = (u32)hw->addr.start + 0x10;
hw->isac.a.io.port = hw->isac.a.io.ale + 4;
hw->isac.mode = hw->addr.mode;
hw->hscx.a.io.ale = hw->isac.a.io.ale;
hw->hscx.a.io.port = hw->isac.a.io.port;
hw->hscx.mode = hw->addr.mode;
break;
case INF_SCT_4:
hw->ipac.type = IPAC_TYPE_IPAC;
hw->ipac.isac.off = 0x80;
hw->isac.a.io.ale = (u32)hw->addr.start + 0x20;
hw->isac.a.io.port = hw->isac.a.io.ale + 4;
hw->isac.mode = hw->addr.mode;
hw->hscx.a.io.ale = hw->isac.a.io.ale;
hw->hscx.a.io.port = hw->isac.a.io.port;
hw->hscx.mode = hw->addr.mode;
break;
case INF_GAZEL_R685:
hw->ipac.type = IPAC_TYPE_ISAC | IPAC_TYPE_HSCX;
hw->ipac.isac.off = 0x80;
hw->isac.mode = hw->addr.mode;
hw->isac.a.io.port = (u32)hw->addr.start;
hw->hscx.mode = hw->addr.mode;
hw->hscx.a.io.port = hw->isac.a.io.port;
break;
case INF_GAZEL_R753:
hw->ipac.type = IPAC_TYPE_IPAC;
hw->ipac.isac.off = 0x80;
hw->isac.mode = hw->addr.mode;
hw->isac.a.io.ale = (u32)hw->addr.start;
hw->isac.a.io.port = (u32)hw->addr.start + GAZEL_IPAC_DATA_PORT;
hw->hscx.mode = hw->addr.mode;
hw->hscx.a.io.ale = hw->isac.a.io.ale;
hw->hscx.a.io.port = hw->isac.a.io.port;
break;
default:
return -EINVAL;
}
switch (hw->isac.mode) {
case AM_MEMIO:
ASSIGN_FUNC_IPAC(MIO, hw->ipac);
break;
case AM_IND_IO:
ASSIGN_FUNC_IPAC(IND, hw->ipac);
break;
case AM_IO:
ASSIGN_FUNC_IPAC(IO, hw->ipac);
break;
default:
return -EINVAL;
}
return 0;
}
static void
release_card(struct inf_hw *card) {
ulong flags;
int i;
spin_lock_irqsave(&card->lock, flags);
disable_hwirq(card);
spin_unlock_irqrestore(&card->lock, flags);
card->ipac.isac.release(&card->ipac.isac);
free_irq(card->irq, card);
mISDN_unregister_device(&card->ipac.isac.dch.dev);
release_io(card);
write_lock_irqsave(&card_lock, flags);
list_del(&card->list);
write_unlock_irqrestore(&card_lock, flags);
switch (card->ci->typ) {
case INF_SCT_2:
case INF_SCT_3:
case INF_SCT_4:
break;
case INF_SCT_1:
for (i = 0; i < 3; i++) {
if (card->sc[i])
release_card(card->sc[i]);
card->sc[i] = NULL;
}
default:
pci_disable_device(card->pdev);
pci_set_drvdata(card->pdev, NULL);
break;
}
kfree(card);
inf_cnt--;
}
static int __devinit
setup_instance(struct inf_hw *card)
{
int err;
ulong flags;
snprintf(card->name, MISDN_MAX_IDLEN - 1, "%s.%d", card->ci->name,
inf_cnt + 1);
write_lock_irqsave(&card_lock, flags);
list_add_tail(&card->list, &Cards);
write_unlock_irqrestore(&card_lock, flags);
_set_debug(card);
card->ipac.isac.name = card->name;
card->ipac.name = card->name;
card->ipac.owner = THIS_MODULE;
spin_lock_init(&card->lock);
card->ipac.isac.hwlock = &card->lock;
card->ipac.hwlock = &card->lock;
card->ipac.ctrl = (void *)&inf_ctrl;
err = setup_io(card);
if (err)
goto error_setup;
card->ipac.isac.dch.dev.Bprotocols =
mISDNipac_init(&card->ipac, card);
if (card->ipac.isac.dch.dev.Bprotocols == 0)
goto error_setup;
err = mISDN_register_device(&card->ipac.isac.dch.dev,
&card->pdev->dev, card->name);
if (err)
goto error;
err = init_irq(card);
if (!err) {
inf_cnt++;
pr_notice("Infineon %d cards installed\n", inf_cnt);
return 0;
}
mISDN_unregister_device(&card->ipac.isac.dch.dev);
error:
card->ipac.release(&card->ipac);
error_setup:
release_io(card);
write_lock_irqsave(&card_lock, flags);
list_del(&card->list);
write_unlock_irqrestore(&card_lock, flags);
return err;
}
static const struct inf_cinfo inf_card_info[] = {
{
INF_DIVA20,
"Dialogic Diva 2.0",
"diva20",
AM_IND_IO, AM_NONE, 2, 0,
&diva_irq
},
{
INF_DIVA20U,
"Dialogic Diva 2.0U",
"diva20U",
AM_IND_IO, AM_NONE, 2, 0,
&diva_irq
},
{
INF_DIVA201,
"Dialogic Diva 2.01",
"diva201",
AM_MEMIO, AM_MEMIO, 0, 1,
&diva20x_irq
},
{
INF_DIVA202,
"Dialogic Diva 2.02",
"diva202",
AM_MEMIO, AM_MEMIO, 0, 1,
&diva20x_irq
},
{
INF_SPEEDWIN,
"Sedlbauer SpeedWin PCI",
"speedwin",
AM_IND_IO, AM_NONE, 0, 0,
&tiger_irq
},
{
INF_SAPHIR3,
"HST Saphir 3",
"saphir",
AM_IND_IO, AM_NONE, 0, 0,
&tiger_irq
},
{
INF_QS1000,
"Develo Microlink PCI",
"qs1000",
AM_IO, AM_IND_IO, 1, 3,
&elsa_irq
},
{
INF_QS3000,
"Develo QuickStep 3000",
"qs3000",
AM_IO, AM_IND_IO, 1, 3,
&elsa_irq
},
{
INF_NICCY,
"Sagem NICCY",
"niccy",
AM_IO, AM_IND_IO, 0, 1,
&niccy_irq
},
{
INF_SCT_1,
"SciTel Quadro",
"p1_scitel",
AM_IO, AM_IND_IO, 1, 5,
&ipac_irq
},
{
INF_SCT_2,
"SciTel Quadro",
"p2_scitel",
AM_NONE, AM_IND_IO, 0, 4,
&ipac_irq
},
{
INF_SCT_3,
"SciTel Quadro",
"p3_scitel",
AM_NONE, AM_IND_IO, 0, 3,
&ipac_irq
},
{
INF_SCT_4,
"SciTel Quadro",
"p4_scitel",
AM_NONE, AM_IND_IO, 0, 2,
&ipac_irq
},
{
INF_GAZEL_R685,
"Gazel R685",
"gazel685",
AM_IO, AM_IO, 1, 2,
&gazel_irq
},
{
INF_GAZEL_R753,
"Gazel R753",
"gazel753",
AM_IO, AM_IND_IO, 1, 2,
&ipac_irq
},
{
INF_NONE,
}
};
static const struct inf_cinfo * __devinit
get_card_info(enum inf_types typ)
{
const struct inf_cinfo *ci = inf_card_info;
while (ci->typ != INF_NONE) {
if (ci->typ == typ)
return ci;
ci++;
}
return NULL;
}
static int __devinit
inf_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int err = -ENOMEM;
struct inf_hw *card;
card = kzalloc(sizeof(struct inf_hw), GFP_KERNEL);
if (!card) {
pr_info("No memory for Infineon ISDN card\n");
return err;
}
card->pdev = pdev;
err = pci_enable_device(pdev);
if (err) {
kfree(card);
return err;
}
card->ci = get_card_info(ent->driver_data);
if (!card->ci) {
pr_info("mISDN: do not have informations about adapter at %s\n",
pci_name(pdev));
kfree(card);
pci_disable_device(pdev);
return -EINVAL;
} else
pr_notice("mISDN: found adapter %s at %s\n",
card->ci->full, pci_name(pdev));
card->irq = pdev->irq;
pci_set_drvdata(pdev, card);
err = setup_instance(card);
if (err) {
pci_disable_device(pdev);
kfree(card);
pci_set_drvdata(pdev, NULL);
} else if (ent->driver_data == INF_SCT_1) {
int i;
struct inf_hw *sc;
for (i = 1; i < 4; i++) {
sc = kzalloc(sizeof(struct inf_hw), GFP_KERNEL);
if (!sc) {
release_card(card);
pci_disable_device(pdev);
return -ENOMEM;
}
sc->irq = card->irq;
sc->pdev = card->pdev;
sc->ci = card->ci + i;
err = setup_instance(sc);
if (err) {
pci_disable_device(pdev);
kfree(sc);
release_card(card);
break;
} else
card->sc[i - 1] = sc;
}
}
return err;
}
static void __devexit
inf_remove(struct pci_dev *pdev)
{
struct inf_hw *card = pci_get_drvdata(pdev);
if (card)
release_card(card);
else
pr_debug("%s: drvdata already removed\n", __func__);
}
static struct pci_driver infineon_driver = {
.name = "ISDN Infineon pci",
.probe = inf_probe,
.remove = __devexit_p(inf_remove),
.id_table = infineon_ids,
};
static int __init
infineon_init(void)
{
int err;
pr_notice("Infineon ISDN Driver Rev. %s\n", INFINEON_REV);
err = pci_register_driver(&infineon_driver);
return err;
}
static void __exit
infineon_cleanup(void)
{
pci_unregister_driver(&infineon_driver);
}
module_init(infineon_init);
module_exit(infineon_cleanup);
| gpl-2.0 |
AICP/kernel_htc_msm8960-old | sound/arm/aaci.c | 4990 | 25625 | /*
* linux/sound/arm/aaci.c - ARM PrimeCell AACI PL041 driver
*
* Copyright (C) 2003 Deep Blue Solutions Ltd, 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.
*
* Documentation: ARM DDI 0173B
*/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/err.h>
#include <linux/amba/bus.h>
#include <linux/io.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/ac97_codec.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "aaci.h"
#define DRIVER_NAME "aaci-pl041"
#define FRAME_PERIOD_US 21
/*
* PM support is not complete. Turn it off.
*/
#undef CONFIG_PM
static void aaci_ac97_select_codec(struct aaci *aaci, struct snd_ac97 *ac97)
{
u32 v, maincr = aaci->maincr | MAINCR_SCRA(ac97->num);
/*
* Ensure that the slot 1/2 RX registers are empty.
*/
v = readl(aaci->base + AACI_SLFR);
if (v & SLFR_2RXV)
readl(aaci->base + AACI_SL2RX);
if (v & SLFR_1RXV)
readl(aaci->base + AACI_SL1RX);
if (maincr != readl(aaci->base + AACI_MAINCR)) {
writel(maincr, aaci->base + AACI_MAINCR);
readl(aaci->base + AACI_MAINCR);
udelay(1);
}
}
/*
* P29:
* The recommended use of programming the external codec through slot 1
* and slot 2 data is to use the channels during setup routines and the
* slot register at any other time. The data written into slot 1, slot 2
* and slot 12 registers is transmitted only when their corresponding
* SI1TxEn, SI2TxEn and SI12TxEn bits are set in the AACI_MAINCR
* register.
*/
static void aaci_ac97_write(struct snd_ac97 *ac97, unsigned short reg,
unsigned short val)
{
struct aaci *aaci = ac97->private_data;
int timeout;
u32 v;
if (ac97->num >= 4)
return;
mutex_lock(&aaci->ac97_sem);
aaci_ac97_select_codec(aaci, ac97);
/*
* P54: You must ensure that AACI_SL2TX is always written
* to, if required, before data is written to AACI_SL1TX.
*/
writel(val << 4, aaci->base + AACI_SL2TX);
writel(reg << 12, aaci->base + AACI_SL1TX);
/* Initially, wait one frame period */
udelay(FRAME_PERIOD_US);
/* And then wait an additional eight frame periods for it to be sent */
timeout = FRAME_PERIOD_US * 8;
do {
udelay(1);
v = readl(aaci->base + AACI_SLFR);
} while ((v & (SLFR_1TXB|SLFR_2TXB)) && --timeout);
if (v & (SLFR_1TXB|SLFR_2TXB))
dev_err(&aaci->dev->dev,
"timeout waiting for write to complete\n");
mutex_unlock(&aaci->ac97_sem);
}
/*
* Read an AC'97 register.
*/
static unsigned short aaci_ac97_read(struct snd_ac97 *ac97, unsigned short reg)
{
struct aaci *aaci = ac97->private_data;
int timeout, retries = 10;
u32 v;
if (ac97->num >= 4)
return ~0;
mutex_lock(&aaci->ac97_sem);
aaci_ac97_select_codec(aaci, ac97);
/*
* Write the register address to slot 1.
*/
writel((reg << 12) | (1 << 19), aaci->base + AACI_SL1TX);
/* Initially, wait one frame period */
udelay(FRAME_PERIOD_US);
/* And then wait an additional eight frame periods for it to be sent */
timeout = FRAME_PERIOD_US * 8;
do {
udelay(1);
v = readl(aaci->base + AACI_SLFR);
} while ((v & SLFR_1TXB) && --timeout);
if (v & SLFR_1TXB) {
dev_err(&aaci->dev->dev, "timeout on slot 1 TX busy\n");
v = ~0;
goto out;
}
/* Now wait for the response frame */
udelay(FRAME_PERIOD_US);
/* And then wait an additional eight frame periods for data */
timeout = FRAME_PERIOD_US * 8;
do {
udelay(1);
cond_resched();
v = readl(aaci->base + AACI_SLFR) & (SLFR_1RXV|SLFR_2RXV);
} while ((v != (SLFR_1RXV|SLFR_2RXV)) && --timeout);
if (v != (SLFR_1RXV|SLFR_2RXV)) {
dev_err(&aaci->dev->dev, "timeout on RX valid\n");
v = ~0;
goto out;
}
do {
v = readl(aaci->base + AACI_SL1RX) >> 12;
if (v == reg) {
v = readl(aaci->base + AACI_SL2RX) >> 4;
break;
} else if (--retries) {
dev_warn(&aaci->dev->dev,
"ac97 read back fail. retry\n");
continue;
} else {
dev_warn(&aaci->dev->dev,
"wrong ac97 register read back (%x != %x)\n",
v, reg);
v = ~0;
}
} while (retries);
out:
mutex_unlock(&aaci->ac97_sem);
return v;
}
static inline void
aaci_chan_wait_ready(struct aaci_runtime *aacirun, unsigned long mask)
{
u32 val;
int timeout = 5000;
do {
udelay(1);
val = readl(aacirun->base + AACI_SR);
} while (val & mask && timeout--);
}
/*
* Interrupt support.
*/
static void aaci_fifo_irq(struct aaci *aaci, int channel, u32 mask)
{
if (mask & ISR_ORINTR) {
dev_warn(&aaci->dev->dev, "RX overrun on chan %d\n", channel);
writel(ICLR_RXOEC1 << channel, aaci->base + AACI_INTCLR);
}
if (mask & ISR_RXTOINTR) {
dev_warn(&aaci->dev->dev, "RX timeout on chan %d\n", channel);
writel(ICLR_RXTOFEC1 << channel, aaci->base + AACI_INTCLR);
}
if (mask & ISR_RXINTR) {
struct aaci_runtime *aacirun = &aaci->capture;
bool period_elapsed = false;
void *ptr;
if (!aacirun->substream || !aacirun->start) {
dev_warn(&aaci->dev->dev, "RX interrupt???\n");
writel(0, aacirun->base + AACI_IE);
return;
}
spin_lock(&aacirun->lock);
ptr = aacirun->ptr;
do {
unsigned int len = aacirun->fifo_bytes;
u32 val;
if (aacirun->bytes <= 0) {
aacirun->bytes += aacirun->period;
period_elapsed = true;
}
if (!(aacirun->cr & CR_EN))
break;
val = readl(aacirun->base + AACI_SR);
if (!(val & SR_RXHF))
break;
if (!(val & SR_RXFF))
len >>= 1;
aacirun->bytes -= len;
/* reading 16 bytes at a time */
for( ; len > 0; len -= 16) {
asm(
"ldmia %1, {r0, r1, r2, r3}\n\t"
"stmia %0!, {r0, r1, r2, r3}"
: "+r" (ptr)
: "r" (aacirun->fifo)
: "r0", "r1", "r2", "r3", "cc");
if (ptr >= aacirun->end)
ptr = aacirun->start;
}
} while(1);
aacirun->ptr = ptr;
spin_unlock(&aacirun->lock);
if (period_elapsed)
snd_pcm_period_elapsed(aacirun->substream);
}
if (mask & ISR_URINTR) {
dev_dbg(&aaci->dev->dev, "TX underrun on chan %d\n", channel);
writel(ICLR_TXUEC1 << channel, aaci->base + AACI_INTCLR);
}
if (mask & ISR_TXINTR) {
struct aaci_runtime *aacirun = &aaci->playback;
bool period_elapsed = false;
void *ptr;
if (!aacirun->substream || !aacirun->start) {
dev_warn(&aaci->dev->dev, "TX interrupt???\n");
writel(0, aacirun->base + AACI_IE);
return;
}
spin_lock(&aacirun->lock);
ptr = aacirun->ptr;
do {
unsigned int len = aacirun->fifo_bytes;
u32 val;
if (aacirun->bytes <= 0) {
aacirun->bytes += aacirun->period;
period_elapsed = true;
}
if (!(aacirun->cr & CR_EN))
break;
val = readl(aacirun->base + AACI_SR);
if (!(val & SR_TXHE))
break;
if (!(val & SR_TXFE))
len >>= 1;
aacirun->bytes -= len;
/* writing 16 bytes at a time */
for ( ; len > 0; len -= 16) {
asm(
"ldmia %0!, {r0, r1, r2, r3}\n\t"
"stmia %1, {r0, r1, r2, r3}"
: "+r" (ptr)
: "r" (aacirun->fifo)
: "r0", "r1", "r2", "r3", "cc");
if (ptr >= aacirun->end)
ptr = aacirun->start;
}
} while (1);
aacirun->ptr = ptr;
spin_unlock(&aacirun->lock);
if (period_elapsed)
snd_pcm_period_elapsed(aacirun->substream);
}
}
static irqreturn_t aaci_irq(int irq, void *devid)
{
struct aaci *aaci = devid;
u32 mask;
int i;
mask = readl(aaci->base + AACI_ALLINTS);
if (mask) {
u32 m = mask;
for (i = 0; i < 4; i++, m >>= 7) {
if (m & 0x7f) {
aaci_fifo_irq(aaci, i, m);
}
}
}
return mask ? IRQ_HANDLED : IRQ_NONE;
}
/*
* ALSA support.
*/
static struct snd_pcm_hardware aaci_hw_info = {
.info = SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_RESUME,
/*
* ALSA doesn't support 18-bit or 20-bit packed into 32-bit
* words. It also doesn't support 12-bit at all.
*/
.formats = SNDRV_PCM_FMTBIT_S16_LE,
/* rates are setup from the AC'97 codec */
.channels_min = 2,
.channels_max = 2,
.buffer_bytes_max = 64 * 1024,
.period_bytes_min = 256,
.period_bytes_max = PAGE_SIZE,
.periods_min = 4,
.periods_max = PAGE_SIZE / 16,
};
/*
* We can support two and four channel audio. Unfortunately
* six channel audio requires a non-standard channel ordering:
* 2 -> FL(3), FR(4)
* 4 -> FL(3), FR(4), SL(7), SR(8)
* 6 -> FL(3), FR(4), SL(7), SR(8), C(6), LFE(9) (required)
* FL(3), FR(4), C(6), SL(7), SR(8), LFE(9) (actual)
* This requires an ALSA configuration file to correct.
*/
static int aaci_rule_channels(struct snd_pcm_hw_params *p,
struct snd_pcm_hw_rule *rule)
{
static unsigned int channel_list[] = { 2, 4, 6 };
struct aaci *aaci = rule->private;
unsigned int mask = 1 << 0, slots;
/* pcms[0] is the our 5.1 PCM instance. */
slots = aaci->ac97_bus->pcms[0].r[0].slots;
if (slots & (1 << AC97_SLOT_PCM_SLEFT)) {
mask |= 1 << 1;
if (slots & (1 << AC97_SLOT_LFE))
mask |= 1 << 2;
}
return snd_interval_list(hw_param_interval(p, rule->var),
ARRAY_SIZE(channel_list), channel_list, mask);
}
static int aaci_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci *aaci = substream->private_data;
struct aaci_runtime *aacirun;
int ret = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
aacirun = &aaci->playback;
} else {
aacirun = &aaci->capture;
}
aacirun->substream = substream;
runtime->private_data = aacirun;
runtime->hw = aaci_hw_info;
runtime->hw.rates = aacirun->pcm->rates;
snd_pcm_limit_hw_rates(runtime);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
runtime->hw.channels_max = 6;
/* Add rule describing channel dependency. */
ret = snd_pcm_hw_rule_add(substream->runtime, 0,
SNDRV_PCM_HW_PARAM_CHANNELS,
aaci_rule_channels, aaci,
SNDRV_PCM_HW_PARAM_CHANNELS, -1);
if (ret)
return ret;
if (aacirun->pcm->r[1].slots)
snd_ac97_pcm_double_rate_rules(runtime);
}
/*
* ALSA wants the byte-size of the FIFOs. As we only support
* 16-bit samples, this is twice the FIFO depth irrespective
* of whether it's in compact mode or not.
*/
runtime->hw.fifo_size = aaci->fifo_depth * 2;
mutex_lock(&aaci->irq_lock);
if (!aaci->users++) {
ret = request_irq(aaci->dev->irq[0], aaci_irq,
IRQF_SHARED, DRIVER_NAME, aaci);
if (ret != 0)
aaci->users--;
}
mutex_unlock(&aaci->irq_lock);
return ret;
}
/*
* Common ALSA stuff
*/
static int aaci_pcm_close(struct snd_pcm_substream *substream)
{
struct aaci *aaci = substream->private_data;
struct aaci_runtime *aacirun = substream->runtime->private_data;
WARN_ON(aacirun->cr & CR_EN);
aacirun->substream = NULL;
mutex_lock(&aaci->irq_lock);
if (!--aaci->users)
free_irq(aaci->dev->irq[0], aaci);
mutex_unlock(&aaci->irq_lock);
return 0;
}
static int aaci_pcm_hw_free(struct snd_pcm_substream *substream)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
/*
* This must not be called with the device enabled.
*/
WARN_ON(aacirun->cr & CR_EN);
if (aacirun->pcm_open)
snd_ac97_pcm_close(aacirun->pcm);
aacirun->pcm_open = 0;
/*
* Clear out the DMA and any allocated buffers.
*/
snd_pcm_lib_free_pages(substream);
return 0;
}
/* Channel to slot mask */
static const u32 channels_to_slotmask[] = {
[2] = CR_SL3 | CR_SL4,
[4] = CR_SL3 | CR_SL4 | CR_SL7 | CR_SL8,
[6] = CR_SL3 | CR_SL4 | CR_SL7 | CR_SL8 | CR_SL6 | CR_SL9,
};
static int aaci_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
unsigned int channels = params_channels(params);
unsigned int rate = params_rate(params);
int dbl = rate > 48000;
int err;
aaci_pcm_hw_free(substream);
if (aacirun->pcm_open) {
snd_ac97_pcm_close(aacirun->pcm);
aacirun->pcm_open = 0;
}
/* channels is already limited to 2, 4, or 6 by aaci_rule_channels */
if (dbl && channels != 2)
return -EINVAL;
err = snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(params));
if (err >= 0) {
struct aaci *aaci = substream->private_data;
err = snd_ac97_pcm_open(aacirun->pcm, rate, channels,
aacirun->pcm->r[dbl].slots);
aacirun->pcm_open = err == 0;
aacirun->cr = CR_FEN | CR_COMPACT | CR_SZ16;
aacirun->cr |= channels_to_slotmask[channels + dbl * 2];
/*
* fifo_bytes is the number of bytes we transfer to/from
* the FIFO, including padding. So that's x4. As we're
* in compact mode, the FIFO is half the size.
*/
aacirun->fifo_bytes = aaci->fifo_depth * 4 / 2;
}
return err;
}
static int aaci_pcm_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci_runtime *aacirun = runtime->private_data;
aacirun->period = snd_pcm_lib_period_bytes(substream);
aacirun->start = runtime->dma_area;
aacirun->end = aacirun->start + snd_pcm_lib_buffer_bytes(substream);
aacirun->ptr = aacirun->start;
aacirun->bytes = aacirun->period;
return 0;
}
static snd_pcm_uframes_t aaci_pcm_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci_runtime *aacirun = runtime->private_data;
ssize_t bytes = aacirun->ptr - aacirun->start;
return bytes_to_frames(runtime, bytes);
}
/*
* Playback specific ALSA stuff
*/
static void aaci_pcm_playback_stop(struct aaci_runtime *aacirun)
{
u32 ie;
ie = readl(aacirun->base + AACI_IE);
ie &= ~(IE_URIE|IE_TXIE);
writel(ie, aacirun->base + AACI_IE);
aacirun->cr &= ~CR_EN;
aaci_chan_wait_ready(aacirun, SR_TXB);
writel(aacirun->cr, aacirun->base + AACI_TXCR);
}
static void aaci_pcm_playback_start(struct aaci_runtime *aacirun)
{
u32 ie;
aaci_chan_wait_ready(aacirun, SR_TXB);
aacirun->cr |= CR_EN;
ie = readl(aacirun->base + AACI_IE);
ie |= IE_URIE | IE_TXIE;
writel(ie, aacirun->base + AACI_IE);
writel(aacirun->cr, aacirun->base + AACI_TXCR);
}
static int aaci_pcm_playback_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&aacirun->lock, flags);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
aaci_pcm_playback_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_RESUME:
aaci_pcm_playback_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_STOP:
aaci_pcm_playback_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_SUSPEND:
aaci_pcm_playback_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
break;
default:
ret = -EINVAL;
}
spin_unlock_irqrestore(&aacirun->lock, flags);
return ret;
}
static struct snd_pcm_ops aaci_playback_ops = {
.open = aaci_pcm_open,
.close = aaci_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = aaci_pcm_hw_params,
.hw_free = aaci_pcm_hw_free,
.prepare = aaci_pcm_prepare,
.trigger = aaci_pcm_playback_trigger,
.pointer = aaci_pcm_pointer,
};
static void aaci_pcm_capture_stop(struct aaci_runtime *aacirun)
{
u32 ie;
aaci_chan_wait_ready(aacirun, SR_RXB);
ie = readl(aacirun->base + AACI_IE);
ie &= ~(IE_ORIE | IE_RXIE);
writel(ie, aacirun->base+AACI_IE);
aacirun->cr &= ~CR_EN;
writel(aacirun->cr, aacirun->base + AACI_RXCR);
}
static void aaci_pcm_capture_start(struct aaci_runtime *aacirun)
{
u32 ie;
aaci_chan_wait_ready(aacirun, SR_RXB);
#ifdef DEBUG
/* RX Timeout value: bits 28:17 in RXCR */
aacirun->cr |= 0xf << 17;
#endif
aacirun->cr |= CR_EN;
writel(aacirun->cr, aacirun->base + AACI_RXCR);
ie = readl(aacirun->base + AACI_IE);
ie |= IE_ORIE |IE_RXIE; // overrun and rx interrupt -- half full
writel(ie, aacirun->base + AACI_IE);
}
static int aaci_pcm_capture_trigger(struct snd_pcm_substream *substream, int cmd)
{
struct aaci_runtime *aacirun = substream->runtime->private_data;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&aacirun->lock, flags);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
aaci_pcm_capture_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_RESUME:
aaci_pcm_capture_start(aacirun);
break;
case SNDRV_PCM_TRIGGER_STOP:
aaci_pcm_capture_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_SUSPEND:
aaci_pcm_capture_stop(aacirun);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
break;
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
break;
default:
ret = -EINVAL;
}
spin_unlock_irqrestore(&aacirun->lock, flags);
return ret;
}
static int aaci_pcm_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct aaci *aaci = substream->private_data;
aaci_pcm_prepare(substream);
/* allow changing of sample rate */
aaci_ac97_write(aaci->ac97, AC97_EXTENDED_STATUS, 0x0001); /* VRA */
aaci_ac97_write(aaci->ac97, AC97_PCM_LR_ADC_RATE, runtime->rate);
aaci_ac97_write(aaci->ac97, AC97_PCM_MIC_ADC_RATE, runtime->rate);
/* Record select: Mic: 0, Aux: 3, Line: 4 */
aaci_ac97_write(aaci->ac97, AC97_REC_SEL, 0x0404);
return 0;
}
static struct snd_pcm_ops aaci_capture_ops = {
.open = aaci_pcm_open,
.close = aaci_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = aaci_pcm_hw_params,
.hw_free = aaci_pcm_hw_free,
.prepare = aaci_pcm_capture_prepare,
.trigger = aaci_pcm_capture_trigger,
.pointer = aaci_pcm_pointer,
};
/*
* Power Management.
*/
#ifdef CONFIG_PM
static int aaci_do_suspend(struct snd_card *card, unsigned int state)
{
struct aaci *aaci = card->private_data;
snd_power_change_state(card, SNDRV_CTL_POWER_D3cold);
snd_pcm_suspend_all(aaci->pcm);
return 0;
}
static int aaci_do_resume(struct snd_card *card, unsigned int state)
{
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
static int aaci_suspend(struct amba_device *dev, pm_message_t state)
{
struct snd_card *card = amba_get_drvdata(dev);
return card ? aaci_do_suspend(card) : 0;
}
static int aaci_resume(struct amba_device *dev)
{
struct snd_card *card = amba_get_drvdata(dev);
return card ? aaci_do_resume(card) : 0;
}
#else
#define aaci_do_suspend NULL
#define aaci_do_resume NULL
#define aaci_suspend NULL
#define aaci_resume NULL
#endif
static struct ac97_pcm ac97_defs[] __devinitdata = {
[0] = { /* Front PCM */
.exclusive = 1,
.r = {
[0] = {
.slots = (1 << AC97_SLOT_PCM_LEFT) |
(1 << AC97_SLOT_PCM_RIGHT) |
(1 << AC97_SLOT_PCM_CENTER) |
(1 << AC97_SLOT_PCM_SLEFT) |
(1 << AC97_SLOT_PCM_SRIGHT) |
(1 << AC97_SLOT_LFE),
},
[1] = {
.slots = (1 << AC97_SLOT_PCM_LEFT) |
(1 << AC97_SLOT_PCM_RIGHT) |
(1 << AC97_SLOT_PCM_LEFT_0) |
(1 << AC97_SLOT_PCM_RIGHT_0),
},
},
},
[1] = { /* PCM in */
.stream = 1,
.exclusive = 1,
.r = {
[0] = {
.slots = (1 << AC97_SLOT_PCM_LEFT) |
(1 << AC97_SLOT_PCM_RIGHT),
},
},
},
[2] = { /* Mic in */
.stream = 1,
.exclusive = 1,
.r = {
[0] = {
.slots = (1 << AC97_SLOT_MIC),
},
},
}
};
static struct snd_ac97_bus_ops aaci_bus_ops = {
.write = aaci_ac97_write,
.read = aaci_ac97_read,
};
static int __devinit aaci_probe_ac97(struct aaci *aaci)
{
struct snd_ac97_template ac97_template;
struct snd_ac97_bus *ac97_bus;
struct snd_ac97 *ac97;
int ret;
/*
* Assert AACIRESET for 2us
*/
writel(0, aaci->base + AACI_RESET);
udelay(2);
writel(RESET_NRST, aaci->base + AACI_RESET);
/*
* Give the AC'97 codec more than enough time
* to wake up. (42us = ~2 frames at 48kHz.)
*/
udelay(FRAME_PERIOD_US * 2);
ret = snd_ac97_bus(aaci->card, 0, &aaci_bus_ops, aaci, &ac97_bus);
if (ret)
goto out;
ac97_bus->clock = 48000;
aaci->ac97_bus = ac97_bus;
memset(&ac97_template, 0, sizeof(struct snd_ac97_template));
ac97_template.private_data = aaci;
ac97_template.num = 0;
ac97_template.scaps = AC97_SCAP_SKIP_MODEM;
ret = snd_ac97_mixer(ac97_bus, &ac97_template, &ac97);
if (ret)
goto out;
aaci->ac97 = ac97;
/*
* Disable AC97 PC Beep input on audio codecs.
*/
if (ac97_is_audio(ac97))
snd_ac97_write_cache(ac97, AC97_PC_BEEP, 0x801e);
ret = snd_ac97_pcm_assign(ac97_bus, ARRAY_SIZE(ac97_defs), ac97_defs);
if (ret)
goto out;
aaci->playback.pcm = &ac97_bus->pcms[0];
aaci->capture.pcm = &ac97_bus->pcms[1];
out:
return ret;
}
static void aaci_free_card(struct snd_card *card)
{
struct aaci *aaci = card->private_data;
if (aaci->base)
iounmap(aaci->base);
}
static struct aaci * __devinit aaci_init_card(struct amba_device *dev)
{
struct aaci *aaci;
struct snd_card *card;
int err;
err = snd_card_create(SNDRV_DEFAULT_IDX1, SNDRV_DEFAULT_STR1,
THIS_MODULE, sizeof(struct aaci), &card);
if (err < 0)
return NULL;
card->private_free = aaci_free_card;
strlcpy(card->driver, DRIVER_NAME, sizeof(card->driver));
strlcpy(card->shortname, "ARM AC'97 Interface", sizeof(card->shortname));
snprintf(card->longname, sizeof(card->longname),
"%s PL%03x rev%u at 0x%08llx, irq %d",
card->shortname, amba_part(dev), amba_rev(dev),
(unsigned long long)dev->res.start, dev->irq[0]);
aaci = card->private_data;
mutex_init(&aaci->ac97_sem);
mutex_init(&aaci->irq_lock);
aaci->card = card;
aaci->dev = dev;
/* Set MAINCR to allow slot 1 and 2 data IO */
aaci->maincr = MAINCR_IE | MAINCR_SL1RXEN | MAINCR_SL1TXEN |
MAINCR_SL2RXEN | MAINCR_SL2TXEN;
return aaci;
}
static int __devinit aaci_init_pcm(struct aaci *aaci)
{
struct snd_pcm *pcm;
int ret;
ret = snd_pcm_new(aaci->card, "AACI AC'97", 0, 1, 1, &pcm);
if (ret == 0) {
aaci->pcm = pcm;
pcm->private_data = aaci;
pcm->info_flags = 0;
strlcpy(pcm->name, DRIVER_NAME, sizeof(pcm->name));
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &aaci_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &aaci_capture_ops);
snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
NULL, 0, 64 * 1024);
}
return ret;
}
static unsigned int __devinit aaci_size_fifo(struct aaci *aaci)
{
struct aaci_runtime *aacirun = &aaci->playback;
int i;
/*
* Enable the channel, but don't assign it to any slots, so
* it won't empty onto the AC'97 link.
*/
writel(CR_FEN | CR_SZ16 | CR_EN, aacirun->base + AACI_TXCR);
for (i = 0; !(readl(aacirun->base + AACI_SR) & SR_TXFF) && i < 4096; i++)
writel(0, aacirun->fifo);
writel(0, aacirun->base + AACI_TXCR);
/*
* Re-initialise the AACI after the FIFO depth test, to
* ensure that the FIFOs are empty. Unfortunately, merely
* disabling the channel doesn't clear the FIFO.
*/
writel(aaci->maincr & ~MAINCR_IE, aaci->base + AACI_MAINCR);
readl(aaci->base + AACI_MAINCR);
udelay(1);
writel(aaci->maincr, aaci->base + AACI_MAINCR);
/*
* If we hit 4096 entries, we failed. Go back to the specified
* fifo depth.
*/
if (i == 4096)
i = 8;
return i;
}
static int __devinit aaci_probe(struct amba_device *dev,
const struct amba_id *id)
{
struct aaci *aaci;
int ret, i;
ret = amba_request_regions(dev, NULL);
if (ret)
return ret;
aaci = aaci_init_card(dev);
if (!aaci) {
ret = -ENOMEM;
goto out;
}
aaci->base = ioremap(dev->res.start, resource_size(&dev->res));
if (!aaci->base) {
ret = -ENOMEM;
goto out;
}
/*
* Playback uses AACI channel 0
*/
spin_lock_init(&aaci->playback.lock);
aaci->playback.base = aaci->base + AACI_CSCH1;
aaci->playback.fifo = aaci->base + AACI_DR1;
/*
* Capture uses AACI channel 0
*/
spin_lock_init(&aaci->capture.lock);
aaci->capture.base = aaci->base + AACI_CSCH1;
aaci->capture.fifo = aaci->base + AACI_DR1;
for (i = 0; i < 4; i++) {
void __iomem *base = aaci->base + i * 0x14;
writel(0, base + AACI_IE);
writel(0, base + AACI_TXCR);
writel(0, base + AACI_RXCR);
}
writel(0x1fff, aaci->base + AACI_INTCLR);
writel(aaci->maincr, aaci->base + AACI_MAINCR);
/*
* Fix: ac97 read back fail errors by reading
* from any arbitrary aaci register.
*/
readl(aaci->base + AACI_CSCH1);
ret = aaci_probe_ac97(aaci);
if (ret)
goto out;
/*
* Size the FIFOs (must be multiple of 16).
* This is the number of entries in the FIFO.
*/
aaci->fifo_depth = aaci_size_fifo(aaci);
if (aaci->fifo_depth & 15) {
printk(KERN_WARNING "AACI: FIFO depth %d not supported\n",
aaci->fifo_depth);
ret = -ENODEV;
goto out;
}
ret = aaci_init_pcm(aaci);
if (ret)
goto out;
snd_card_set_dev(aaci->card, &dev->dev);
ret = snd_card_register(aaci->card);
if (ret == 0) {
dev_info(&dev->dev, "%s\n", aaci->card->longname);
dev_info(&dev->dev, "FIFO %u entries\n", aaci->fifo_depth);
amba_set_drvdata(dev, aaci->card);
return ret;
}
out:
if (aaci)
snd_card_free(aaci->card);
amba_release_regions(dev);
return ret;
}
static int __devexit aaci_remove(struct amba_device *dev)
{
struct snd_card *card = amba_get_drvdata(dev);
amba_set_drvdata(dev, NULL);
if (card) {
struct aaci *aaci = card->private_data;
writel(0, aaci->base + AACI_MAINCR);
snd_card_free(card);
amba_release_regions(dev);
}
return 0;
}
static struct amba_id aaci_ids[] = {
{
.id = 0x00041041,
.mask = 0x000fffff,
},
{ 0, 0 },
};
MODULE_DEVICE_TABLE(amba, aaci_ids);
static struct amba_driver aaci_driver = {
.drv = {
.name = DRIVER_NAME,
},
.probe = aaci_probe,
.remove = __devexit_p(aaci_remove),
.suspend = aaci_suspend,
.resume = aaci_resume,
.id_table = aaci_ids,
};
module_amba_driver(aaci_driver);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("ARM PrimeCell PL041 Advanced Audio CODEC Interface driver");
| gpl-2.0 |
VegaDevTeam/android_kernel_pantech_ef60s | drivers/ata/pata_ns87415.c | 5502 | 11360 | /*
* pata_ns87415.c - NS87415 (non PARISC) PATA
*
* (C) 2005 Red Hat <alan@lxorguk.ukuu.org.uk>
*
* This is a fairly generic MWDMA controller. It has some limitations
* as it requires timing reloads on PIO/DMA transitions but it is otherwise
* fairly well designed.
*
* This driver assumes the firmware has left the chip in a valid ST506
* compliant state, either legacy IRQ 14/15 or native INTA shared. You
* may need to add platform code if your system fails to do this.
*
* The same cell appears in the 87560 controller used by some PARISC
* systems. This has its own special mountain of errata.
*
* TODO:
* Test PARISC SuperIO
* Get someone to test on SPARC
* Implement lazy pio/dma switching for better performance
* 8bit shared timing.
* See if we need to kill the FIFO for ATAPI
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#include <linux/ata.h>
#define DRV_NAME "pata_ns87415"
#define DRV_VERSION "0.0.1"
/**
* ns87415_set_mode - Initialize host controller mode timings
* @ap: Port whose timings we are configuring
* @adev: Device whose timings we are configuring
* @mode: Mode to set
*
* Program the mode registers for this controller, channel and
* device. Because the chip is quite an old design we have to do this
* for PIO/DMA switches.
*
* LOCKING:
* None (inherited from caller).
*/
static void ns87415_set_mode(struct ata_port *ap, struct ata_device *adev, u8 mode)
{
struct pci_dev *dev = to_pci_dev(ap->host->dev);
int unit = 2 * ap->port_no + adev->devno;
int timing = 0x44 + 2 * unit;
unsigned long T = 1000000000 / 33333; /* PCI clocks */
struct ata_timing t;
u16 clocking;
u8 iordy;
u8 status;
/* Timing register format is 17 - low nybble read timing with
the high nybble being 16 - x for recovery time in PCI clocks */
ata_timing_compute(adev, adev->pio_mode, &t, T, 0);
clocking = 17 - clamp_val(t.active, 2, 17);
clocking |= (16 - clamp_val(t.recover, 1, 16)) << 4;
/* Use the same timing for read and write bytes */
clocking |= (clocking << 8);
pci_write_config_word(dev, timing, clocking);
/* Set the IORDY enable versus DMA enable on or off properly */
pci_read_config_byte(dev, 0x42, &iordy);
iordy &= ~(1 << (4 + unit));
if (mode >= XFER_MW_DMA_0 || !ata_pio_need_iordy(adev))
iordy |= (1 << (4 + unit));
/* Paranoia: We shouldn't ever get here with busy write buffers
but if so wait */
pci_read_config_byte(dev, 0x43, &status);
while (status & 0x03) {
udelay(1);
pci_read_config_byte(dev, 0x43, &status);
}
/* Flip the IORDY/DMA bits now we are sure the write buffers are
clear */
pci_write_config_byte(dev, 0x42, iordy);
/* TODO: Set byte 54 command timing to the best 8bit
mode shared by all four devices */
}
/**
* ns87415_set_piomode - Initialize host controller PATA PIO timings
* @ap: Port whose timings we are configuring
* @adev: Device to program
*
* Set PIO mode for device, in host controller PCI config space.
*
* LOCKING:
* None (inherited from caller).
*/
static void ns87415_set_piomode(struct ata_port *ap, struct ata_device *adev)
{
ns87415_set_mode(ap, adev, adev->pio_mode);
}
/**
* ns87415_bmdma_setup - Set up DMA
* @qc: Command block
*
* Set up for bus masterng DMA. We have to do this ourselves
* rather than use the helper due to a chip erratum
*/
static void ns87415_bmdma_setup(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
u8 dmactl;
/* load PRD table addr. */
mb(); /* make sure PRD table writes are visible to controller */
iowrite32(ap->bmdma_prd_dma, ap->ioaddr.bmdma_addr + ATA_DMA_TABLE_OFS);
/* specify data direction, triple-check start bit is clear */
dmactl = ioread8(ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
/* Due to an erratum we need to write these bits to the wrong
place - which does save us an I/O bizarrely */
dmactl |= ATA_DMA_INTR | ATA_DMA_ERR;
if (!rw)
dmactl |= ATA_DMA_WR;
iowrite8(dmactl, ap->ioaddr.bmdma_addr + ATA_DMA_CMD);
/* issue r/w command */
ap->ops->sff_exec_command(ap, &qc->tf);
}
/**
* ns87415_bmdma_start - Begin DMA transfer
* @qc: Command block
*
* Switch the timings for the chip and set up for a DMA transfer
* before the DMA burst begins.
*
* FIXME: We should do lazy switching on bmdma_start versus
* ata_pio_data_xfer for better performance.
*/
static void ns87415_bmdma_start(struct ata_queued_cmd *qc)
{
ns87415_set_mode(qc->ap, qc->dev, qc->dev->dma_mode);
ata_bmdma_start(qc);
}
/**
* ns87415_bmdma_stop - End DMA transfer
* @qc: Command block
*
* End DMA mode and switch the controller back into PIO mode
*/
static void ns87415_bmdma_stop(struct ata_queued_cmd *qc)
{
ata_bmdma_stop(qc);
ns87415_set_mode(qc->ap, qc->dev, qc->dev->pio_mode);
}
/**
* ns87415_irq_clear - Clear interrupt
* @ap: Channel to clear
*
* Erratum: Due to a chip bug regisers 02 and 0A bit 1 and 2 (the
* error bits) are reset by writing to register 00 or 08.
*/
static void ns87415_irq_clear(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.bmdma_addr;
if (!mmio)
return;
iowrite8((ioread8(mmio + ATA_DMA_CMD) | ATA_DMA_INTR | ATA_DMA_ERR),
mmio + ATA_DMA_CMD);
}
/**
* ns87415_check_atapi_dma - ATAPI DMA filter
* @qc: Command block
*
* Disable ATAPI DMA (for now). We may be able to do DMA if we
* kill the prefetching. This isn't clear.
*/
static int ns87415_check_atapi_dma(struct ata_queued_cmd *qc)
{
return -EOPNOTSUPP;
}
#if defined(CONFIG_SUPERIO)
/* SUPERIO 87560 is a PoS chip that NatSem denies exists.
* Unfortunately, it's built-in on all Astro-based PA-RISC workstations
* which use the integrated NS87514 cell for CD-ROM support.
* i.e we have to support for CD-ROM installs.
* See drivers/parisc/superio.c for more gory details.
*
* Workarounds taken from drivers/ide/pci/ns87415.c
*/
#include <asm/superio.h>
#define SUPERIO_IDE_MAX_RETRIES 25
/**
* ns87560_read_buggy - workaround buggy Super I/O chip
* @port: Port to read
*
* Work around chipset problems in the 87560 SuperIO chip
*/
static u8 ns87560_read_buggy(void __iomem *port)
{
u8 tmp;
int retries = SUPERIO_IDE_MAX_RETRIES;
do {
tmp = ioread8(port);
if (tmp != 0)
return tmp;
udelay(50);
} while(retries-- > 0);
return tmp;
}
/**
* ns87560_check_status
* @ap: channel to check
*
* Return the status of the channel working around the
* 87560 flaws.
*/
static u8 ns87560_check_status(struct ata_port *ap)
{
return ns87560_read_buggy(ap->ioaddr.status_addr);
}
/**
* ns87560_tf_read - input device's ATA taskfile shadow registers
* @ap: Port from which input is read
* @tf: ATA taskfile register set for storing input
*
* Reads ATA taskfile registers for currently-selected device
* into @tf. Work around the 87560 bugs.
*
* LOCKING:
* Inherited from caller.
*/
void ns87560_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
tf->command = ns87560_check_status(ap);
tf->feature = ioread8(ioaddr->error_addr);
tf->nsect = ioread8(ioaddr->nsect_addr);
tf->lbal = ioread8(ioaddr->lbal_addr);
tf->lbam = ioread8(ioaddr->lbam_addr);
tf->lbah = ioread8(ioaddr->lbah_addr);
tf->device = ns87560_read_buggy(ioaddr->device_addr);
if (tf->flags & ATA_TFLAG_LBA48) {
iowrite8(tf->ctl | ATA_HOB, ioaddr->ctl_addr);
tf->hob_feature = ioread8(ioaddr->error_addr);
tf->hob_nsect = ioread8(ioaddr->nsect_addr);
tf->hob_lbal = ioread8(ioaddr->lbal_addr);
tf->hob_lbam = ioread8(ioaddr->lbam_addr);
tf->hob_lbah = ioread8(ioaddr->lbah_addr);
iowrite8(tf->ctl, ioaddr->ctl_addr);
ap->last_ctl = tf->ctl;
}
}
/**
* ns87560_bmdma_status
* @ap: channel to check
*
* Return the DMA status of the channel working around the
* 87560 flaws.
*/
static u8 ns87560_bmdma_status(struct ata_port *ap)
{
return ns87560_read_buggy(ap->ioaddr.bmdma_addr + ATA_DMA_STATUS);
}
#endif /* 87560 SuperIO Support */
static struct ata_port_operations ns87415_pata_ops = {
.inherits = &ata_bmdma_port_ops,
.check_atapi_dma = ns87415_check_atapi_dma,
.bmdma_setup = ns87415_bmdma_setup,
.bmdma_start = ns87415_bmdma_start,
.bmdma_stop = ns87415_bmdma_stop,
.sff_irq_clear = ns87415_irq_clear,
.cable_detect = ata_cable_40wire,
.set_piomode = ns87415_set_piomode,
};
#if defined(CONFIG_SUPERIO)
static struct ata_port_operations ns87560_pata_ops = {
.inherits = &ns87415_pata_ops,
.sff_tf_read = ns87560_tf_read,
.sff_check_status = ns87560_check_status,
.bmdma_status = ns87560_bmdma_status,
};
#endif
static struct scsi_host_template ns87415_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static void ns87415_fixup(struct pci_dev *pdev)
{
/* Select 512 byte sectors */
pci_write_config_byte(pdev, 0x55, 0xEE);
/* Select PIO0 8bit clocking */
pci_write_config_byte(pdev, 0x54, 0xB7);
}
/**
* ns87415_init_one - Register 87415 ATA PCI device with kernel services
* @pdev: PCI device to register
* @ent: Entry in ns87415_pci_tbl matching with @pdev
*
* Called from kernel PCI layer. We probe for combined mode (sigh),
* and then hand over control to libata, for it to do the rest.
*
* LOCKING:
* Inherited from PCI layer (may sleep).
*
* RETURNS:
* Zero on success, or -ERRNO value.
*/
static int ns87415_init_one (struct pci_dev *pdev, const struct pci_device_id *ent)
{
static const struct ata_port_info info = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.port_ops = &ns87415_pata_ops,
};
const struct ata_port_info *ppi[] = { &info, NULL };
int rc;
#if defined(CONFIG_SUPERIO)
static const struct ata_port_info info87560 = {
.flags = ATA_FLAG_SLAVE_POSS,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.port_ops = &ns87560_pata_ops,
};
if (PCI_SLOT(pdev->devfn) == 0x0E)
ppi[0] = &info87560;
#endif
ata_print_version_once(&pdev->dev, DRV_VERSION);
rc = pcim_enable_device(pdev);
if (rc)
return rc;
ns87415_fixup(pdev);
return ata_pci_bmdma_init_one(pdev, ppi, &ns87415_sht, NULL, 0);
}
static const struct pci_device_id ns87415_pci_tbl[] = {
{ PCI_VDEVICE(NS, PCI_DEVICE_ID_NS_87415), },
{ } /* terminate list */
};
#ifdef CONFIG_PM
static int ns87415_reinit_one(struct pci_dev *pdev)
{
struct ata_host *host = dev_get_drvdata(&pdev->dev);
int rc;
rc = ata_pci_device_do_resume(pdev);
if (rc)
return rc;
ns87415_fixup(pdev);
ata_host_resume(host);
return 0;
}
#endif
static struct pci_driver ns87415_pci_driver = {
.name = DRV_NAME,
.id_table = ns87415_pci_tbl,
.probe = ns87415_init_one,
.remove = ata_pci_remove_one,
#ifdef CONFIG_PM
.suspend = ata_pci_device_suspend,
.resume = ns87415_reinit_one,
#endif
};
static int __init ns87415_init(void)
{
return pci_register_driver(&ns87415_pci_driver);
}
static void __exit ns87415_exit(void)
{
pci_unregister_driver(&ns87415_pci_driver);
}
module_init(ns87415_init);
module_exit(ns87415_exit);
MODULE_AUTHOR("Alan Cox");
MODULE_DESCRIPTION("ATA low-level driver for NS87415 controllers");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, ns87415_pci_tbl);
MODULE_VERSION(DRV_VERSION);
| gpl-2.0 |
TeamExodus/kernel_google_msm | drivers/ide/ide-ioctls.c | 7550 | 6861 | /*
* IDE ioctls handling.
*/
#include <linux/export.h>
#include <linux/hdreg.h>
#include <linux/ide.h>
#include <linux/slab.h>
static const struct ide_ioctl_devset ide_ioctl_settings[] = {
{ HDIO_GET_32BIT, HDIO_SET_32BIT, &ide_devset_io_32bit },
{ HDIO_GET_KEEPSETTINGS, HDIO_SET_KEEPSETTINGS, &ide_devset_keepsettings },
{ HDIO_GET_UNMASKINTR, HDIO_SET_UNMASKINTR, &ide_devset_unmaskirq },
{ HDIO_GET_DMA, HDIO_SET_DMA, &ide_devset_using_dma },
{ -1, HDIO_SET_PIO_MODE, &ide_devset_pio_mode },
{ 0 }
};
int ide_setting_ioctl(ide_drive_t *drive, struct block_device *bdev,
unsigned int cmd, unsigned long arg,
const struct ide_ioctl_devset *s)
{
const struct ide_devset *ds;
int err = -EOPNOTSUPP;
for (; (ds = s->setting); s++) {
if (ds->get && s->get_ioctl == cmd)
goto read_val;
else if (ds->set && s->set_ioctl == cmd)
goto set_val;
}
return err;
read_val:
mutex_lock(&ide_setting_mtx);
err = ds->get(drive);
mutex_unlock(&ide_setting_mtx);
return err >= 0 ? put_user(err, (long __user *)arg) : err;
set_val:
if (bdev != bdev->bd_contains)
err = -EINVAL;
else {
if (!capable(CAP_SYS_ADMIN))
err = -EACCES;
else {
mutex_lock(&ide_setting_mtx);
err = ide_devset_execute(drive, ds, arg);
mutex_unlock(&ide_setting_mtx);
}
}
return err;
}
EXPORT_SYMBOL_GPL(ide_setting_ioctl);
static int ide_get_identity_ioctl(ide_drive_t *drive, unsigned int cmd,
unsigned long arg)
{
u16 *id = NULL;
int size = (cmd == HDIO_GET_IDENTITY) ? (ATA_ID_WORDS * 2) : 142;
int rc = 0;
if ((drive->dev_flags & IDE_DFLAG_ID_READ) == 0) {
rc = -ENOMSG;
goto out;
}
/* ata_id_to_hd_driveid() relies on 'id' to be fully allocated. */
id = kmalloc(ATA_ID_WORDS * 2, GFP_KERNEL);
if (id == NULL) {
rc = -ENOMEM;
goto out;
}
memcpy(id, drive->id, size);
ata_id_to_hd_driveid(id);
if (copy_to_user((void __user *)arg, id, size))
rc = -EFAULT;
kfree(id);
out:
return rc;
}
static int ide_get_nice_ioctl(ide_drive_t *drive, unsigned long arg)
{
return put_user((!!(drive->dev_flags & IDE_DFLAG_DSC_OVERLAP)
<< IDE_NICE_DSC_OVERLAP) |
(!!(drive->dev_flags & IDE_DFLAG_NICE1)
<< IDE_NICE_1), (long __user *)arg);
}
static int ide_set_nice_ioctl(ide_drive_t *drive, unsigned long arg)
{
if (arg != (arg & ((1 << IDE_NICE_DSC_OVERLAP) | (1 << IDE_NICE_1))))
return -EPERM;
if (((arg >> IDE_NICE_DSC_OVERLAP) & 1) &&
(drive->media != ide_tape))
return -EPERM;
if ((arg >> IDE_NICE_DSC_OVERLAP) & 1)
drive->dev_flags |= IDE_DFLAG_DSC_OVERLAP;
else
drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
if ((arg >> IDE_NICE_1) & 1)
drive->dev_flags |= IDE_DFLAG_NICE1;
else
drive->dev_flags &= ~IDE_DFLAG_NICE1;
return 0;
}
static int ide_cmd_ioctl(ide_drive_t *drive, unsigned long arg)
{
u8 *buf = NULL;
int bufsize = 0, err = 0;
u8 args[4], xfer_rate = 0;
struct ide_cmd cmd;
struct ide_taskfile *tf = &cmd.tf;
if (NULL == (void *) arg) {
struct request *rq;
rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
rq->cmd_type = REQ_TYPE_ATA_TASKFILE;
err = blk_execute_rq(drive->queue, NULL, rq, 0);
blk_put_request(rq);
return err;
}
if (copy_from_user(args, (void __user *)arg, 4))
return -EFAULT;
memset(&cmd, 0, sizeof(cmd));
tf->feature = args[2];
if (args[0] == ATA_CMD_SMART) {
tf->nsect = args[3];
tf->lbal = args[1];
tf->lbam = 0x4f;
tf->lbah = 0xc2;
cmd.valid.out.tf = IDE_VALID_OUT_TF;
cmd.valid.in.tf = IDE_VALID_NSECT;
} else {
tf->nsect = args[1];
cmd.valid.out.tf = IDE_VALID_FEATURE | IDE_VALID_NSECT;
cmd.valid.in.tf = IDE_VALID_NSECT;
}
tf->command = args[0];
cmd.protocol = args[3] ? ATA_PROT_PIO : ATA_PROT_NODATA;
if (args[3]) {
cmd.tf_flags |= IDE_TFLAG_IO_16BIT;
bufsize = SECTOR_SIZE * args[3];
buf = kzalloc(bufsize, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
}
if (tf->command == ATA_CMD_SET_FEATURES &&
tf->feature == SETFEATURES_XFER &&
tf->nsect >= XFER_SW_DMA_0) {
xfer_rate = ide_find_dma_mode(drive, tf->nsect);
if (xfer_rate != tf->nsect) {
err = -EINVAL;
goto abort;
}
cmd.tf_flags |= IDE_TFLAG_SET_XFER;
}
err = ide_raw_taskfile(drive, &cmd, buf, args[3]);
args[0] = tf->status;
args[1] = tf->error;
args[2] = tf->nsect;
abort:
if (copy_to_user((void __user *)arg, &args, 4))
err = -EFAULT;
if (buf) {
if (copy_to_user((void __user *)(arg + 4), buf, bufsize))
err = -EFAULT;
kfree(buf);
}
return err;
}
static int ide_task_ioctl(ide_drive_t *drive, unsigned long arg)
{
void __user *p = (void __user *)arg;
int err = 0;
u8 args[7];
struct ide_cmd cmd;
if (copy_from_user(args, p, 7))
return -EFAULT;
memset(&cmd, 0, sizeof(cmd));
memcpy(&cmd.tf.feature, &args[1], 6);
cmd.tf.command = args[0];
cmd.valid.out.tf = IDE_VALID_OUT_TF | IDE_VALID_DEVICE;
cmd.valid.in.tf = IDE_VALID_IN_TF | IDE_VALID_DEVICE;
err = ide_no_data_taskfile(drive, &cmd);
args[0] = cmd.tf.command;
memcpy(&args[1], &cmd.tf.feature, 6);
if (copy_to_user(p, args, 7))
err = -EFAULT;
return err;
}
static int generic_drive_reset(ide_drive_t *drive)
{
struct request *rq;
int ret = 0;
rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
rq->cmd_type = REQ_TYPE_SPECIAL;
rq->cmd_len = 1;
rq->cmd[0] = REQ_DRIVE_RESET;
if (blk_execute_rq(drive->queue, NULL, rq, 1))
ret = rq->errors;
blk_put_request(rq);
return ret;
}
int generic_ide_ioctl(ide_drive_t *drive, struct block_device *bdev,
unsigned int cmd, unsigned long arg)
{
int err;
err = ide_setting_ioctl(drive, bdev, cmd, arg, ide_ioctl_settings);
if (err != -EOPNOTSUPP)
return err;
switch (cmd) {
case HDIO_OBSOLETE_IDENTITY:
case HDIO_GET_IDENTITY:
if (bdev != bdev->bd_contains)
return -EINVAL;
return ide_get_identity_ioctl(drive, cmd, arg);
case HDIO_GET_NICE:
return ide_get_nice_ioctl(drive, arg);
case HDIO_SET_NICE:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return ide_set_nice_ioctl(drive, arg);
#ifdef CONFIG_IDE_TASK_IOCTL
case HDIO_DRIVE_TASKFILE:
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
return -EACCES;
if (drive->media == ide_disk)
return ide_taskfile_ioctl(drive, arg);
return -ENOMSG;
#endif
case HDIO_DRIVE_CMD:
if (!capable(CAP_SYS_RAWIO))
return -EACCES;
return ide_cmd_ioctl(drive, arg);
case HDIO_DRIVE_TASK:
if (!capable(CAP_SYS_RAWIO))
return -EACCES;
return ide_task_ioctl(drive, arg);
case HDIO_DRIVE_RESET:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return generic_drive_reset(drive);
case HDIO_GET_BUSSTATE:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (put_user(BUSSTATE_ON, (long __user *)arg))
return -EFAULT;
return 0;
case HDIO_SET_BUSSTATE:
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
return -EOPNOTSUPP;
default:
return -EINVAL;
}
}
EXPORT_SYMBOL(generic_ide_ioctl);
| gpl-2.0 |
master-j/e210s_cam | arch/powerpc/platforms/pseries/scanlog.c | 7806 | 5568 | /*
* c 2001 PPC 64 Team, IBM Corp
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* scan-log-data driver for PPC64 Todd Inglett <tinglett@vnet.ibm.com>
*
* When ppc64 hardware fails the service processor dumps internal state
* of the system. After a reboot the operating system can access a dump
* of this data using this driver. A dump exists if the device-tree
* /chosen/ibm,scan-log-data property exists.
*
* This driver exports /proc/powerpc/scan-log-dump which can be read.
* The driver supports only sequential reads.
*
* The driver looks at a write to the driver for the single word "reset".
* If given, the driver will reset the scanlog so the platform can free it.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <asm/rtas.h>
#include <asm/prom.h>
#define MODULE_VERS "1.0"
#define MODULE_NAME "scanlog"
/* Status returns from ibm,scan-log-dump */
#define SCANLOG_COMPLETE 0
#define SCANLOG_HWERROR -1
#define SCANLOG_CONTINUE 1
static unsigned int ibm_scan_log_dump; /* RTAS token */
static struct proc_dir_entry *proc_ppc64_scan_log_dump; /* The proc file */
static ssize_t scanlog_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct inode * inode = file->f_path.dentry->d_inode;
struct proc_dir_entry *dp;
unsigned int *data;
int status;
unsigned long len, off;
unsigned int wait_time;
dp = PDE(inode);
data = (unsigned int *)dp->data;
if (count > RTAS_DATA_BUF_SIZE)
count = RTAS_DATA_BUF_SIZE;
if (count < 1024) {
/* This is the min supported by this RTAS call. Rather
* than do all the buffering we insist the user code handle
* larger reads. As long as cp works... :)
*/
printk(KERN_ERR "scanlog: cannot perform a small read (%ld)\n", count);
return -EINVAL;
}
if (!access_ok(VERIFY_WRITE, buf, count))
return -EFAULT;
for (;;) {
wait_time = 500; /* default wait if no data */
spin_lock(&rtas_data_buf_lock);
memcpy(rtas_data_buf, data, RTAS_DATA_BUF_SIZE);
status = rtas_call(ibm_scan_log_dump, 2, 1, NULL,
(u32) __pa(rtas_data_buf), (u32) count);
memcpy(data, rtas_data_buf, RTAS_DATA_BUF_SIZE);
spin_unlock(&rtas_data_buf_lock);
pr_debug("scanlog: status=%d, data[0]=%x, data[1]=%x, " \
"data[2]=%x\n", status, data[0], data[1], data[2]);
switch (status) {
case SCANLOG_COMPLETE:
pr_debug("scanlog: hit eof\n");
return 0;
case SCANLOG_HWERROR:
pr_debug("scanlog: hardware error reading data\n");
return -EIO;
case SCANLOG_CONTINUE:
/* We may or may not have data yet */
len = data[1];
off = data[2];
if (len > 0) {
if (copy_to_user(buf, ((char *)data)+off, len))
return -EFAULT;
return len;
}
/* Break to sleep default time */
break;
default:
/* Assume extended busy */
wait_time = rtas_busy_delay_time(status);
if (!wait_time) {
printk(KERN_ERR "scanlog: unknown error " \
"from rtas: %d\n", status);
return -EIO;
}
}
/* Apparently no data yet. Wait and try again. */
msleep_interruptible(wait_time);
}
/*NOTREACHED*/
}
static ssize_t scanlog_write(struct file * file, const char __user * buf,
size_t count, loff_t *ppos)
{
char stkbuf[20];
int status;
if (count > 19) count = 19;
if (copy_from_user (stkbuf, buf, count)) {
return -EFAULT;
}
stkbuf[count] = 0;
if (buf) {
if (strncmp(stkbuf, "reset", 5) == 0) {
pr_debug("scanlog: reset scanlog\n");
status = rtas_call(ibm_scan_log_dump, 2, 1, NULL, 0, 0);
pr_debug("scanlog: rtas returns %d\n", status);
}
}
return count;
}
static int scanlog_open(struct inode * inode, struct file * file)
{
struct proc_dir_entry *dp = PDE(inode);
unsigned int *data = (unsigned int *)dp->data;
if (data[0] != 0) {
/* This imperfect test stops a second copy of the
* data (or a reset while data is being copied)
*/
return -EBUSY;
}
data[0] = 0; /* re-init so we restart the scan */
return 0;
}
static int scanlog_release(struct inode * inode, struct file * file)
{
struct proc_dir_entry *dp = PDE(inode);
unsigned int *data = (unsigned int *)dp->data;
data[0] = 0;
return 0;
}
const struct file_operations scanlog_fops = {
.owner = THIS_MODULE,
.read = scanlog_read,
.write = scanlog_write,
.open = scanlog_open,
.release = scanlog_release,
.llseek = noop_llseek,
};
static int __init scanlog_init(void)
{
struct proc_dir_entry *ent;
void *data;
int err = -ENOMEM;
ibm_scan_log_dump = rtas_token("ibm,scan-log-dump");
if (ibm_scan_log_dump == RTAS_UNKNOWN_SERVICE)
return -ENODEV;
/* Ideally we could allocate a buffer < 4G */
data = kzalloc(RTAS_DATA_BUF_SIZE, GFP_KERNEL);
if (!data)
goto err;
ent = proc_create_data("powerpc/rtas/scan-log-dump", S_IRUSR, NULL,
&scanlog_fops, data);
if (!ent)
goto err;
proc_ppc64_scan_log_dump = ent;
return 0;
err:
kfree(data);
return err;
}
static void __exit scanlog_cleanup(void)
{
if (proc_ppc64_scan_log_dump) {
kfree(proc_ppc64_scan_log_dump->data);
remove_proc_entry("scan-log-dump", proc_ppc64_scan_log_dump->parent);
}
}
module_init(scanlog_init);
module_exit(scanlog_cleanup);
MODULE_LICENSE("GPL");
| gpl-2.0 |
nmenon/ti-linux-kernel-nm | arch/mips/math-emu/sp_fint.c | 10366 | 1865 | /* IEEE754 floating point arithmetic
* single precision
*/
/*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* ########################################################################
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* ########################################################################
*/
#include "ieee754sp.h"
ieee754sp ieee754sp_fint(int x)
{
unsigned xm;
int xe;
int xs;
CLEARCX;
if (x == 0)
return ieee754sp_zero(0);
if (x == 1 || x == -1)
return ieee754sp_one(x < 0);
if (x == 10 || x == -10)
return ieee754sp_ten(x < 0);
xs = (x < 0);
if (xs) {
if (x == (1 << 31))
xm = ((unsigned) 1 << 31); /* max neg can't be safely negated */
else
xm = -x;
} else {
xm = x;
}
xe = SP_MBITS + 3;
if (xm >> (SP_MBITS + 1 + 3)) {
/* shunt out overflow bits
*/
while (xm >> (SP_MBITS + 1 + 3)) {
SPXSRSX1();
}
} else {
/* normalize in grs extended single precision
*/
while ((xm >> (SP_MBITS + 3)) == 0) {
xm <<= 1;
xe--;
}
}
SPNORMRET1(xs, xe, xm, "fint", x);
}
ieee754sp ieee754sp_funs(unsigned int u)
{
if ((int) u < 0)
return ieee754sp_add(ieee754sp_1e31(),
ieee754sp_fint(u & ~(1 << 31)));
return ieee754sp_fint(u);
}
| gpl-2.0 |
Evil-Green/Lonas_KL | arch/mips/math-emu/sp_div.c | 10366 | 4335 | /* IEEE754 floating point arithmetic
* single precision
*/
/*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* ########################################################################
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* ########################################################################
*/
#include "ieee754sp.h"
ieee754sp ieee754sp_div(ieee754sp x, ieee754sp y)
{
COMPXSP;
COMPYSP;
EXPLODEXSP;
EXPLODEYSP;
CLEARCX;
FLUSHXSP;
FLUSHYSP;
switch (CLPAIR(xc, yc)) {
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_SNAN):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_SNAN, IEEE754_CLASS_INF):
SETCX(IEEE754_INVALID_OPERATION);
return ieee754sp_nanxcpt(ieee754sp_indef(), "div", x, y);
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_QNAN):
return y;
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_QNAN):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_DNORM):
case CLPAIR(IEEE754_CLASS_QNAN, IEEE754_CLASS_INF):
return x;
/* Infinity handling
*/
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_INF):
SETCX(IEEE754_INVALID_OPERATION);
return ieee754sp_xcpt(ieee754sp_indef(), "div", x, y);
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_INF):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_INF):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_INF):
return ieee754sp_zero(xs ^ ys);
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_INF, IEEE754_CLASS_DNORM):
return ieee754sp_inf(xs ^ ys);
/* Zero handling
*/
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_ZERO):
SETCX(IEEE754_INVALID_OPERATION);
return ieee754sp_xcpt(ieee754sp_indef(), "div", x, y);
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_ZERO):
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_ZERO):
SETCX(IEEE754_ZERO_DIVIDE);
return ieee754sp_xcpt(ieee754sp_inf(xs ^ ys), "div", x, y);
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_NORM):
case CLPAIR(IEEE754_CLASS_ZERO, IEEE754_CLASS_DNORM):
return ieee754sp_zero(xs == ys ? 0 : 1);
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_DNORM):
SPDNORMX;
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_DNORM):
SPDNORMY;
break;
case CLPAIR(IEEE754_CLASS_DNORM, IEEE754_CLASS_NORM):
SPDNORMX;
break;
case CLPAIR(IEEE754_CLASS_NORM, IEEE754_CLASS_NORM):
break;
}
assert(xm & SP_HIDDEN_BIT);
assert(ym & SP_HIDDEN_BIT);
/* provide rounding space */
xm <<= 3;
ym <<= 3;
{
/* now the dirty work */
unsigned rm = 0;
int re = xe - ye;
unsigned bm;
for (bm = SP_MBIT(SP_MBITS + 2); bm; bm >>= 1) {
if (xm >= ym) {
xm -= ym;
rm |= bm;
if (xm == 0)
break;
}
xm <<= 1;
}
rm <<= 1;
if (xm)
rm |= 1; /* have remainder, set sticky */
assert(rm);
/* normalise rm to rounding precision ?
*/
while ((rm >> (SP_MBITS + 3)) == 0) {
rm <<= 1;
re--;
}
SPNORMRET2(xs == ys ? 0 : 1, re, rm, "div", x, y);
}
}
| gpl-2.0 |
kfazz/android_kernel_motorola_sholes | net/wireless/wext-compat.c | 127 | 36685 | /*
* cfg80211 - wext compat code
*
* This is temporary code until all wireless functionality is migrated
* into cfg80211, when that happens all the exports here go away and
* we directly assign the wireless handlers of wireless interfaces.
*
* Copyright 2008-2009 Johannes Berg <johannes@sipsolutions.net>
*/
#include <linux/wireless.h>
#include <linux/nl80211.h>
#include <linux/if_arp.h>
#include <linux/etherdevice.h>
#include <net/iw_handler.h>
#include <net/cfg80211.h>
#include "wext-compat.h"
#include "core.h"
int cfg80211_wext_giwname(struct net_device *dev,
struct iw_request_info *info,
char *name, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct ieee80211_supported_band *sband;
bool is_ht = false, is_a = false, is_b = false, is_g = false;
if (!wdev)
return -EOPNOTSUPP;
sband = wdev->wiphy->bands[IEEE80211_BAND_5GHZ];
if (sband) {
is_a = true;
is_ht |= sband->ht_cap.ht_supported;
}
sband = wdev->wiphy->bands[IEEE80211_BAND_2GHZ];
if (sband) {
int i;
/* Check for mandatory rates */
for (i = 0; i < sband->n_bitrates; i++) {
if (sband->bitrates[i].bitrate == 10)
is_b = true;
if (sband->bitrates[i].bitrate == 60)
is_g = true;
}
is_ht |= sband->ht_cap.ht_supported;
}
strcpy(name, "IEEE 802.11");
if (is_a)
strcat(name, "a");
if (is_b)
strcat(name, "b");
if (is_g)
strcat(name, "g");
if (is_ht)
strcat(name, "n");
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwname);
int cfg80211_wext_siwmode(struct net_device *dev, struct iw_request_info *info,
u32 *mode, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev;
struct vif_params vifparams;
enum nl80211_iftype type;
int ret;
rdev = wiphy_to_dev(wdev->wiphy);
switch (*mode) {
case IW_MODE_INFRA:
type = NL80211_IFTYPE_STATION;
break;
case IW_MODE_ADHOC:
type = NL80211_IFTYPE_ADHOC;
break;
case IW_MODE_REPEAT:
type = NL80211_IFTYPE_WDS;
break;
case IW_MODE_MONITOR:
type = NL80211_IFTYPE_MONITOR;
break;
default:
return -EINVAL;
}
if (type == wdev->iftype)
return 0;
memset(&vifparams, 0, sizeof(vifparams));
cfg80211_lock_rdev(rdev);
ret = cfg80211_change_iface(rdev, dev, type, NULL, &vifparams);
cfg80211_unlock_rdev(rdev);
return ret;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwmode);
int cfg80211_wext_giwmode(struct net_device *dev, struct iw_request_info *info,
u32 *mode, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (!wdev)
return -EOPNOTSUPP;
switch (wdev->iftype) {
case NL80211_IFTYPE_AP:
*mode = IW_MODE_MASTER;
break;
case NL80211_IFTYPE_STATION:
*mode = IW_MODE_INFRA;
break;
case NL80211_IFTYPE_ADHOC:
*mode = IW_MODE_ADHOC;
break;
case NL80211_IFTYPE_MONITOR:
*mode = IW_MODE_MONITOR;
break;
case NL80211_IFTYPE_WDS:
*mode = IW_MODE_REPEAT;
break;
case NL80211_IFTYPE_AP_VLAN:
*mode = IW_MODE_SECOND; /* FIXME */
break;
default:
*mode = IW_MODE_AUTO;
break;
}
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwmode);
int cfg80211_wext_giwrange(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct iw_range *range = (struct iw_range *) extra;
enum ieee80211_band band;
int i, c = 0;
if (!wdev)
return -EOPNOTSUPP;
data->length = sizeof(struct iw_range);
memset(range, 0, sizeof(struct iw_range));
range->we_version_compiled = WIRELESS_EXT;
range->we_version_source = 21;
range->retry_capa = IW_RETRY_LIMIT;
range->retry_flags = IW_RETRY_LIMIT;
range->min_retry = 0;
range->max_retry = 255;
range->min_rts = 0;
range->max_rts = 2347;
range->min_frag = 256;
range->max_frag = 2346;
range->max_encoding_tokens = 4;
range->max_qual.updated = IW_QUAL_NOISE_INVALID;
switch (wdev->wiphy->signal_type) {
case CFG80211_SIGNAL_TYPE_NONE:
break;
case CFG80211_SIGNAL_TYPE_MBM:
range->max_qual.level = -110;
range->max_qual.qual = 70;
range->avg_qual.qual = 35;
range->max_qual.updated |= IW_QUAL_DBM;
range->max_qual.updated |= IW_QUAL_QUAL_UPDATED;
range->max_qual.updated |= IW_QUAL_LEVEL_UPDATED;
break;
case CFG80211_SIGNAL_TYPE_UNSPEC:
range->max_qual.level = 100;
range->max_qual.qual = 100;
range->avg_qual.qual = 50;
range->max_qual.updated |= IW_QUAL_QUAL_UPDATED;
range->max_qual.updated |= IW_QUAL_LEVEL_UPDATED;
break;
}
range->avg_qual.level = range->max_qual.level / 2;
range->avg_qual.noise = range->max_qual.noise / 2;
range->avg_qual.updated = range->max_qual.updated;
for (i = 0; i < wdev->wiphy->n_cipher_suites; i++) {
switch (wdev->wiphy->cipher_suites[i]) {
case WLAN_CIPHER_SUITE_TKIP:
range->enc_capa |= (IW_ENC_CAPA_CIPHER_TKIP |
IW_ENC_CAPA_WPA);
break;
case WLAN_CIPHER_SUITE_CCMP:
range->enc_capa |= (IW_ENC_CAPA_CIPHER_CCMP |
IW_ENC_CAPA_WPA2);
break;
case WLAN_CIPHER_SUITE_WEP40:
range->encoding_size[range->num_encoding_sizes++] =
WLAN_KEY_LEN_WEP40;
break;
case WLAN_CIPHER_SUITE_WEP104:
range->encoding_size[range->num_encoding_sizes++] =
WLAN_KEY_LEN_WEP104;
break;
}
}
for (band = 0; band < IEEE80211_NUM_BANDS; band ++) {
struct ieee80211_supported_band *sband;
sband = wdev->wiphy->bands[band];
if (!sband)
continue;
for (i = 0; i < sband->n_channels && c < IW_MAX_FREQUENCIES; i++) {
struct ieee80211_channel *chan = &sband->channels[i];
if (!(chan->flags & IEEE80211_CHAN_DISABLED)) {
range->freq[c].i =
ieee80211_frequency_to_channel(
chan->center_freq);
range->freq[c].m = chan->center_freq;
range->freq[c].e = 6;
c++;
}
}
}
range->num_channels = c;
range->num_frequency = c;
IW_EVENT_CAPA_SET_KERNEL(range->event_capa);
IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWAP);
IW_EVENT_CAPA_SET(range->event_capa, SIOCGIWSCAN);
if (wdev->wiphy->max_scan_ssids > 0)
range->scan_capa |= IW_SCAN_CAPA_ESSID;
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwrange);
/**
* cfg80211_wext_freq - get wext frequency for non-"auto"
* @wiphy: the wiphy
* @freq: the wext freq encoding
*
* Returns a frequency, or a negative error code, or 0 for auto.
*/
int cfg80211_wext_freq(struct wiphy *wiphy, struct iw_freq *freq)
{
/*
* Parse frequency - return 0 for auto and
* -EINVAL for impossible things.
*/
if (freq->e == 0) {
if (freq->m < 0)
return 0;
return ieee80211_channel_to_frequency(freq->m);
} else {
int i, div = 1000000;
for (i = 0; i < freq->e; i++)
div /= 10;
if (div <= 0)
return -EINVAL;
return freq->m / div;
}
}
int cfg80211_wext_siwrts(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *rts, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
u32 orts = wdev->wiphy->rts_threshold;
int err;
if (rts->disabled || !rts->fixed)
wdev->wiphy->rts_threshold = (u32) -1;
else if (rts->value < 0)
return -EINVAL;
else
wdev->wiphy->rts_threshold = rts->value;
err = rdev->ops->set_wiphy_params(wdev->wiphy,
WIPHY_PARAM_RTS_THRESHOLD);
if (err)
wdev->wiphy->rts_threshold = orts;
return err;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwrts);
int cfg80211_wext_giwrts(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *rts, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
rts->value = wdev->wiphy->rts_threshold;
rts->disabled = rts->value == (u32) -1;
rts->fixed = 1;
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwrts);
int cfg80211_wext_siwfrag(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *frag, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
u32 ofrag = wdev->wiphy->frag_threshold;
int err;
if (frag->disabled || !frag->fixed)
wdev->wiphy->frag_threshold = (u32) -1;
else if (frag->value < 256)
return -EINVAL;
else {
/* Fragment length must be even, so strip LSB. */
wdev->wiphy->frag_threshold = frag->value & ~0x1;
}
err = rdev->ops->set_wiphy_params(wdev->wiphy,
WIPHY_PARAM_FRAG_THRESHOLD);
if (err)
wdev->wiphy->frag_threshold = ofrag;
return err;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwfrag);
int cfg80211_wext_giwfrag(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *frag, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
frag->value = wdev->wiphy->frag_threshold;
frag->disabled = frag->value == (u32) -1;
frag->fixed = 1;
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwfrag);
int cfg80211_wext_siwretry(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *retry, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
u32 changed = 0;
u8 olong = wdev->wiphy->retry_long;
u8 oshort = wdev->wiphy->retry_short;
int err;
if (retry->disabled ||
(retry->flags & IW_RETRY_TYPE) != IW_RETRY_LIMIT)
return -EINVAL;
if (retry->flags & IW_RETRY_LONG) {
wdev->wiphy->retry_long = retry->value;
changed |= WIPHY_PARAM_RETRY_LONG;
} else if (retry->flags & IW_RETRY_SHORT) {
wdev->wiphy->retry_short = retry->value;
changed |= WIPHY_PARAM_RETRY_SHORT;
} else {
wdev->wiphy->retry_short = retry->value;
wdev->wiphy->retry_long = retry->value;
changed |= WIPHY_PARAM_RETRY_LONG;
changed |= WIPHY_PARAM_RETRY_SHORT;
}
if (!changed)
return 0;
err = rdev->ops->set_wiphy_params(wdev->wiphy, changed);
if (err) {
wdev->wiphy->retry_short = oshort;
wdev->wiphy->retry_long = olong;
}
return err;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwretry);
int cfg80211_wext_giwretry(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *retry, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
retry->disabled = 0;
if (retry->flags == 0 || (retry->flags & IW_RETRY_SHORT)) {
/*
* First return short value, iwconfig will ask long value
* later if needed
*/
retry->flags |= IW_RETRY_LIMIT;
retry->value = wdev->wiphy->retry_short;
if (wdev->wiphy->retry_long != wdev->wiphy->retry_short)
retry->flags |= IW_RETRY_LONG;
return 0;
}
if (retry->flags & IW_RETRY_LONG) {
retry->flags = IW_RETRY_LIMIT | IW_RETRY_LONG;
retry->value = wdev->wiphy->retry_long;
}
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwretry);
static int __cfg80211_set_encryption(struct cfg80211_registered_device *rdev,
struct net_device *dev, const u8 *addr,
bool remove, bool tx_key, int idx,
struct key_params *params)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int err, i;
if (!wdev->wext.keys) {
wdev->wext.keys = kzalloc(sizeof(*wdev->wext.keys),
GFP_KERNEL);
if (!wdev->wext.keys)
return -ENOMEM;
for (i = 0; i < 6; i++)
wdev->wext.keys->params[i].key =
wdev->wext.keys->data[i];
}
if (wdev->iftype != NL80211_IFTYPE_ADHOC &&
wdev->iftype != NL80211_IFTYPE_STATION)
return -EOPNOTSUPP;
if (params->cipher == WLAN_CIPHER_SUITE_AES_CMAC) {
if (!wdev->current_bss)
return -ENOLINK;
if (!rdev->ops->set_default_mgmt_key)
return -EOPNOTSUPP;
if (idx < 4 || idx > 5)
return -EINVAL;
} else if (idx < 0 || idx > 3)
return -EINVAL;
if (remove) {
err = 0;
if (wdev->current_bss)
err = rdev->ops->del_key(&rdev->wiphy, dev, idx, addr);
if (!err) {
if (!addr) {
wdev->wext.keys->params[idx].key_len = 0;
wdev->wext.keys->params[idx].cipher = 0;
}
if (idx == wdev->wext.default_key)
wdev->wext.default_key = -1;
else if (idx == wdev->wext.default_mgmt_key)
wdev->wext.default_mgmt_key = -1;
}
/*
* Applications using wireless extensions expect to be
* able to delete keys that don't exist, so allow that.
*/
if (err == -ENOENT)
return 0;
return err;
}
if (addr)
tx_key = false;
if (cfg80211_validate_key_settings(rdev, params, idx, addr))
return -EINVAL;
err = 0;
if (wdev->current_bss)
err = rdev->ops->add_key(&rdev->wiphy, dev, idx, addr, params);
if (err)
return err;
if (!addr) {
wdev->wext.keys->params[idx] = *params;
memcpy(wdev->wext.keys->data[idx],
params->key, params->key_len);
wdev->wext.keys->params[idx].key =
wdev->wext.keys->data[idx];
}
if ((params->cipher == WLAN_CIPHER_SUITE_WEP40 ||
params->cipher == WLAN_CIPHER_SUITE_WEP104) &&
(tx_key || (!addr && wdev->wext.default_key == -1))) {
if (wdev->current_bss)
err = rdev->ops->set_default_key(&rdev->wiphy,
dev, idx);
if (!err)
wdev->wext.default_key = idx;
return err;
}
if (params->cipher == WLAN_CIPHER_SUITE_AES_CMAC &&
(tx_key || (!addr && wdev->wext.default_mgmt_key == -1))) {
if (wdev->current_bss)
err = rdev->ops->set_default_mgmt_key(&rdev->wiphy,
dev, idx);
if (!err)
wdev->wext.default_mgmt_key = idx;
return err;
}
return 0;
}
static int cfg80211_set_encryption(struct cfg80211_registered_device *rdev,
struct net_device *dev, const u8 *addr,
bool remove, bool tx_key, int idx,
struct key_params *params)
{
int err;
wdev_lock(dev->ieee80211_ptr);
err = __cfg80211_set_encryption(rdev, dev, addr, remove,
tx_key, idx, params);
wdev_unlock(dev->ieee80211_ptr);
return err;
}
int cfg80211_wext_siwencode(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *erq, char *keybuf)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
int idx, err;
bool remove = false;
struct key_params params;
if (wdev->iftype != NL80211_IFTYPE_STATION &&
wdev->iftype != NL80211_IFTYPE_ADHOC)
return -EOPNOTSUPP;
/* no use -- only MFP (set_default_mgmt_key) is optional */
if (!rdev->ops->del_key ||
!rdev->ops->add_key ||
!rdev->ops->set_default_key)
return -EOPNOTSUPP;
idx = erq->flags & IW_ENCODE_INDEX;
if (idx == 0) {
idx = wdev->wext.default_key;
if (idx < 0)
idx = 0;
} else if (idx < 1 || idx > 4)
return -EINVAL;
else
idx--;
if (erq->flags & IW_ENCODE_DISABLED)
remove = true;
else if (erq->length == 0) {
/* No key data - just set the default TX key index */
err = 0;
wdev_lock(wdev);
if (wdev->current_bss)
err = rdev->ops->set_default_key(&rdev->wiphy,
dev, idx);
if (!err)
wdev->wext.default_key = idx;
wdev_unlock(wdev);
return err;
}
memset(¶ms, 0, sizeof(params));
params.key = keybuf;
params.key_len = erq->length;
if (erq->length == 5)
params.cipher = WLAN_CIPHER_SUITE_WEP40;
else if (erq->length == 13)
params.cipher = WLAN_CIPHER_SUITE_WEP104;
else if (!remove)
return -EINVAL;
return cfg80211_set_encryption(rdev, dev, NULL, remove,
wdev->wext.default_key == -1,
idx, ¶ms);
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwencode);
int cfg80211_wext_siwencodeext(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *erq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
struct iw_encode_ext *ext = (struct iw_encode_ext *) extra;
const u8 *addr;
int idx;
bool remove = false;
struct key_params params;
u32 cipher;
if (wdev->iftype != NL80211_IFTYPE_STATION &&
wdev->iftype != NL80211_IFTYPE_ADHOC)
return -EOPNOTSUPP;
/* no use -- only MFP (set_default_mgmt_key) is optional */
if (!rdev->ops->del_key ||
!rdev->ops->add_key ||
!rdev->ops->set_default_key)
return -EOPNOTSUPP;
switch (ext->alg) {
case IW_ENCODE_ALG_NONE:
remove = true;
cipher = 0;
break;
case IW_ENCODE_ALG_WEP:
if (ext->key_len == 5)
cipher = WLAN_CIPHER_SUITE_WEP40;
else if (ext->key_len == 13)
cipher = WLAN_CIPHER_SUITE_WEP104;
else
return -EINVAL;
break;
case IW_ENCODE_ALG_TKIP:
cipher = WLAN_CIPHER_SUITE_TKIP;
break;
case IW_ENCODE_ALG_CCMP:
cipher = WLAN_CIPHER_SUITE_CCMP;
break;
case IW_ENCODE_ALG_AES_CMAC:
cipher = WLAN_CIPHER_SUITE_AES_CMAC;
break;
default:
return -EOPNOTSUPP;
}
if (erq->flags & IW_ENCODE_DISABLED)
remove = true;
idx = erq->flags & IW_ENCODE_INDEX;
if (cipher == WLAN_CIPHER_SUITE_AES_CMAC) {
if (idx < 4 || idx > 5) {
idx = wdev->wext.default_mgmt_key;
if (idx < 0)
return -EINVAL;
} else
idx--;
} else {
if (idx < 1 || idx > 4) {
idx = wdev->wext.default_key;
if (idx < 0)
return -EINVAL;
} else
idx--;
}
addr = ext->addr.sa_data;
if (is_broadcast_ether_addr(addr))
addr = NULL;
memset(¶ms, 0, sizeof(params));
params.key = ext->key;
params.key_len = ext->key_len;
params.cipher = cipher;
if (ext->ext_flags & IW_ENCODE_EXT_RX_SEQ_VALID) {
params.seq = ext->rx_seq;
params.seq_len = 6;
}
return cfg80211_set_encryption(
rdev, dev, addr, remove,
ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY,
idx, ¶ms);
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwencodeext);
int cfg80211_wext_giwencode(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *erq, char *keybuf)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
int idx;
if (wdev->iftype != NL80211_IFTYPE_STATION &&
wdev->iftype != NL80211_IFTYPE_ADHOC)
return -EOPNOTSUPP;
idx = erq->flags & IW_ENCODE_INDEX;
if (idx == 0) {
idx = wdev->wext.default_key;
if (idx < 0)
idx = 0;
} else if (idx < 1 || idx > 4)
return -EINVAL;
else
idx--;
erq->flags = idx + 1;
if (!wdev->wext.keys || !wdev->wext.keys->params[idx].cipher) {
erq->flags |= IW_ENCODE_DISABLED;
erq->length = 0;
return 0;
}
erq->length = min_t(size_t, erq->length,
wdev->wext.keys->params[idx].key_len);
memcpy(keybuf, wdev->wext.keys->params[idx].key, erq->length);
erq->flags |= IW_ENCODE_ENABLED;
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwencode);
int cfg80211_wext_siwfreq(struct net_device *dev,
struct iw_request_info *info,
struct iw_freq *wextfreq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
int freq, err;
switch (wdev->iftype) {
case NL80211_IFTYPE_STATION:
return cfg80211_mgd_wext_siwfreq(dev, info, wextfreq, extra);
case NL80211_IFTYPE_ADHOC:
return cfg80211_ibss_wext_siwfreq(dev, info, wextfreq, extra);
default:
freq = cfg80211_wext_freq(wdev->wiphy, wextfreq);
if (freq < 0)
return freq;
if (freq == 0)
return -EINVAL;
mutex_lock(&rdev->devlist_mtx);
err = rdev_set_freq(rdev, NULL, freq, NL80211_CHAN_NO_HT);
mutex_unlock(&rdev->devlist_mtx);
return err;
}
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwfreq);
int cfg80211_wext_giwfreq(struct net_device *dev,
struct iw_request_info *info,
struct iw_freq *freq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
switch (wdev->iftype) {
case NL80211_IFTYPE_STATION:
return cfg80211_mgd_wext_giwfreq(dev, info, freq, extra);
case NL80211_IFTYPE_ADHOC:
return cfg80211_ibss_wext_giwfreq(dev, info, freq, extra);
default:
if (!rdev->channel)
return -EINVAL;
freq->m = rdev->channel->center_freq;
freq->e = 6;
return 0;
}
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwfreq);
int cfg80211_wext_siwtxpower(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *data, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
enum tx_power_setting type;
int dbm = 0;
if ((data->txpower.flags & IW_TXPOW_TYPE) != IW_TXPOW_DBM)
return -EINVAL;
if (data->txpower.flags & IW_TXPOW_RANGE)
return -EINVAL;
if (!rdev->ops->set_tx_power)
return -EOPNOTSUPP;
/* only change when not disabling */
if (!data->txpower.disabled) {
rfkill_set_sw_state(rdev->rfkill, false);
if (data->txpower.fixed) {
/*
* wext doesn't support negative values, see
* below where it's for automatic
*/
if (data->txpower.value < 0)
return -EINVAL;
dbm = data->txpower.value;
type = TX_POWER_FIXED;
/* TODO: do regulatory check! */
} else {
/*
* Automatic power level setting, max being the value
* passed in from userland.
*/
if (data->txpower.value < 0) {
type = TX_POWER_AUTOMATIC;
} else {
dbm = data->txpower.value;
type = TX_POWER_LIMITED;
}
}
} else {
rfkill_set_sw_state(rdev->rfkill, true);
schedule_work(&rdev->rfkill_sync);
return 0;
}
return rdev->ops->set_tx_power(wdev->wiphy, type, dbm);
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwtxpower);
int cfg80211_wext_giwtxpower(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *data, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
int err, val;
if ((data->txpower.flags & IW_TXPOW_TYPE) != IW_TXPOW_DBM)
return -EINVAL;
if (data->txpower.flags & IW_TXPOW_RANGE)
return -EINVAL;
if (!rdev->ops->get_tx_power)
return -EOPNOTSUPP;
err = rdev->ops->get_tx_power(wdev->wiphy, &val);
if (err)
return err;
/* well... oh well */
data->txpower.fixed = 1;
data->txpower.disabled = rfkill_blocked(rdev->rfkill);
data->txpower.value = val;
data->txpower.flags = IW_TXPOW_DBM;
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwtxpower);
static int cfg80211_set_auth_alg(struct wireless_dev *wdev,
s32 auth_alg)
{
int nr_alg = 0;
if (!auth_alg)
return -EINVAL;
if (auth_alg & ~(IW_AUTH_ALG_OPEN_SYSTEM |
IW_AUTH_ALG_SHARED_KEY |
IW_AUTH_ALG_LEAP))
return -EINVAL;
if (auth_alg & IW_AUTH_ALG_OPEN_SYSTEM) {
nr_alg++;
wdev->wext.connect.auth_type = NL80211_AUTHTYPE_OPEN_SYSTEM;
}
if (auth_alg & IW_AUTH_ALG_SHARED_KEY) {
nr_alg++;
wdev->wext.connect.auth_type = NL80211_AUTHTYPE_SHARED_KEY;
}
if (auth_alg & IW_AUTH_ALG_LEAP) {
nr_alg++;
wdev->wext.connect.auth_type = NL80211_AUTHTYPE_NETWORK_EAP;
}
if (nr_alg > 1)
wdev->wext.connect.auth_type = NL80211_AUTHTYPE_AUTOMATIC;
return 0;
}
static int cfg80211_set_wpa_version(struct wireless_dev *wdev, u32 wpa_versions)
{
wdev->wext.connect.crypto.wpa_versions = 0;
if (wpa_versions & ~(IW_AUTH_WPA_VERSION_WPA |
IW_AUTH_WPA_VERSION_WPA2|
IW_AUTH_WPA_VERSION_DISABLED))
return -EINVAL;
if ((wpa_versions & IW_AUTH_WPA_VERSION_DISABLED) &&
(wpa_versions & (IW_AUTH_WPA_VERSION_WPA|
IW_AUTH_WPA_VERSION_WPA2)))
return -EINVAL;
if (wpa_versions & IW_AUTH_WPA_VERSION_DISABLED)
wdev->wext.connect.crypto.wpa_versions &=
~(NL80211_WPA_VERSION_1|NL80211_WPA_VERSION_2);
if (wpa_versions & IW_AUTH_WPA_VERSION_WPA)
wdev->wext.connect.crypto.wpa_versions |=
NL80211_WPA_VERSION_1;
if (wpa_versions & IW_AUTH_WPA_VERSION_WPA2)
wdev->wext.connect.crypto.wpa_versions |=
NL80211_WPA_VERSION_2;
return 0;
}
static int cfg80211_set_cipher_group(struct wireless_dev *wdev, u32 cipher)
{
wdev->wext.connect.crypto.cipher_group = 0;
if (cipher & IW_AUTH_CIPHER_WEP40)
wdev->wext.connect.crypto.cipher_group =
WLAN_CIPHER_SUITE_WEP40;
else if (cipher & IW_AUTH_CIPHER_WEP104)
wdev->wext.connect.crypto.cipher_group =
WLAN_CIPHER_SUITE_WEP104;
else if (cipher & IW_AUTH_CIPHER_TKIP)
wdev->wext.connect.crypto.cipher_group =
WLAN_CIPHER_SUITE_TKIP;
else if (cipher & IW_AUTH_CIPHER_CCMP)
wdev->wext.connect.crypto.cipher_group =
WLAN_CIPHER_SUITE_CCMP;
else if (cipher & IW_AUTH_CIPHER_AES_CMAC)
wdev->wext.connect.crypto.cipher_group =
WLAN_CIPHER_SUITE_AES_CMAC;
else
return -EINVAL;
return 0;
}
static int cfg80211_set_cipher_pairwise(struct wireless_dev *wdev, u32 cipher)
{
int nr_ciphers = 0;
u32 *ciphers_pairwise = wdev->wext.connect.crypto.ciphers_pairwise;
if (cipher & IW_AUTH_CIPHER_WEP40) {
ciphers_pairwise[nr_ciphers] = WLAN_CIPHER_SUITE_WEP40;
nr_ciphers++;
}
if (cipher & IW_AUTH_CIPHER_WEP104) {
ciphers_pairwise[nr_ciphers] = WLAN_CIPHER_SUITE_WEP104;
nr_ciphers++;
}
if (cipher & IW_AUTH_CIPHER_TKIP) {
ciphers_pairwise[nr_ciphers] = WLAN_CIPHER_SUITE_TKIP;
nr_ciphers++;
}
if (cipher & IW_AUTH_CIPHER_CCMP) {
ciphers_pairwise[nr_ciphers] = WLAN_CIPHER_SUITE_CCMP;
nr_ciphers++;
}
if (cipher & IW_AUTH_CIPHER_AES_CMAC) {
ciphers_pairwise[nr_ciphers] = WLAN_CIPHER_SUITE_AES_CMAC;
nr_ciphers++;
}
BUILD_BUG_ON(NL80211_MAX_NR_CIPHER_SUITES < 5);
wdev->wext.connect.crypto.n_ciphers_pairwise = nr_ciphers;
return 0;
}
static int cfg80211_set_key_mgt(struct wireless_dev *wdev, u32 key_mgt)
{
int nr_akm_suites = 0;
if (key_mgt & ~(IW_AUTH_KEY_MGMT_802_1X |
IW_AUTH_KEY_MGMT_PSK))
return -EINVAL;
if (key_mgt & IW_AUTH_KEY_MGMT_802_1X) {
wdev->wext.connect.crypto.akm_suites[nr_akm_suites] =
WLAN_AKM_SUITE_8021X;
nr_akm_suites++;
}
if (key_mgt & IW_AUTH_KEY_MGMT_PSK) {
wdev->wext.connect.crypto.akm_suites[nr_akm_suites] =
WLAN_AKM_SUITE_PSK;
nr_akm_suites++;
}
wdev->wext.connect.crypto.n_akm_suites = nr_akm_suites;
return 0;
}
int cfg80211_wext_siwauth(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *data, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (wdev->iftype != NL80211_IFTYPE_STATION)
return -EOPNOTSUPP;
switch (data->flags & IW_AUTH_INDEX) {
case IW_AUTH_PRIVACY_INVOKED:
wdev->wext.connect.privacy = data->value;
return 0;
case IW_AUTH_WPA_VERSION:
return cfg80211_set_wpa_version(wdev, data->value);
case IW_AUTH_CIPHER_GROUP:
return cfg80211_set_cipher_group(wdev, data->value);
case IW_AUTH_KEY_MGMT:
return cfg80211_set_key_mgt(wdev, data->value);
case IW_AUTH_CIPHER_PAIRWISE:
return cfg80211_set_cipher_pairwise(wdev, data->value);
case IW_AUTH_80211_AUTH_ALG:
return cfg80211_set_auth_alg(wdev, data->value);
case IW_AUTH_WPA_ENABLED:
case IW_AUTH_RX_UNENCRYPTED_EAPOL:
case IW_AUTH_DROP_UNENCRYPTED:
case IW_AUTH_MFP:
return 0;
default:
return -EOPNOTSUPP;
}
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwauth);
int cfg80211_wext_giwauth(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *data, char *extra)
{
/* XXX: what do we need? */
return -EOPNOTSUPP;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwauth);
int cfg80211_wext_siwpower(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *wrq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
bool ps = wdev->wext.ps;
int timeout = wdev->wext.ps_timeout;
int err;
if (wdev->iftype != NL80211_IFTYPE_STATION)
return -EINVAL;
if (!rdev->ops->set_power_mgmt)
return -EOPNOTSUPP;
if (wrq->disabled) {
ps = false;
} else {
switch (wrq->flags & IW_POWER_MODE) {
case IW_POWER_ON: /* If not specified */
case IW_POWER_MODE: /* If set all mask */
case IW_POWER_ALL_R: /* If explicitely state all */
ps = true;
break;
default: /* Otherwise we ignore */
return -EINVAL;
}
if (wrq->flags & ~(IW_POWER_MODE | IW_POWER_TIMEOUT))
return -EINVAL;
if (wrq->flags & IW_POWER_TIMEOUT)
timeout = wrq->value / 1000;
}
err = rdev->ops->set_power_mgmt(wdev->wiphy, dev, ps, timeout);
if (err)
return err;
wdev->wext.ps = ps;
wdev->wext.ps_timeout = timeout;
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwpower);
int cfg80211_wext_giwpower(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *wrq, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
wrq->disabled = !wdev->wext.ps;
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwpower);
static int cfg80211_wds_wext_siwap(struct net_device *dev,
struct iw_request_info *info,
struct sockaddr *addr, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
int err;
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_WDS))
return -EINVAL;
if (addr->sa_family != ARPHRD_ETHER)
return -EINVAL;
if (netif_running(dev))
return -EBUSY;
if (!rdev->ops->set_wds_peer)
return -EOPNOTSUPP;
err = rdev->ops->set_wds_peer(wdev->wiphy, dev, (u8 *) &addr->sa_data);
if (err)
return err;
memcpy(&wdev->wext.bssid, (u8 *) &addr->sa_data, ETH_ALEN);
return 0;
}
static int cfg80211_wds_wext_giwap(struct net_device *dev,
struct iw_request_info *info,
struct sockaddr *addr, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_WDS))
return -EINVAL;
addr->sa_family = ARPHRD_ETHER;
memcpy(&addr->sa_data, wdev->wext.bssid, ETH_ALEN);
return 0;
}
int cfg80211_wext_siwrate(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *rate, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
struct cfg80211_bitrate_mask mask;
if (!rdev->ops->set_bitrate_mask)
return -EOPNOTSUPP;
mask.fixed = 0;
mask.maxrate = 0;
if (rate->value < 0) {
/* nothing */
} else if (rate->fixed) {
mask.fixed = rate->value / 1000; /* kbps */
} else {
mask.maxrate = rate->value / 1000; /* kbps */
}
return rdev->ops->set_bitrate_mask(wdev->wiphy, dev, NULL, &mask);
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwrate);
int cfg80211_wext_giwrate(struct net_device *dev,
struct iw_request_info *info,
struct iw_param *rate, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
/* we are under RTNL - globally locked - so can use a static struct */
static struct station_info sinfo;
u8 addr[ETH_ALEN];
int err;
if (wdev->iftype != NL80211_IFTYPE_STATION)
return -EOPNOTSUPP;
if (!rdev->ops->get_station)
return -EOPNOTSUPP;
err = 0;
wdev_lock(wdev);
if (wdev->current_bss)
memcpy(addr, wdev->current_bss->pub.bssid, ETH_ALEN);
else
err = -EOPNOTSUPP;
wdev_unlock(wdev);
if (err)
return err;
err = rdev->ops->get_station(&rdev->wiphy, dev, addr, &sinfo);
if (err)
return err;
if (!(sinfo.filled & STATION_INFO_TX_BITRATE))
return -EOPNOTSUPP;
rate->value = 100000 * cfg80211_calculate_bitrate(&sinfo.txrate);
return 0;
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwrate);
/* Get wireless statistics. Called by /proc/net/wireless and by SIOCGIWSTATS */
struct iw_statistics *cfg80211_wireless_stats(struct net_device *dev)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
/* we are under RTNL - globally locked - so can use static structs */
static struct iw_statistics wstats;
static struct station_info sinfo;
u8 bssid[ETH_ALEN];
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION)
return NULL;
if (!rdev->ops->get_station)
return NULL;
/* Grab BSSID of current BSS, if any */
wdev_lock(wdev);
if (!wdev->current_bss) {
wdev_unlock(wdev);
return NULL;
}
memcpy(bssid, wdev->current_bss->pub.bssid, ETH_ALEN);
wdev_unlock(wdev);
if (rdev->ops->get_station(&rdev->wiphy, dev, bssid, &sinfo))
return NULL;
memset(&wstats, 0, sizeof(wstats));
switch (rdev->wiphy.signal_type) {
case CFG80211_SIGNAL_TYPE_MBM:
if (sinfo.filled & STATION_INFO_SIGNAL) {
int sig = sinfo.signal;
wstats.qual.updated |= IW_QUAL_LEVEL_UPDATED;
wstats.qual.updated |= IW_QUAL_QUAL_UPDATED;
wstats.qual.updated |= IW_QUAL_DBM;
wstats.qual.level = sig;
if (sig < -110)
sig = -110;
else if (sig > -40)
sig = -40;
wstats.qual.qual = sig + 110;
break;
}
case CFG80211_SIGNAL_TYPE_UNSPEC:
if (sinfo.filled & STATION_INFO_SIGNAL) {
wstats.qual.updated |= IW_QUAL_LEVEL_UPDATED;
wstats.qual.updated |= IW_QUAL_QUAL_UPDATED;
wstats.qual.level = sinfo.signal;
wstats.qual.qual = sinfo.signal;
break;
}
default:
wstats.qual.updated |= IW_QUAL_LEVEL_INVALID;
wstats.qual.updated |= IW_QUAL_QUAL_INVALID;
}
wstats.qual.updated |= IW_QUAL_NOISE_INVALID;
return &wstats;
}
EXPORT_SYMBOL_GPL(cfg80211_wireless_stats);
int cfg80211_wext_siwap(struct net_device *dev,
struct iw_request_info *info,
struct sockaddr *ap_addr, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
switch (wdev->iftype) {
case NL80211_IFTYPE_ADHOC:
return cfg80211_ibss_wext_siwap(dev, info, ap_addr, extra);
case NL80211_IFTYPE_STATION:
return cfg80211_mgd_wext_siwap(dev, info, ap_addr, extra);
case NL80211_IFTYPE_WDS:
return cfg80211_wds_wext_siwap(dev, info, ap_addr, extra);
default:
return -EOPNOTSUPP;
}
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwap);
int cfg80211_wext_giwap(struct net_device *dev,
struct iw_request_info *info,
struct sockaddr *ap_addr, char *extra)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
switch (wdev->iftype) {
case NL80211_IFTYPE_ADHOC:
return cfg80211_ibss_wext_giwap(dev, info, ap_addr, extra);
case NL80211_IFTYPE_STATION:
return cfg80211_mgd_wext_giwap(dev, info, ap_addr, extra);
case NL80211_IFTYPE_WDS:
return cfg80211_wds_wext_giwap(dev, info, ap_addr, extra);
default:
return -EOPNOTSUPP;
}
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwap);
int cfg80211_wext_siwessid(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *ssid)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
switch (wdev->iftype) {
case NL80211_IFTYPE_ADHOC:
return cfg80211_ibss_wext_siwessid(dev, info, data, ssid);
case NL80211_IFTYPE_STATION:
return cfg80211_mgd_wext_siwessid(dev, info, data, ssid);
default:
return -EOPNOTSUPP;
}
}
EXPORT_SYMBOL_GPL(cfg80211_wext_siwessid);
int cfg80211_wext_giwessid(struct net_device *dev,
struct iw_request_info *info,
struct iw_point *data, char *ssid)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
data->flags = 0;
data->length = 0;
switch (wdev->iftype) {
case NL80211_IFTYPE_ADHOC:
return cfg80211_ibss_wext_giwessid(dev, info, data, ssid);
case NL80211_IFTYPE_STATION:
return cfg80211_mgd_wext_giwessid(dev, info, data, ssid);
default:
return -EOPNOTSUPP;
}
}
EXPORT_SYMBOL_GPL(cfg80211_wext_giwessid);
static const iw_handler cfg80211_handlers[] = {
[IW_IOCTL_IDX(SIOCGIWNAME)] = (iw_handler) cfg80211_wext_giwname,
[IW_IOCTL_IDX(SIOCSIWFREQ)] = (iw_handler) cfg80211_wext_siwfreq,
[IW_IOCTL_IDX(SIOCGIWFREQ)] = (iw_handler) cfg80211_wext_giwfreq,
[IW_IOCTL_IDX(SIOCSIWMODE)] = (iw_handler) cfg80211_wext_siwmode,
[IW_IOCTL_IDX(SIOCGIWMODE)] = (iw_handler) cfg80211_wext_giwmode,
[IW_IOCTL_IDX(SIOCGIWRANGE)] = (iw_handler) cfg80211_wext_giwrange,
[IW_IOCTL_IDX(SIOCSIWAP)] = (iw_handler) cfg80211_wext_siwap,
[IW_IOCTL_IDX(SIOCGIWAP)] = (iw_handler) cfg80211_wext_giwap,
[IW_IOCTL_IDX(SIOCSIWMLME)] = (iw_handler) cfg80211_wext_siwmlme,
[IW_IOCTL_IDX(SIOCSIWSCAN)] = (iw_handler) cfg80211_wext_siwscan,
[IW_IOCTL_IDX(SIOCGIWSCAN)] = (iw_handler) cfg80211_wext_giwscan,
[IW_IOCTL_IDX(SIOCSIWESSID)] = (iw_handler) cfg80211_wext_siwessid,
[IW_IOCTL_IDX(SIOCGIWESSID)] = (iw_handler) cfg80211_wext_giwessid,
[IW_IOCTL_IDX(SIOCSIWRATE)] = (iw_handler) cfg80211_wext_siwrate,
[IW_IOCTL_IDX(SIOCGIWRATE)] = (iw_handler) cfg80211_wext_giwrate,
[IW_IOCTL_IDX(SIOCSIWRTS)] = (iw_handler) cfg80211_wext_siwrts,
[IW_IOCTL_IDX(SIOCGIWRTS)] = (iw_handler) cfg80211_wext_giwrts,
[IW_IOCTL_IDX(SIOCSIWFRAG)] = (iw_handler) cfg80211_wext_siwfrag,
[IW_IOCTL_IDX(SIOCGIWFRAG)] = (iw_handler) cfg80211_wext_giwfrag,
[IW_IOCTL_IDX(SIOCSIWTXPOW)] = (iw_handler) cfg80211_wext_siwtxpower,
[IW_IOCTL_IDX(SIOCGIWTXPOW)] = (iw_handler) cfg80211_wext_giwtxpower,
[IW_IOCTL_IDX(SIOCSIWRETRY)] = (iw_handler) cfg80211_wext_siwretry,
[IW_IOCTL_IDX(SIOCGIWRETRY)] = (iw_handler) cfg80211_wext_giwretry,
[IW_IOCTL_IDX(SIOCSIWENCODE)] = (iw_handler) cfg80211_wext_siwencode,
[IW_IOCTL_IDX(SIOCGIWENCODE)] = (iw_handler) cfg80211_wext_giwencode,
[IW_IOCTL_IDX(SIOCSIWPOWER)] = (iw_handler) cfg80211_wext_siwpower,
[IW_IOCTL_IDX(SIOCGIWPOWER)] = (iw_handler) cfg80211_wext_giwpower,
[IW_IOCTL_IDX(SIOCSIWGENIE)] = (iw_handler) cfg80211_wext_siwgenie,
[IW_IOCTL_IDX(SIOCSIWAUTH)] = (iw_handler) cfg80211_wext_siwauth,
[IW_IOCTL_IDX(SIOCGIWAUTH)] = (iw_handler) cfg80211_wext_giwauth,
[IW_IOCTL_IDX(SIOCSIWENCODEEXT)]= (iw_handler) cfg80211_wext_siwencodeext,
};
const struct iw_handler_def cfg80211_wext_handler = {
.num_standard = ARRAY_SIZE(cfg80211_handlers),
.standard = cfg80211_handlers,
.get_wireless_stats = cfg80211_wireless_stats,
};
| gpl-2.0 |
Vitallium/qtwebkit | Source/WebCore/Modules/mediastream/NavigatorMediaStream.cpp | 127 | 2339 | /*
* Copyright (C) 2000 Harri Porten (porten@kde.org)
* Copyright (c) 2000 Daniel Molkentin (molkentin@kde.org)
* Copyright (c) 2000 Stefan Schimanski (schimmi@kde.org)
* Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc.
* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#include "NavigatorMediaStream.h"
#if ENABLE(MEDIA_STREAM)
#include "Dictionary.h"
#include "Document.h"
#include "ExceptionCode.h"
#include "Frame.h"
#include "Navigator.h"
#include "NavigatorUserMediaErrorCallback.h"
#include "NavigatorUserMediaSuccessCallback.h"
#include "Page.h"
#include "UserMediaController.h"
#include "UserMediaRequest.h"
namespace WebCore {
NavigatorMediaStream::NavigatorMediaStream()
{
}
NavigatorMediaStream::~NavigatorMediaStream()
{
}
void NavigatorMediaStream::webkitGetUserMedia(Navigator* navigator, const Dictionary& options, PassRefPtr<NavigatorUserMediaSuccessCallback> successCallback, PassRefPtr<NavigatorUserMediaErrorCallback> errorCallback, ExceptionCode& ec)
{
if (!successCallback)
return;
UserMediaController* userMedia = UserMediaController::from(navigator->frame() ? navigator->frame()->page() : 0);
if (!userMedia) {
ec = NOT_SUPPORTED_ERR;
return;
}
RefPtr<UserMediaRequest> request = UserMediaRequest::create(navigator->frame()->document(), userMedia, options, successCallback, errorCallback, ec);
if (!request) {
ec = NOT_SUPPORTED_ERR;
return;
}
request->start();
}
} // namespace WebCore
#endif // ENABLE(MEDIA_STREAM)
| gpl-2.0 |
BrandonSchaefer/xbmc | xbmc/cores/DllLoader/LibraryLoader.cpp | 127 | 1768 | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.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, 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "LibraryLoader.h"
#include <string.h>
#include <stdlib.h>
#include "utils/log.h"
LibraryLoader::LibraryLoader(const std::string& libraryFile):
m_fileName(libraryFile)
{
size_t pos = m_fileName.find_last_of("\\/");
if (pos != std::string::npos)
m_path = m_fileName.substr(0, pos);
m_iRefCount = 1;
}
LibraryLoader::~LibraryLoader()
{
}
const char *LibraryLoader::GetName() const
{
size_t pos = m_fileName.find_last_of('/');
if (pos != std::string::npos)
return &m_fileName.at(pos);
return m_fileName.c_str();
}
const char *LibraryLoader::GetFileName() const
{
return m_fileName.c_str();
}
const char *LibraryLoader::GetPath() const
{
return m_path.c_str();
}
int LibraryLoader::IncrRef()
{
m_iRefCount++;
return m_iRefCount;
}
int LibraryLoader::DecrRef()
{
m_iRefCount--;
return m_iRefCount;
}
int LibraryLoader::ResolveOrdinal(unsigned long ordinal, void** ptr)
{
CLog::Log(LOGWARNING, "%s - Unable to resolve %lu in dll %s", __FUNCTION__, ordinal, GetName());
return 0;
}
| gpl-2.0 |
pershoot/galaxy-2636 | sound/soc/omap/omap3pandora.c | 127 | 9378 | /*
* omap3pandora.c -- SoC audio for Pandora Handheld Console
*
* Author: Gražvydas Ignotas <notasas@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/regulator/consumer.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <asm/mach-types.h>
#include "omap-mcbsp.h"
#include "omap-pcm.h"
#include "../codecs/twl4030.h"
#define OMAP3_PANDORA_DAC_POWER_GPIO 118
#define OMAP3_PANDORA_AMP_POWER_GPIO 14
#define PREFIX "ASoC omap3pandora: "
static struct regulator *omap3pandora_dac_reg;
static int omap3pandora_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->dai->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai;
int fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF |
SND_SOC_DAIFMT_CBS_CFS;
int ret;
/* Set codec DAI configuration */
ret = snd_soc_dai_set_fmt(codec_dai, fmt);
if (ret < 0) {
pr_err(PREFIX "can't set codec DAI configuration\n");
return ret;
}
/* Set cpu DAI configuration */
ret = snd_soc_dai_set_fmt(cpu_dai, fmt);
if (ret < 0) {
pr_err(PREFIX "can't set cpu DAI configuration\n");
return ret;
}
/* Set the codec system clock for DAC and ADC */
ret = snd_soc_dai_set_sysclk(codec_dai, 0, 26000000,
SND_SOC_CLOCK_IN);
if (ret < 0) {
pr_err(PREFIX "can't set codec system clock\n");
return ret;
}
/* Set McBSP clock to external */
ret = snd_soc_dai_set_sysclk(cpu_dai, OMAP_MCBSP_SYSCLK_CLKS_EXT,
256 * params_rate(params),
SND_SOC_CLOCK_IN);
if (ret < 0) {
pr_err(PREFIX "can't set cpu system clock\n");
return ret;
}
ret = snd_soc_dai_set_clkdiv(cpu_dai, OMAP_MCBSP_CLKGDV, 8);
if (ret < 0) {
pr_err(PREFIX "can't set SRG clock divider\n");
return ret;
}
return 0;
}
static int omap3pandora_dac_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
/*
* The PCM1773 DAC datasheet requires 1ms delay between switching
* VCC power on/off and /PD pin high/low
*/
if (SND_SOC_DAPM_EVENT_ON(event)) {
regulator_enable(omap3pandora_dac_reg);
mdelay(1);
gpio_set_value(OMAP3_PANDORA_DAC_POWER_GPIO, 1);
} else {
gpio_set_value(OMAP3_PANDORA_DAC_POWER_GPIO, 0);
mdelay(1);
regulator_disable(omap3pandora_dac_reg);
}
return 0;
}
static int omap3pandora_hp_event(struct snd_soc_dapm_widget *w,
struct snd_kcontrol *k, int event)
{
if (SND_SOC_DAPM_EVENT_ON(event))
gpio_set_value(OMAP3_PANDORA_AMP_POWER_GPIO, 1);
else
gpio_set_value(OMAP3_PANDORA_AMP_POWER_GPIO, 0);
return 0;
}
/*
* Audio paths on Pandora board:
*
* |O| ---> PCM DAC +-> AMP -> Headphone Jack
* |M| A +--------> Line Out
* |A| <~~clk~~+
* |P| <--- TWL4030 <--------- Line In and MICs
*/
static const struct snd_soc_dapm_widget omap3pandora_out_dapm_widgets[] = {
SND_SOC_DAPM_DAC_E("PCM DAC", "HiFi Playback", SND_SOC_NOPM,
0, 0, omap3pandora_dac_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_PGA_E("Headphone Amplifier", SND_SOC_NOPM,
0, 0, NULL, 0, omap3pandora_hp_event,
SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_PRE_PMD),
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_LINE("Line Out", NULL),
};
static const struct snd_soc_dapm_widget omap3pandora_in_dapm_widgets[] = {
SND_SOC_DAPM_MIC("Mic (internal)", NULL),
SND_SOC_DAPM_MIC("Mic (external)", NULL),
SND_SOC_DAPM_LINE("Line In", NULL),
};
static const struct snd_soc_dapm_route omap3pandora_out_map[] = {
{"PCM DAC", NULL, "APLL Enable"},
{"Headphone Amplifier", NULL, "PCM DAC"},
{"Line Out", NULL, "PCM DAC"},
{"Headphone Jack", NULL, "Headphone Amplifier"},
};
static const struct snd_soc_dapm_route omap3pandora_in_map[] = {
{"AUXL", NULL, "Line In"},
{"AUXR", NULL, "Line In"},
{"MAINMIC", NULL, "Mic Bias 1"},
{"Mic Bias 1", NULL, "Mic (internal)"},
{"SUBMIC", NULL, "Mic Bias 2"},
{"Mic Bias 2", NULL, "Mic (external)"},
};
static int omap3pandora_out_init(struct snd_soc_codec *codec)
{
int ret;
/* All TWL4030 output pins are floating */
snd_soc_dapm_nc_pin(codec, "EARPIECE");
snd_soc_dapm_nc_pin(codec, "PREDRIVEL");
snd_soc_dapm_nc_pin(codec, "PREDRIVER");
snd_soc_dapm_nc_pin(codec, "HSOL");
snd_soc_dapm_nc_pin(codec, "HSOR");
snd_soc_dapm_nc_pin(codec, "CARKITL");
snd_soc_dapm_nc_pin(codec, "CARKITR");
snd_soc_dapm_nc_pin(codec, "HFL");
snd_soc_dapm_nc_pin(codec, "HFR");
snd_soc_dapm_nc_pin(codec, "VIBRA");
ret = snd_soc_dapm_new_controls(codec, omap3pandora_out_dapm_widgets,
ARRAY_SIZE(omap3pandora_out_dapm_widgets));
if (ret < 0)
return ret;
snd_soc_dapm_add_routes(codec, omap3pandora_out_map,
ARRAY_SIZE(omap3pandora_out_map));
return snd_soc_dapm_sync(codec);
}
static int omap3pandora_in_init(struct snd_soc_codec *codec)
{
int ret;
/* Not comnnected */
snd_soc_dapm_nc_pin(codec, "HSMIC");
snd_soc_dapm_nc_pin(codec, "CARKITMIC");
snd_soc_dapm_nc_pin(codec, "DIGIMIC0");
snd_soc_dapm_nc_pin(codec, "DIGIMIC1");
ret = snd_soc_dapm_new_controls(codec, omap3pandora_in_dapm_widgets,
ARRAY_SIZE(omap3pandora_in_dapm_widgets));
if (ret < 0)
return ret;
snd_soc_dapm_add_routes(codec, omap3pandora_in_map,
ARRAY_SIZE(omap3pandora_in_map));
return snd_soc_dapm_sync(codec);
}
static struct snd_soc_ops omap3pandora_ops = {
.hw_params = omap3pandora_hw_params,
};
/* Digital audio interface glue - connects codec <--> CPU */
static struct snd_soc_dai_link omap3pandora_dai[] = {
{
.name = "PCM1773",
.stream_name = "HiFi Out",
.cpu_dai = &omap_mcbsp_dai[0],
.codec_dai = &twl4030_dai[TWL4030_DAI_HIFI],
.ops = &omap3pandora_ops,
.init = omap3pandora_out_init,
}, {
.name = "TWL4030",
.stream_name = "Line/Mic In",
.cpu_dai = &omap_mcbsp_dai[1],
.codec_dai = &twl4030_dai[TWL4030_DAI_HIFI],
.ops = &omap3pandora_ops,
.init = omap3pandora_in_init,
}
};
/* SoC card */
static struct snd_soc_card snd_soc_card_omap3pandora = {
.name = "omap3pandora",
.platform = &omap_soc_platform,
.dai_link = omap3pandora_dai,
.num_links = ARRAY_SIZE(omap3pandora_dai),
};
/* Audio subsystem */
static struct snd_soc_device omap3pandora_snd_data = {
.card = &snd_soc_card_omap3pandora,
.codec_dev = &soc_codec_dev_twl4030,
};
static struct platform_device *omap3pandora_snd_device;
static int __init omap3pandora_soc_init(void)
{
int ret;
if (!machine_is_omap3_pandora())
return -ENODEV;
pr_info("OMAP3 Pandora SoC init\n");
ret = gpio_request(OMAP3_PANDORA_DAC_POWER_GPIO, "dac_power");
if (ret) {
pr_err(PREFIX "Failed to get DAC power GPIO\n");
return ret;
}
ret = gpio_direction_output(OMAP3_PANDORA_DAC_POWER_GPIO, 0);
if (ret) {
pr_err(PREFIX "Failed to set DAC power GPIO direction\n");
goto fail0;
}
ret = gpio_request(OMAP3_PANDORA_AMP_POWER_GPIO, "amp_power");
if (ret) {
pr_err(PREFIX "Failed to get amp power GPIO\n");
goto fail0;
}
ret = gpio_direction_output(OMAP3_PANDORA_AMP_POWER_GPIO, 0);
if (ret) {
pr_err(PREFIX "Failed to set amp power GPIO direction\n");
goto fail1;
}
omap3pandora_snd_device = platform_device_alloc("soc-audio", -1);
if (omap3pandora_snd_device == NULL) {
pr_err(PREFIX "Platform device allocation failed\n");
ret = -ENOMEM;
goto fail1;
}
platform_set_drvdata(omap3pandora_snd_device, &omap3pandora_snd_data);
omap3pandora_snd_data.dev = &omap3pandora_snd_device->dev;
*(unsigned int *)omap_mcbsp_dai[0].private_data = 1; /* McBSP2 */
*(unsigned int *)omap_mcbsp_dai[1].private_data = 3; /* McBSP4 */
ret = platform_device_add(omap3pandora_snd_device);
if (ret) {
pr_err(PREFIX "Unable to add platform device\n");
goto fail2;
}
omap3pandora_dac_reg = regulator_get(&omap3pandora_snd_device->dev, "vcc");
if (IS_ERR(omap3pandora_dac_reg)) {
pr_err(PREFIX "Failed to get DAC regulator from %s: %ld\n",
dev_name(&omap3pandora_snd_device->dev),
PTR_ERR(omap3pandora_dac_reg));
goto fail3;
}
return 0;
fail3:
platform_device_del(omap3pandora_snd_device);
fail2:
platform_device_put(omap3pandora_snd_device);
fail1:
gpio_free(OMAP3_PANDORA_AMP_POWER_GPIO);
fail0:
gpio_free(OMAP3_PANDORA_DAC_POWER_GPIO);
return ret;
}
module_init(omap3pandora_soc_init);
static void __exit omap3pandora_soc_exit(void)
{
regulator_put(omap3pandora_dac_reg);
platform_device_unregister(omap3pandora_snd_device);
gpio_free(OMAP3_PANDORA_AMP_POWER_GPIO);
gpio_free(OMAP3_PANDORA_DAC_POWER_GPIO);
}
module_exit(omap3pandora_soc_exit);
MODULE_AUTHOR("Grazvydas Ignotas <notasas@gmail.com>");
MODULE_DESCRIPTION("ALSA SoC OMAP3 Pandora");
MODULE_LICENSE("GPL");
| gpl-2.0 |
davet321/rpi-linux | drivers/clk/ti/clk-814x.c | 383 | 2255 | /*
* 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/kernel.h>
#include <linux/clk.h>
#include <linux/clk-provider.h>
#include <linux/clk/ti.h>
#include <linux/of_platform.h>
#include "clock.h"
static struct ti_dt_clk dm814_clks[] = {
DT_CLK(NULL, "devosc_ck", "devosc_ck"),
DT_CLK(NULL, "mpu_ck", "mpu_ck"),
DT_CLK(NULL, "sysclk4_ck", "sysclk4_ck"),
DT_CLK(NULL, "sysclk5_ck", "sysclk5_ck"),
DT_CLK(NULL, "sysclk6_ck", "sysclk6_ck"),
DT_CLK(NULL, "sysclk8_ck", "sysclk8_ck"),
DT_CLK(NULL, "sysclk10_ck", "sysclk10_ck"),
DT_CLK(NULL, "sysclk18_ck", "sysclk18_ck"),
DT_CLK(NULL, "timer_sys_ck", "devosc_ck"),
DT_CLK(NULL, "timer1_fck", "timer1_fck"),
DT_CLK(NULL, "timer2_fck", "timer2_fck"),
DT_CLK(NULL, "cpsw_125mhz_gclk", "cpsw_125mhz_gclk"),
DT_CLK(NULL, "cpsw_cpts_rft_clk", "cpsw_cpts_rft_clk"),
{ .node_name = NULL },
};
static bool timer_clocks_initialized;
static int __init dm814x_adpll_early_init(void)
{
struct device_node *np;
if (!timer_clocks_initialized)
return -ENODEV;
np = of_find_node_by_name(NULL, "pllss");
if (!np) {
pr_err("Could not find node for plls\n");
return -ENODEV;
}
of_platform_populate(np, NULL, NULL, NULL);
return 0;
}
core_initcall(dm814x_adpll_early_init);
static const char * const init_clocks[] = {
"pll040clkout", /* MPU 481c5040.adpll.clkout */
"pll290clkout", /* DDR 481c5290.adpll.clkout */
};
static int __init dm814x_adpll_enable_init_clocks(void)
{
int i, err;
if (!timer_clocks_initialized)
return -ENODEV;
for (i = 0; i < ARRAY_SIZE(init_clocks); i++) {
struct clk *clock;
clock = clk_get(NULL, init_clocks[i]);
if (WARN(IS_ERR(clock), "could not find init clock %s\n",
init_clocks[i]))
continue;
err = clk_prepare_enable(clock);
if (WARN(err, "could not enable init clock %s\n",
init_clocks[i]))
continue;
}
return 0;
}
postcore_initcall(dm814x_adpll_enable_init_clocks);
int __init dm814x_dt_clk_init(void)
{
ti_dt_clocks_register(dm814_clks);
omap2_clk_disable_autoidle_all();
omap2_clk_enable_init_clocks(NULL, 0);
timer_clocks_initialized = true;
return 0;
}
| gpl-2.0 |
oceanfly/linux | drivers/net/ethernet/qlogic/qlcnic/qlcnic_sysfs.c | 639 | 36978 | /*
* QLogic qlcnic NIC Driver
* Copyright (c) 2009-2013 QLogic Corporation
*
* See LICENSE.qlcnic for copyright and licensing details.
*/
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/swab.h>
#include <linux/dma-mapping.h>
#include <net/ip.h>
#include <linux/ipv6.h>
#include <linux/inetdevice.h>
#include <linux/sysfs.h>
#include <linux/aer.h>
#include <linux/log2.h>
#ifdef CONFIG_QLCNIC_HWMON
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#endif
#include "qlcnic.h"
#include "qlcnic_hw.h"
int qlcnicvf_config_bridged_mode(struct qlcnic_adapter *adapter, u32 enable)
{
return -EOPNOTSUPP;
}
int qlcnicvf_config_led(struct qlcnic_adapter *adapter, u32 state, u32 rate)
{
return -EOPNOTSUPP;
}
static ssize_t qlcnic_store_bridged_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
unsigned long new;
int ret = -EINVAL;
if (!(adapter->ahw->capabilities & QLCNIC_FW_CAPABILITY_BDG))
goto err_out;
if (!test_bit(__QLCNIC_DEV_UP, &adapter->state))
goto err_out;
if (kstrtoul(buf, 2, &new))
goto err_out;
if (!qlcnic_config_bridged_mode(adapter, !!new))
ret = len;
err_out:
return ret;
}
static ssize_t qlcnic_show_bridged_mode(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
int bridged_mode = 0;
if (adapter->ahw->capabilities & QLCNIC_FW_CAPABILITY_BDG)
bridged_mode = !!(adapter->flags & QLCNIC_BRIDGE_ENABLED);
return sprintf(buf, "%d\n", bridged_mode);
}
static ssize_t qlcnic_store_diag_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
unsigned long new;
if (kstrtoul(buf, 2, &new))
return -EINVAL;
if (!!new != !!(adapter->flags & QLCNIC_DIAG_ENABLED))
adapter->flags ^= QLCNIC_DIAG_ENABLED;
return len;
}
static ssize_t qlcnic_show_diag_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", !!(adapter->flags & QLCNIC_DIAG_ENABLED));
}
static int qlcnic_validate_beacon(struct qlcnic_adapter *adapter, u16 beacon,
u8 *state, u8 *rate)
{
*rate = LSB(beacon);
*state = MSB(beacon);
QLCDB(adapter, DRV, "rate %x state %x\n", *rate, *state);
if (!*state) {
*rate = __QLCNIC_MAX_LED_RATE;
return 0;
} else if (*state > __QLCNIC_MAX_LED_STATE) {
return -EINVAL;
}
if ((!*rate) || (*rate > __QLCNIC_MAX_LED_RATE))
return -EINVAL;
return 0;
}
static int qlcnic_83xx_store_beacon(struct qlcnic_adapter *adapter,
const char *buf, size_t len)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
unsigned long h_beacon;
int err;
if (test_bit(__QLCNIC_RESETTING, &adapter->state))
return -EIO;
if (kstrtoul(buf, 2, &h_beacon))
return -EINVAL;
qlcnic_get_beacon_state(adapter);
if (ahw->beacon_state == h_beacon)
return len;
rtnl_lock();
if (!ahw->beacon_state) {
if (test_and_set_bit(__QLCNIC_LED_ENABLE, &adapter->state)) {
rtnl_unlock();
return -EBUSY;
}
}
if (h_beacon)
err = qlcnic_83xx_config_led(adapter, 1, h_beacon);
else
err = qlcnic_83xx_config_led(adapter, 0, !h_beacon);
if (!err)
ahw->beacon_state = h_beacon;
if (!ahw->beacon_state)
clear_bit(__QLCNIC_LED_ENABLE, &adapter->state);
rtnl_unlock();
return len;
}
static int qlcnic_82xx_store_beacon(struct qlcnic_adapter *adapter,
const char *buf, size_t len)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
int err, drv_sds_rings = adapter->drv_sds_rings;
u16 beacon;
u8 b_state, b_rate;
if (len != sizeof(u16))
return -EINVAL;
memcpy(&beacon, buf, sizeof(u16));
err = qlcnic_validate_beacon(adapter, beacon, &b_state, &b_rate);
if (err)
return err;
qlcnic_get_beacon_state(adapter);
if (ahw->beacon_state == b_state)
return len;
rtnl_lock();
if (!ahw->beacon_state) {
if (test_and_set_bit(__QLCNIC_LED_ENABLE, &adapter->state)) {
rtnl_unlock();
return -EBUSY;
}
}
if (test_bit(__QLCNIC_RESETTING, &adapter->state)) {
err = -EIO;
goto out;
}
if (!test_bit(__QLCNIC_DEV_UP, &adapter->state)) {
err = qlcnic_diag_alloc_res(adapter->netdev, QLCNIC_LED_TEST);
if (err)
goto out;
set_bit(__QLCNIC_DIAG_RES_ALLOC, &adapter->state);
}
err = qlcnic_config_led(adapter, b_state, b_rate);
if (!err) {
err = len;
ahw->beacon_state = b_state;
}
if (test_and_clear_bit(__QLCNIC_DIAG_RES_ALLOC, &adapter->state))
qlcnic_diag_free_res(adapter->netdev, drv_sds_rings);
out:
if (!ahw->beacon_state)
clear_bit(__QLCNIC_LED_ENABLE, &adapter->state);
rtnl_unlock();
return err;
}
static ssize_t qlcnic_store_beacon(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
int err = 0;
if (adapter->ahw->op_mode == QLCNIC_NON_PRIV_FUNC) {
dev_warn(dev,
"LED test not supported in non privileged mode\n");
return -EOPNOTSUPP;
}
if (qlcnic_82xx_check(adapter))
err = qlcnic_82xx_store_beacon(adapter, buf, len);
else if (qlcnic_83xx_check(adapter))
err = qlcnic_83xx_store_beacon(adapter, buf, len);
else
return -EIO;
return err;
}
static ssize_t qlcnic_show_beacon(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
return sprintf(buf, "%d\n", adapter->ahw->beacon_state);
}
static int qlcnic_sysfs_validate_crb(struct qlcnic_adapter *adapter,
loff_t offset, size_t size)
{
size_t crb_size = 4;
if (!(adapter->flags & QLCNIC_DIAG_ENABLED))
return -EIO;
if (offset < QLCNIC_PCI_CRBSPACE) {
if (ADDR_IN_RANGE(offset, QLCNIC_PCI_CAMQM,
QLCNIC_PCI_CAMQM_END))
crb_size = 8;
else
return -EINVAL;
}
if ((size != crb_size) || (offset & (crb_size-1)))
return -EINVAL;
return 0;
}
static ssize_t qlcnic_sysfs_read_crb(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t offset, size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
int ret;
ret = qlcnic_sysfs_validate_crb(adapter, offset, size);
if (ret != 0)
return ret;
qlcnic_read_crb(adapter, buf, offset, size);
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
return size;
}
static ssize_t qlcnic_sysfs_write_crb(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t offset, size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
int ret;
ret = qlcnic_sysfs_validate_crb(adapter, offset, size);
if (ret != 0)
return ret;
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
qlcnic_write_crb(adapter, buf, offset, size);
return size;
}
static int qlcnic_sysfs_validate_mem(struct qlcnic_adapter *adapter,
loff_t offset, size_t size)
{
if (!(adapter->flags & QLCNIC_DIAG_ENABLED))
return -EIO;
if ((size != 8) || (offset & 0x7))
return -EIO;
return 0;
}
static ssize_t qlcnic_sysfs_read_mem(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t offset, size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
u64 data;
int ret;
ret = qlcnic_sysfs_validate_mem(adapter, offset, size);
if (ret != 0)
return ret;
if (qlcnic_pci_mem_read_2M(adapter, offset, &data))
return -EIO;
memcpy(buf, &data, size);
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
return size;
}
static ssize_t qlcnic_sysfs_write_mem(struct file *filp, struct kobject *kobj,
struct bin_attribute *attr, char *buf,
loff_t offset, size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
u64 data;
int ret;
ret = qlcnic_sysfs_validate_mem(adapter, offset, size);
if (ret != 0)
return ret;
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
memcpy(&data, buf, size);
if (qlcnic_pci_mem_write_2M(adapter, offset, data))
return -EIO;
return size;
}
int qlcnic_is_valid_nic_func(struct qlcnic_adapter *adapter, u8 pci_func)
{
int i;
for (i = 0; i < adapter->ahw->total_nic_func; i++) {
if (adapter->npars[i].pci_func == pci_func)
return i;
}
dev_err(&adapter->pdev->dev, "%s: Invalid nic function\n", __func__);
return -EINVAL;
}
static int validate_pm_config(struct qlcnic_adapter *adapter,
struct qlcnic_pm_func_cfg *pm_cfg, int count)
{
u8 src_pci_func, s_esw_id, d_esw_id;
u8 dest_pci_func;
int i, src_index, dest_index;
for (i = 0; i < count; i++) {
src_pci_func = pm_cfg[i].pci_func;
dest_pci_func = pm_cfg[i].dest_npar;
src_index = qlcnic_is_valid_nic_func(adapter, src_pci_func);
if (src_index < 0)
return -EINVAL;
dest_index = qlcnic_is_valid_nic_func(adapter, dest_pci_func);
if (dest_index < 0)
return -EINVAL;
s_esw_id = adapter->npars[src_index].phy_port;
d_esw_id = adapter->npars[dest_index].phy_port;
if (s_esw_id != d_esw_id)
return -EINVAL;
}
return 0;
}
static ssize_t qlcnic_sysfs_write_pm_config(struct file *filp,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
struct qlcnic_pm_func_cfg *pm_cfg;
u32 id, action, pci_func;
int count, rem, i, ret, index;
count = size / sizeof(struct qlcnic_pm_func_cfg);
rem = size % sizeof(struct qlcnic_pm_func_cfg);
if (rem)
return -EINVAL;
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
pm_cfg = (struct qlcnic_pm_func_cfg *)buf;
ret = validate_pm_config(adapter, pm_cfg, count);
if (ret)
return ret;
for (i = 0; i < count; i++) {
pci_func = pm_cfg[i].pci_func;
action = !!pm_cfg[i].action;
index = qlcnic_is_valid_nic_func(adapter, pci_func);
if (index < 0)
return -EINVAL;
id = adapter->npars[index].phy_port;
ret = qlcnic_config_port_mirroring(adapter, id,
action, pci_func);
if (ret)
return ret;
}
for (i = 0; i < count; i++) {
pci_func = pm_cfg[i].pci_func;
index = qlcnic_is_valid_nic_func(adapter, pci_func);
if (index < 0)
return -EINVAL;
id = adapter->npars[index].phy_port;
adapter->npars[index].enable_pm = !!pm_cfg[i].action;
adapter->npars[index].dest_npar = id;
}
return size;
}
static ssize_t qlcnic_sysfs_read_pm_config(struct file *filp,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
struct qlcnic_pm_func_cfg *pm_cfg;
u8 pci_func;
u32 count;
int i;
memset(buf, 0, size);
pm_cfg = (struct qlcnic_pm_func_cfg *)buf;
count = size / sizeof(struct qlcnic_pm_func_cfg);
for (i = 0; i < adapter->ahw->total_nic_func; i++) {
pci_func = adapter->npars[i].pci_func;
if (pci_func >= count) {
dev_dbg(dev, "%s: Total nic functions[%d], App sent function count[%d]\n",
__func__, adapter->ahw->total_nic_func, count);
continue;
}
if (!adapter->npars[i].eswitch_status)
continue;
pm_cfg[pci_func].action = adapter->npars[i].enable_pm;
pm_cfg[pci_func].dest_npar = 0;
pm_cfg[pci_func].pci_func = i;
}
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
return size;
}
static int validate_esw_config(struct qlcnic_adapter *adapter,
struct qlcnic_esw_func_cfg *esw_cfg, int count)
{
struct qlcnic_hardware_context *ahw = adapter->ahw;
int i, ret;
u32 op_mode;
u8 pci_func;
if (qlcnic_82xx_check(adapter))
op_mode = readl(ahw->pci_base0 + QLCNIC_DRV_OP_MODE);
else
op_mode = QLCRDX(ahw, QLC_83XX_DRV_OP_MODE);
for (i = 0; i < count; i++) {
pci_func = esw_cfg[i].pci_func;
if (pci_func >= ahw->max_vnic_func)
return -EINVAL;
if (adapter->ahw->op_mode == QLCNIC_MGMT_FUNC)
if (qlcnic_is_valid_nic_func(adapter, pci_func) < 0)
return -EINVAL;
switch (esw_cfg[i].op_mode) {
case QLCNIC_PORT_DEFAULTS:
if (qlcnic_82xx_check(adapter)) {
ret = QLC_DEV_GET_DRV(op_mode, pci_func);
} else {
ret = QLC_83XX_GET_FUNC_PRIVILEGE(op_mode,
pci_func);
esw_cfg[i].offload_flags = 0;
}
if (ret != QLCNIC_NON_PRIV_FUNC) {
if (esw_cfg[i].mac_anti_spoof != 0)
return -EINVAL;
if (esw_cfg[i].mac_override != 1)
return -EINVAL;
if (esw_cfg[i].promisc_mode != 1)
return -EINVAL;
}
break;
case QLCNIC_ADD_VLAN:
if (!IS_VALID_VLAN(esw_cfg[i].vlan_id))
return -EINVAL;
if (!esw_cfg[i].op_type)
return -EINVAL;
break;
case QLCNIC_DEL_VLAN:
if (!esw_cfg[i].op_type)
return -EINVAL;
break;
default:
return -EINVAL;
}
}
return 0;
}
static ssize_t qlcnic_sysfs_write_esw_config(struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
struct qlcnic_esw_func_cfg *esw_cfg;
struct qlcnic_npar_info *npar;
int count, rem, i, ret;
int index;
u8 op_mode = 0, pci_func;
count = size / sizeof(struct qlcnic_esw_func_cfg);
rem = size % sizeof(struct qlcnic_esw_func_cfg);
if (rem)
return -EINVAL;
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
esw_cfg = (struct qlcnic_esw_func_cfg *)buf;
ret = validate_esw_config(adapter, esw_cfg, count);
if (ret)
return ret;
for (i = 0; i < count; i++) {
if (adapter->ahw->op_mode == QLCNIC_MGMT_FUNC)
if (qlcnic_config_switch_port(adapter, &esw_cfg[i]))
return -EINVAL;
if (adapter->ahw->pci_func != esw_cfg[i].pci_func)
continue;
op_mode = esw_cfg[i].op_mode;
qlcnic_get_eswitch_port_config(adapter, &esw_cfg[i]);
esw_cfg[i].op_mode = op_mode;
esw_cfg[i].pci_func = adapter->ahw->pci_func;
switch (esw_cfg[i].op_mode) {
case QLCNIC_PORT_DEFAULTS:
qlcnic_set_eswitch_port_features(adapter, &esw_cfg[i]);
rtnl_lock();
qlcnic_set_netdev_features(adapter, &esw_cfg[i]);
rtnl_unlock();
break;
case QLCNIC_ADD_VLAN:
qlcnic_set_vlan_config(adapter, &esw_cfg[i]);
break;
case QLCNIC_DEL_VLAN:
esw_cfg[i].vlan_id = 0;
qlcnic_set_vlan_config(adapter, &esw_cfg[i]);
break;
}
}
if (adapter->ahw->op_mode != QLCNIC_MGMT_FUNC)
goto out;
for (i = 0; i < count; i++) {
pci_func = esw_cfg[i].pci_func;
index = qlcnic_is_valid_nic_func(adapter, pci_func);
if (index < 0)
return -EINVAL;
npar = &adapter->npars[index];
switch (esw_cfg[i].op_mode) {
case QLCNIC_PORT_DEFAULTS:
npar->promisc_mode = esw_cfg[i].promisc_mode;
npar->mac_override = esw_cfg[i].mac_override;
npar->offload_flags = esw_cfg[i].offload_flags;
npar->mac_anti_spoof = esw_cfg[i].mac_anti_spoof;
npar->discard_tagged = esw_cfg[i].discard_tagged;
break;
case QLCNIC_ADD_VLAN:
npar->pvid = esw_cfg[i].vlan_id;
break;
case QLCNIC_DEL_VLAN:
npar->pvid = 0;
break;
}
}
out:
return size;
}
static ssize_t qlcnic_sysfs_read_esw_config(struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
struct qlcnic_esw_func_cfg *esw_cfg;
u8 pci_func;
u32 count;
int i;
memset(buf, 0, size);
esw_cfg = (struct qlcnic_esw_func_cfg *)buf;
count = size / sizeof(struct qlcnic_esw_func_cfg);
for (i = 0; i < adapter->ahw->total_nic_func; i++) {
pci_func = adapter->npars[i].pci_func;
if (pci_func >= count) {
dev_dbg(dev, "%s: Total nic functions[%d], App sent function count[%d]\n",
__func__, adapter->ahw->total_nic_func, count);
continue;
}
if (!adapter->npars[i].eswitch_status)
continue;
esw_cfg[pci_func].pci_func = pci_func;
if (qlcnic_get_eswitch_port_config(adapter, &esw_cfg[pci_func]))
return -EINVAL;
}
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
return size;
}
static int validate_npar_config(struct qlcnic_adapter *adapter,
struct qlcnic_npar_func_cfg *np_cfg,
int count)
{
u8 pci_func, i;
for (i = 0; i < count; i++) {
pci_func = np_cfg[i].pci_func;
if (qlcnic_is_valid_nic_func(adapter, pci_func) < 0)
return -EINVAL;
if (!IS_VALID_BW(np_cfg[i].min_bw) ||
!IS_VALID_BW(np_cfg[i].max_bw))
return -EINVAL;
}
return 0;
}
static ssize_t qlcnic_sysfs_write_npar_config(struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
struct qlcnic_info nic_info;
struct qlcnic_npar_func_cfg *np_cfg;
int i, count, rem, ret, index;
u8 pci_func;
count = size / sizeof(struct qlcnic_npar_func_cfg);
rem = size % sizeof(struct qlcnic_npar_func_cfg);
if (rem)
return -EINVAL;
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
np_cfg = (struct qlcnic_npar_func_cfg *)buf;
ret = validate_npar_config(adapter, np_cfg, count);
if (ret)
return ret;
for (i = 0; i < count; i++) {
pci_func = np_cfg[i].pci_func;
memset(&nic_info, 0, sizeof(struct qlcnic_info));
ret = qlcnic_get_nic_info(adapter, &nic_info, pci_func);
if (ret)
return ret;
nic_info.pci_func = pci_func;
nic_info.min_tx_bw = np_cfg[i].min_bw;
nic_info.max_tx_bw = np_cfg[i].max_bw;
ret = qlcnic_set_nic_info(adapter, &nic_info);
if (ret)
return ret;
index = qlcnic_is_valid_nic_func(adapter, pci_func);
if (index < 0)
return -EINVAL;
adapter->npars[index].min_bw = nic_info.min_tx_bw;
adapter->npars[index].max_bw = nic_info.max_tx_bw;
}
return size;
}
static ssize_t qlcnic_sysfs_read_npar_config(struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
struct qlcnic_npar_func_cfg *np_cfg;
struct qlcnic_info nic_info;
u8 pci_func;
int i, ret;
u32 count;
memset(&nic_info, 0, sizeof(struct qlcnic_info));
memset(buf, 0, size);
np_cfg = (struct qlcnic_npar_func_cfg *)buf;
count = size / sizeof(struct qlcnic_npar_func_cfg);
for (i = 0; i < adapter->ahw->total_nic_func; i++) {
if (adapter->npars[i].pci_func >= count) {
dev_dbg(dev, "%s: Total nic functions[%d], App sent function count[%d]\n",
__func__, adapter->ahw->total_nic_func, count);
continue;
}
if (!adapter->npars[i].eswitch_status)
continue;
pci_func = adapter->npars[i].pci_func;
if (qlcnic_is_valid_nic_func(adapter, pci_func) < 0)
continue;
ret = qlcnic_get_nic_info(adapter, &nic_info, pci_func);
if (ret)
return ret;
np_cfg[pci_func].pci_func = pci_func;
np_cfg[pci_func].op_mode = (u8)nic_info.op_mode;
np_cfg[pci_func].port_num = nic_info.phys_port;
np_cfg[pci_func].fw_capab = nic_info.capabilities;
np_cfg[pci_func].min_bw = nic_info.min_tx_bw;
np_cfg[pci_func].max_bw = nic_info.max_tx_bw;
np_cfg[pci_func].max_tx_queues = nic_info.max_tx_ques;
np_cfg[pci_func].max_rx_queues = nic_info.max_rx_ques;
}
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
return size;
}
static ssize_t qlcnic_sysfs_get_port_stats(struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
struct qlcnic_esw_statistics port_stats;
int ret;
if (qlcnic_83xx_check(adapter))
return -EOPNOTSUPP;
if (size != sizeof(struct qlcnic_esw_statistics))
return -EINVAL;
if (offset >= adapter->ahw->max_vnic_func)
return -EINVAL;
memset(&port_stats, 0, size);
ret = qlcnic_get_port_stats(adapter, offset, QLCNIC_QUERY_RX_COUNTER,
&port_stats.rx);
if (ret)
return ret;
ret = qlcnic_get_port_stats(adapter, offset, QLCNIC_QUERY_TX_COUNTER,
&port_stats.tx);
if (ret)
return ret;
memcpy(buf, &port_stats, size);
return size;
}
static ssize_t qlcnic_sysfs_get_esw_stats(struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
struct qlcnic_esw_statistics esw_stats;
int ret;
if (qlcnic_83xx_check(adapter))
return -EOPNOTSUPP;
if (size != sizeof(struct qlcnic_esw_statistics))
return -EINVAL;
if (offset >= QLCNIC_NIU_MAX_XG_PORTS)
return -EINVAL;
memset(&esw_stats, 0, size);
ret = qlcnic_get_eswitch_stats(adapter, offset, QLCNIC_QUERY_RX_COUNTER,
&esw_stats.rx);
if (ret)
return ret;
ret = qlcnic_get_eswitch_stats(adapter, offset, QLCNIC_QUERY_TX_COUNTER,
&esw_stats.tx);
if (ret)
return ret;
memcpy(buf, &esw_stats, size);
return size;
}
static ssize_t qlcnic_sysfs_clear_esw_stats(struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
int ret;
if (qlcnic_83xx_check(adapter))
return -EOPNOTSUPP;
if (offset >= QLCNIC_NIU_MAX_XG_PORTS)
return -EINVAL;
ret = qlcnic_clear_esw_stats(adapter, QLCNIC_STATS_ESWITCH, offset,
QLCNIC_QUERY_RX_COUNTER);
if (ret)
return ret;
ret = qlcnic_clear_esw_stats(adapter, QLCNIC_STATS_ESWITCH, offset,
QLCNIC_QUERY_TX_COUNTER);
if (ret)
return ret;
return size;
}
static ssize_t qlcnic_sysfs_clear_port_stats(struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
int ret;
if (qlcnic_83xx_check(adapter))
return -EOPNOTSUPP;
if (offset >= adapter->ahw->max_vnic_func)
return -EINVAL;
ret = qlcnic_clear_esw_stats(adapter, QLCNIC_STATS_PORT, offset,
QLCNIC_QUERY_RX_COUNTER);
if (ret)
return ret;
ret = qlcnic_clear_esw_stats(adapter, QLCNIC_STATS_PORT, offset,
QLCNIC_QUERY_TX_COUNTER);
if (ret)
return ret;
return size;
}
static ssize_t qlcnic_sysfs_read_pci_config(struct file *file,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
struct qlcnic_pci_func_cfg *pci_cfg;
struct qlcnic_pci_info *pci_info;
int i, ret;
u32 count;
pci_info = kcalloc(size, sizeof(*pci_info), GFP_KERNEL);
if (!pci_info)
return -ENOMEM;
ret = qlcnic_get_pci_info(adapter, pci_info);
if (ret) {
kfree(pci_info);
return ret;
}
pci_cfg = (struct qlcnic_pci_func_cfg *)buf;
count = size / sizeof(struct qlcnic_pci_func_cfg);
qlcnic_swap32_buffer((u32 *)pci_info, size / sizeof(u32));
for (i = 0; i < count; i++) {
pci_cfg[i].pci_func = pci_info[i].id;
pci_cfg[i].func_type = pci_info[i].type;
pci_cfg[i].func_state = 0;
pci_cfg[i].port_num = pci_info[i].default_port;
pci_cfg[i].min_bw = pci_info[i].tx_min_bw;
pci_cfg[i].max_bw = pci_info[i].tx_max_bw;
memcpy(&pci_cfg[i].def_mac_addr, &pci_info[i].mac, ETH_ALEN);
}
kfree(pci_info);
return size;
}
static ssize_t qlcnic_83xx_sysfs_flash_read_handler(struct file *filp,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
unsigned char *p_read_buf;
int ret, count;
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
if (!size)
return -EINVAL;
count = size / sizeof(u32);
if (size % sizeof(u32))
count++;
p_read_buf = kcalloc(size, sizeof(unsigned char), GFP_KERNEL);
if (!p_read_buf)
return -ENOMEM;
if (qlcnic_83xx_lock_flash(adapter) != 0) {
kfree(p_read_buf);
return -EIO;
}
ret = qlcnic_83xx_lockless_flash_read32(adapter, offset, p_read_buf,
count);
if (ret) {
qlcnic_83xx_unlock_flash(adapter);
kfree(p_read_buf);
return ret;
}
qlcnic_83xx_unlock_flash(adapter);
qlcnic_swap32_buffer((u32 *)p_read_buf, count);
memcpy(buf, p_read_buf, size);
kfree(p_read_buf);
return size;
}
static int qlcnic_83xx_sysfs_flash_bulk_write(struct qlcnic_adapter *adapter,
char *buf, loff_t offset,
size_t size)
{
int i, ret, count;
unsigned char *p_cache, *p_src;
p_cache = kcalloc(size, sizeof(unsigned char), GFP_KERNEL);
if (!p_cache)
return -ENOMEM;
count = size / sizeof(u32);
qlcnic_swap32_buffer((u32 *)buf, count);
memcpy(p_cache, buf, size);
p_src = p_cache;
if (qlcnic_83xx_lock_flash(adapter) != 0) {
kfree(p_cache);
return -EIO;
}
if (adapter->ahw->fdt.mfg_id == adapter->flash_mfg_id) {
ret = qlcnic_83xx_enable_flash_write(adapter);
if (ret) {
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return -EIO;
}
}
for (i = 0; i < count / QLC_83XX_FLASH_WRITE_MAX; i++) {
ret = qlcnic_83xx_flash_bulk_write(adapter, offset,
(u32 *)p_src,
QLC_83XX_FLASH_WRITE_MAX);
if (ret) {
if (adapter->ahw->fdt.mfg_id == adapter->flash_mfg_id) {
ret = qlcnic_83xx_disable_flash_write(adapter);
if (ret) {
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return -EIO;
}
}
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return -EIO;
}
p_src = p_src + sizeof(u32)*QLC_83XX_FLASH_WRITE_MAX;
offset = offset + sizeof(u32)*QLC_83XX_FLASH_WRITE_MAX;
}
if (adapter->ahw->fdt.mfg_id == adapter->flash_mfg_id) {
ret = qlcnic_83xx_disable_flash_write(adapter);
if (ret) {
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return -EIO;
}
}
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return 0;
}
static int qlcnic_83xx_sysfs_flash_write(struct qlcnic_adapter *adapter,
char *buf, loff_t offset, size_t size)
{
int i, ret, count;
unsigned char *p_cache, *p_src;
p_cache = kcalloc(size, sizeof(unsigned char), GFP_KERNEL);
if (!p_cache)
return -ENOMEM;
qlcnic_swap32_buffer((u32 *)buf, size / sizeof(u32));
memcpy(p_cache, buf, size);
p_src = p_cache;
count = size / sizeof(u32);
if (qlcnic_83xx_lock_flash(adapter) != 0) {
kfree(p_cache);
return -EIO;
}
if (adapter->ahw->fdt.mfg_id == adapter->flash_mfg_id) {
ret = qlcnic_83xx_enable_flash_write(adapter);
if (ret) {
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return -EIO;
}
}
for (i = 0; i < count; i++) {
ret = qlcnic_83xx_flash_write32(adapter, offset, (u32 *)p_src);
if (ret) {
if (adapter->ahw->fdt.mfg_id == adapter->flash_mfg_id) {
ret = qlcnic_83xx_disable_flash_write(adapter);
if (ret) {
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return -EIO;
}
}
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return -EIO;
}
p_src = p_src + sizeof(u32);
offset = offset + sizeof(u32);
}
if (adapter->ahw->fdt.mfg_id == adapter->flash_mfg_id) {
ret = qlcnic_83xx_disable_flash_write(adapter);
if (ret) {
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return -EIO;
}
}
kfree(p_cache);
qlcnic_83xx_unlock_flash(adapter);
return 0;
}
static ssize_t qlcnic_83xx_sysfs_flash_write_handler(struct file *filp,
struct kobject *kobj,
struct bin_attribute *attr,
char *buf, loff_t offset,
size_t size)
{
int ret;
static int flash_mode;
unsigned long data;
struct device *dev = container_of(kobj, struct device, kobj);
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
ret = kstrtoul(buf, 16, &data);
switch (data) {
case QLC_83XX_FLASH_SECTOR_ERASE_CMD:
flash_mode = QLC_83XX_ERASE_MODE;
ret = qlcnic_83xx_erase_flash_sector(adapter, offset);
if (ret) {
dev_err(&adapter->pdev->dev,
"%s failed at %d\n", __func__, __LINE__);
return -EIO;
}
break;
case QLC_83XX_FLASH_BULK_WRITE_CMD:
flash_mode = QLC_83XX_BULK_WRITE_MODE;
break;
case QLC_83XX_FLASH_WRITE_CMD:
flash_mode = QLC_83XX_WRITE_MODE;
break;
default:
if (flash_mode == QLC_83XX_BULK_WRITE_MODE) {
ret = qlcnic_83xx_sysfs_flash_bulk_write(adapter, buf,
offset, size);
if (ret) {
dev_err(&adapter->pdev->dev,
"%s failed at %d\n",
__func__, __LINE__);
return -EIO;
}
}
if (flash_mode == QLC_83XX_WRITE_MODE) {
ret = qlcnic_83xx_sysfs_flash_write(adapter, buf,
offset, size);
if (ret) {
dev_err(&adapter->pdev->dev,
"%s failed at %d\n", __func__,
__LINE__);
return -EIO;
}
}
}
return size;
}
static struct device_attribute dev_attr_bridged_mode = {
.attr = {.name = "bridged_mode", .mode = (S_IRUGO | S_IWUSR)},
.show = qlcnic_show_bridged_mode,
.store = qlcnic_store_bridged_mode,
};
static struct device_attribute dev_attr_diag_mode = {
.attr = {.name = "diag_mode", .mode = (S_IRUGO | S_IWUSR)},
.show = qlcnic_show_diag_mode,
.store = qlcnic_store_diag_mode,
};
static struct device_attribute dev_attr_beacon = {
.attr = {.name = "beacon", .mode = (S_IRUGO | S_IWUSR)},
.show = qlcnic_show_beacon,
.store = qlcnic_store_beacon,
};
static struct bin_attribute bin_attr_crb = {
.attr = {.name = "crb", .mode = (S_IRUGO | S_IWUSR)},
.size = 0,
.read = qlcnic_sysfs_read_crb,
.write = qlcnic_sysfs_write_crb,
};
static struct bin_attribute bin_attr_mem = {
.attr = {.name = "mem", .mode = (S_IRUGO | S_IWUSR)},
.size = 0,
.read = qlcnic_sysfs_read_mem,
.write = qlcnic_sysfs_write_mem,
};
static struct bin_attribute bin_attr_npar_config = {
.attr = {.name = "npar_config", .mode = (S_IRUGO | S_IWUSR)},
.size = 0,
.read = qlcnic_sysfs_read_npar_config,
.write = qlcnic_sysfs_write_npar_config,
};
static struct bin_attribute bin_attr_pci_config = {
.attr = {.name = "pci_config", .mode = (S_IRUGO | S_IWUSR)},
.size = 0,
.read = qlcnic_sysfs_read_pci_config,
.write = NULL,
};
static struct bin_attribute bin_attr_port_stats = {
.attr = {.name = "port_stats", .mode = (S_IRUGO | S_IWUSR)},
.size = 0,
.read = qlcnic_sysfs_get_port_stats,
.write = qlcnic_sysfs_clear_port_stats,
};
static struct bin_attribute bin_attr_esw_stats = {
.attr = {.name = "esw_stats", .mode = (S_IRUGO | S_IWUSR)},
.size = 0,
.read = qlcnic_sysfs_get_esw_stats,
.write = qlcnic_sysfs_clear_esw_stats,
};
static struct bin_attribute bin_attr_esw_config = {
.attr = {.name = "esw_config", .mode = (S_IRUGO | S_IWUSR)},
.size = 0,
.read = qlcnic_sysfs_read_esw_config,
.write = qlcnic_sysfs_write_esw_config,
};
static struct bin_attribute bin_attr_pm_config = {
.attr = {.name = "pm_config", .mode = (S_IRUGO | S_IWUSR)},
.size = 0,
.read = qlcnic_sysfs_read_pm_config,
.write = qlcnic_sysfs_write_pm_config,
};
static struct bin_attribute bin_attr_flash = {
.attr = {.name = "flash", .mode = (S_IRUGO | S_IWUSR)},
.size = 0,
.read = qlcnic_83xx_sysfs_flash_read_handler,
.write = qlcnic_83xx_sysfs_flash_write_handler,
};
#ifdef CONFIG_QLCNIC_HWMON
static ssize_t qlcnic_hwmon_show_temp(struct device *dev,
struct device_attribute *dev_attr,
char *buf)
{
struct qlcnic_adapter *adapter = dev_get_drvdata(dev);
unsigned int temperature = 0, value = 0;
if (qlcnic_83xx_check(adapter))
value = QLCRDX(adapter->ahw, QLC_83XX_ASIC_TEMP);
else if (qlcnic_82xx_check(adapter))
value = QLC_SHARED_REG_RD32(adapter, QLCNIC_ASIC_TEMP);
temperature = qlcnic_get_temp_val(value);
/* display millidegree celcius */
temperature *= 1000;
return sprintf(buf, "%u\n", temperature);
}
/* hwmon-sysfs attributes */
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO,
qlcnic_hwmon_show_temp, NULL, 1);
static struct attribute *qlcnic_hwmon_attrs[] = {
&sensor_dev_attr_temp1_input.dev_attr.attr,
NULL
};
ATTRIBUTE_GROUPS(qlcnic_hwmon);
void qlcnic_register_hwmon_dev(struct qlcnic_adapter *adapter)
{
struct device *dev = &adapter->pdev->dev;
struct device *hwmon_dev;
/* Skip hwmon registration for a VF device */
if (qlcnic_sriov_vf_check(adapter)) {
adapter->ahw->hwmon_dev = NULL;
return;
}
hwmon_dev = hwmon_device_register_with_groups(dev, qlcnic_driver_name,
adapter,
qlcnic_hwmon_groups);
if (IS_ERR(hwmon_dev)) {
dev_err(dev, "Cannot register with hwmon, err=%ld\n",
PTR_ERR(hwmon_dev));
hwmon_dev = NULL;
}
adapter->ahw->hwmon_dev = hwmon_dev;
}
void qlcnic_unregister_hwmon_dev(struct qlcnic_adapter *adapter)
{
struct device *hwmon_dev = adapter->ahw->hwmon_dev;
if (hwmon_dev) {
hwmon_device_unregister(hwmon_dev);
adapter->ahw->hwmon_dev = NULL;
}
}
#endif
void qlcnic_create_sysfs_entries(struct qlcnic_adapter *adapter)
{
struct device *dev = &adapter->pdev->dev;
if (adapter->ahw->capabilities & QLCNIC_FW_CAPABILITY_BDG)
if (device_create_file(dev, &dev_attr_bridged_mode))
dev_warn(dev,
"failed to create bridged_mode sysfs entry\n");
}
void qlcnic_remove_sysfs_entries(struct qlcnic_adapter *adapter)
{
struct device *dev = &adapter->pdev->dev;
if (adapter->ahw->capabilities & QLCNIC_FW_CAPABILITY_BDG)
device_remove_file(dev, &dev_attr_bridged_mode);
}
static void qlcnic_create_diag_entries(struct qlcnic_adapter *adapter)
{
struct device *dev = &adapter->pdev->dev;
if (device_create_bin_file(dev, &bin_attr_port_stats))
dev_info(dev, "failed to create port stats sysfs entry");
if (adapter->ahw->op_mode == QLCNIC_NON_PRIV_FUNC)
return;
if (device_create_file(dev, &dev_attr_diag_mode))
dev_info(dev, "failed to create diag_mode sysfs entry\n");
if (device_create_bin_file(dev, &bin_attr_crb))
dev_info(dev, "failed to create crb sysfs entry\n");
if (device_create_bin_file(dev, &bin_attr_mem))
dev_info(dev, "failed to create mem sysfs entry\n");
if (test_bit(__QLCNIC_MAINTENANCE_MODE, &adapter->state))
return;
if (device_create_bin_file(dev, &bin_attr_pci_config))
dev_info(dev, "failed to create pci config sysfs entry");
if (device_create_file(dev, &dev_attr_beacon))
dev_info(dev, "failed to create beacon sysfs entry");
if (!(adapter->flags & QLCNIC_ESWITCH_ENABLED))
return;
if (device_create_bin_file(dev, &bin_attr_esw_config))
dev_info(dev, "failed to create esw config sysfs entry");
if (adapter->ahw->op_mode != QLCNIC_MGMT_FUNC)
return;
if (device_create_bin_file(dev, &bin_attr_npar_config))
dev_info(dev, "failed to create npar config sysfs entry");
if (device_create_bin_file(dev, &bin_attr_pm_config))
dev_info(dev, "failed to create pm config sysfs entry");
if (device_create_bin_file(dev, &bin_attr_esw_stats))
dev_info(dev, "failed to create eswitch stats sysfs entry");
}
static void qlcnic_remove_diag_entries(struct qlcnic_adapter *adapter)
{
struct device *dev = &adapter->pdev->dev;
device_remove_bin_file(dev, &bin_attr_port_stats);
if (adapter->ahw->op_mode == QLCNIC_NON_PRIV_FUNC)
return;
device_remove_file(dev, &dev_attr_diag_mode);
device_remove_bin_file(dev, &bin_attr_crb);
device_remove_bin_file(dev, &bin_attr_mem);
if (test_bit(__QLCNIC_MAINTENANCE_MODE, &adapter->state))
return;
device_remove_bin_file(dev, &bin_attr_pci_config);
device_remove_file(dev, &dev_attr_beacon);
if (!(adapter->flags & QLCNIC_ESWITCH_ENABLED))
return;
device_remove_bin_file(dev, &bin_attr_esw_config);
if (adapter->ahw->op_mode != QLCNIC_MGMT_FUNC)
return;
device_remove_bin_file(dev, &bin_attr_npar_config);
device_remove_bin_file(dev, &bin_attr_pm_config);
device_remove_bin_file(dev, &bin_attr_esw_stats);
}
void qlcnic_82xx_add_sysfs(struct qlcnic_adapter *adapter)
{
qlcnic_create_diag_entries(adapter);
}
void qlcnic_82xx_remove_sysfs(struct qlcnic_adapter *adapter)
{
qlcnic_remove_diag_entries(adapter);
}
void qlcnic_83xx_add_sysfs(struct qlcnic_adapter *adapter)
{
struct device *dev = &adapter->pdev->dev;
qlcnic_create_diag_entries(adapter);
if (sysfs_create_bin_file(&dev->kobj, &bin_attr_flash))
dev_info(dev, "failed to create flash sysfs entry\n");
}
void qlcnic_83xx_remove_sysfs(struct qlcnic_adapter *adapter)
{
struct device *dev = &adapter->pdev->dev;
qlcnic_remove_diag_entries(adapter);
sysfs_remove_bin_file(&dev->kobj, &bin_attr_flash);
}
| gpl-2.0 |
invisiblek/android_kernel_lge_msm8610 | drivers/pci/pci-driver.c | 2431 | 30907 | /*
* drivers/pci/pci-driver.c
*
* (C) Copyright 2002-2004, 2007 Greg Kroah-Hartman <greg@kroah.com>
* (C) Copyright 2007 Novell Inc.
*
* Released under the GPL v2 only.
*
*/
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/mempolicy.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/cpu.h>
#include <linux/pm_runtime.h>
#include <linux/suspend.h>
#include "pci.h"
struct pci_dynid {
struct list_head node;
struct pci_device_id id;
};
/**
* pci_add_dynid - add a new PCI device ID to this driver and re-probe devices
* @drv: target pci driver
* @vendor: PCI vendor ID
* @device: PCI device ID
* @subvendor: PCI subvendor ID
* @subdevice: PCI subdevice ID
* @class: PCI class
* @class_mask: PCI class mask
* @driver_data: private driver data
*
* Adds a new dynamic pci device ID to this driver and causes the
* driver to probe for all devices again. @drv must have been
* registered prior to calling this function.
*
* CONTEXT:
* Does GFP_KERNEL allocation.
*
* RETURNS:
* 0 on success, -errno on failure.
*/
int pci_add_dynid(struct pci_driver *drv,
unsigned int vendor, unsigned int device,
unsigned int subvendor, unsigned int subdevice,
unsigned int class, unsigned int class_mask,
unsigned long driver_data)
{
struct pci_dynid *dynid;
int retval;
dynid = kzalloc(sizeof(*dynid), GFP_KERNEL);
if (!dynid)
return -ENOMEM;
dynid->id.vendor = vendor;
dynid->id.device = device;
dynid->id.subvendor = subvendor;
dynid->id.subdevice = subdevice;
dynid->id.class = class;
dynid->id.class_mask = class_mask;
dynid->id.driver_data = driver_data;
spin_lock(&drv->dynids.lock);
list_add_tail(&dynid->node, &drv->dynids.list);
spin_unlock(&drv->dynids.lock);
retval = driver_attach(&drv->driver);
return retval;
}
static void pci_free_dynids(struct pci_driver *drv)
{
struct pci_dynid *dynid, *n;
spin_lock(&drv->dynids.lock);
list_for_each_entry_safe(dynid, n, &drv->dynids.list, node) {
list_del(&dynid->node);
kfree(dynid);
}
spin_unlock(&drv->dynids.lock);
}
/*
* Dynamic device ID manipulation via sysfs is disabled for !CONFIG_HOTPLUG
*/
#ifdef CONFIG_HOTPLUG
/**
* store_new_id - sysfs frontend to pci_add_dynid()
* @driver: target device driver
* @buf: buffer for scanning device ID data
* @count: input size
*
* Allow PCI IDs to be added to an existing driver via sysfs.
*/
static ssize_t
store_new_id(struct device_driver *driver, const char *buf, size_t count)
{
struct pci_driver *pdrv = to_pci_driver(driver);
const struct pci_device_id *ids = pdrv->id_table;
__u32 vendor, device, subvendor=PCI_ANY_ID,
subdevice=PCI_ANY_ID, class=0, class_mask=0;
unsigned long driver_data=0;
int fields=0;
int retval;
fields = sscanf(buf, "%x %x %x %x %x %x %lx",
&vendor, &device, &subvendor, &subdevice,
&class, &class_mask, &driver_data);
if (fields < 2)
return -EINVAL;
/* Only accept driver_data values that match an existing id_table
entry */
if (ids) {
retval = -EINVAL;
while (ids->vendor || ids->subvendor || ids->class_mask) {
if (driver_data == ids->driver_data) {
retval = 0;
break;
}
ids++;
}
if (retval) /* No match */
return retval;
}
retval = pci_add_dynid(pdrv, vendor, device, subvendor, subdevice,
class, class_mask, driver_data);
if (retval)
return retval;
return count;
}
static DRIVER_ATTR(new_id, S_IWUSR, NULL, store_new_id);
/**
* store_remove_id - remove a PCI device ID from this driver
* @driver: target device driver
* @buf: buffer for scanning device ID data
* @count: input size
*
* Removes a dynamic pci device ID to this driver.
*/
static ssize_t
store_remove_id(struct device_driver *driver, const char *buf, size_t count)
{
struct pci_dynid *dynid, *n;
struct pci_driver *pdrv = to_pci_driver(driver);
__u32 vendor, device, subvendor = PCI_ANY_ID,
subdevice = PCI_ANY_ID, class = 0, class_mask = 0;
int fields = 0;
int retval = -ENODEV;
fields = sscanf(buf, "%x %x %x %x %x %x",
&vendor, &device, &subvendor, &subdevice,
&class, &class_mask);
if (fields < 2)
return -EINVAL;
spin_lock(&pdrv->dynids.lock);
list_for_each_entry_safe(dynid, n, &pdrv->dynids.list, node) {
struct pci_device_id *id = &dynid->id;
if ((id->vendor == vendor) &&
(id->device == device) &&
(subvendor == PCI_ANY_ID || id->subvendor == subvendor) &&
(subdevice == PCI_ANY_ID || id->subdevice == subdevice) &&
!((id->class ^ class) & class_mask)) {
list_del(&dynid->node);
kfree(dynid);
retval = 0;
break;
}
}
spin_unlock(&pdrv->dynids.lock);
if (retval)
return retval;
return count;
}
static DRIVER_ATTR(remove_id, S_IWUSR, NULL, store_remove_id);
static int
pci_create_newid_files(struct pci_driver *drv)
{
int error = 0;
if (drv->probe != NULL) {
error = driver_create_file(&drv->driver, &driver_attr_new_id);
if (error == 0) {
error = driver_create_file(&drv->driver,
&driver_attr_remove_id);
if (error)
driver_remove_file(&drv->driver,
&driver_attr_new_id);
}
}
return error;
}
static void pci_remove_newid_files(struct pci_driver *drv)
{
driver_remove_file(&drv->driver, &driver_attr_remove_id);
driver_remove_file(&drv->driver, &driver_attr_new_id);
}
#else /* !CONFIG_HOTPLUG */
static inline int pci_create_newid_files(struct pci_driver *drv)
{
return 0;
}
static inline void pci_remove_newid_files(struct pci_driver *drv) {}
#endif
/**
* pci_match_id - See if a pci device matches a given pci_id table
* @ids: array of PCI device id structures to search in
* @dev: the PCI device structure to match against.
*
* Used by a driver to check whether a PCI device present in the
* system is in its list of supported devices. Returns the matching
* pci_device_id structure or %NULL if there is no match.
*
* Deprecated, don't use this as it will not catch any dynamic ids
* that a driver might want to check for.
*/
const struct pci_device_id *pci_match_id(const struct pci_device_id *ids,
struct pci_dev *dev)
{
if (ids) {
while (ids->vendor || ids->subvendor || ids->class_mask) {
if (pci_match_one_device(ids, dev))
return ids;
ids++;
}
}
return NULL;
}
/**
* pci_match_device - Tell if a PCI device structure has a matching PCI device id structure
* @drv: the PCI driver to match against
* @dev: the PCI device structure to match against
*
* Used by a driver to check whether a PCI device present in the
* system is in its list of supported devices. Returns the matching
* pci_device_id structure or %NULL if there is no match.
*/
static const struct pci_device_id *pci_match_device(struct pci_driver *drv,
struct pci_dev *dev)
{
struct pci_dynid *dynid;
/* Look at the dynamic ids first, before the static ones */
spin_lock(&drv->dynids.lock);
list_for_each_entry(dynid, &drv->dynids.list, node) {
if (pci_match_one_device(&dynid->id, dev)) {
spin_unlock(&drv->dynids.lock);
return &dynid->id;
}
}
spin_unlock(&drv->dynids.lock);
return pci_match_id(drv->id_table, dev);
}
struct drv_dev_and_id {
struct pci_driver *drv;
struct pci_dev *dev;
const struct pci_device_id *id;
};
static long local_pci_probe(void *_ddi)
{
struct drv_dev_and_id *ddi = _ddi;
struct device *dev = &ddi->dev->dev;
int rc;
/* Unbound PCI devices are always set to disabled and suspended.
* During probe, the device is set to enabled and active and the
* usage count is incremented. If the driver supports runtime PM,
* it should call pm_runtime_put_noidle() in its probe routine and
* pm_runtime_get_noresume() in its remove routine.
*/
pm_runtime_get_noresume(dev);
pm_runtime_set_active(dev);
pm_runtime_enable(dev);
rc = ddi->drv->probe(ddi->dev, ddi->id);
if (rc) {
pm_runtime_disable(dev);
pm_runtime_set_suspended(dev);
pm_runtime_put_noidle(dev);
}
return rc;
}
static int pci_call_probe(struct pci_driver *drv, struct pci_dev *dev,
const struct pci_device_id *id)
{
int error, node;
struct drv_dev_and_id ddi = { drv, dev, id };
/* Execute driver initialization on node where the device's
bus is attached to. This way the driver likely allocates
its local memory on the right node without any need to
change it. */
node = dev_to_node(&dev->dev);
if (node >= 0) {
int cpu;
get_online_cpus();
cpu = cpumask_any_and(cpumask_of_node(node), cpu_online_mask);
if (cpu < nr_cpu_ids)
error = work_on_cpu(cpu, local_pci_probe, &ddi);
else
error = local_pci_probe(&ddi);
put_online_cpus();
} else
error = local_pci_probe(&ddi);
return error;
}
/**
* __pci_device_probe - check if a driver wants to claim a specific PCI device
* @drv: driver to call to check if it wants the PCI device
* @pci_dev: PCI device being probed
*
* returns 0 on success, else error.
* side-effect: pci_dev->driver is set to drv when drv claims pci_dev.
*/
static int
__pci_device_probe(struct pci_driver *drv, struct pci_dev *pci_dev)
{
const struct pci_device_id *id;
int error = 0;
if (!pci_dev->driver && drv->probe) {
error = -ENODEV;
id = pci_match_device(drv, pci_dev);
if (id)
error = pci_call_probe(drv, pci_dev, id);
if (error >= 0) {
pci_dev->driver = drv;
error = 0;
}
}
return error;
}
static int pci_device_probe(struct device * dev)
{
int error = 0;
struct pci_driver *drv;
struct pci_dev *pci_dev;
drv = to_pci_driver(dev->driver);
pci_dev = to_pci_dev(dev);
pci_dev_get(pci_dev);
error = __pci_device_probe(drv, pci_dev);
if (error)
pci_dev_put(pci_dev);
return error;
}
static int pci_device_remove(struct device * dev)
{
struct pci_dev * pci_dev = to_pci_dev(dev);
struct pci_driver * drv = pci_dev->driver;
if (drv) {
if (drv->remove) {
pm_runtime_get_sync(dev);
drv->remove(pci_dev);
pm_runtime_put_noidle(dev);
}
pci_dev->driver = NULL;
}
/* Undo the runtime PM settings in local_pci_probe() */
pm_runtime_disable(dev);
pm_runtime_set_suspended(dev);
pm_runtime_put_noidle(dev);
/*
* If the device is still on, set the power state as "unknown",
* since it might change by the next time we load the driver.
*/
if (pci_dev->current_state == PCI_D0)
pci_dev->current_state = PCI_UNKNOWN;
/*
* We would love to complain here if pci_dev->is_enabled is set, that
* the driver should have called pci_disable_device(), but the
* unfortunate fact is there are too many odd BIOS and bridge setups
* that don't like drivers doing that all of the time.
* Oh well, we can dream of sane hardware when we sleep, no matter how
* horrible the crap we have to deal with is when we are awake...
*/
pci_dev_put(pci_dev);
return 0;
}
static void pci_device_shutdown(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct pci_driver *drv = pci_dev->driver;
if (drv && drv->shutdown)
drv->shutdown(pci_dev);
pci_msi_shutdown(pci_dev);
pci_msix_shutdown(pci_dev);
/*
* Devices may be enabled to wake up by runtime PM, but they need not
* be supposed to wake up the system from its "power off" state (e.g.
* ACPI S5). Therefore disable wakeup for all devices that aren't
* supposed to wake up the system at this point. The state argument
* will be ignored by pci_enable_wake().
*/
if (!device_may_wakeup(dev))
pci_enable_wake(pci_dev, PCI_UNKNOWN, false);
}
#ifdef CONFIG_PM
/* Auxiliary functions used for system resume and run-time resume. */
/**
* pci_restore_standard_config - restore standard config registers of PCI device
* @pci_dev: PCI device to handle
*/
static int pci_restore_standard_config(struct pci_dev *pci_dev)
{
pci_update_current_state(pci_dev, PCI_UNKNOWN);
if (pci_dev->current_state != PCI_D0) {
int error = pci_set_power_state(pci_dev, PCI_D0);
if (error)
return error;
}
pci_restore_state(pci_dev);
return 0;
}
static void pci_pm_default_resume_early(struct pci_dev *pci_dev)
{
pci_restore_standard_config(pci_dev);
pci_fixup_device(pci_fixup_resume_early, pci_dev);
}
#endif
#ifdef CONFIG_PM_SLEEP
/*
* Default "suspend" method for devices that have no driver provided suspend,
* or not even a driver at all (second part).
*/
static void pci_pm_set_unknown_state(struct pci_dev *pci_dev)
{
/*
* mark its power state as "unknown", since we don't know if
* e.g. the BIOS will change its device state when we suspend.
*/
if (pci_dev->current_state == PCI_D0)
pci_dev->current_state = PCI_UNKNOWN;
}
/*
* Default "resume" method for devices that have no driver provided resume,
* or not even a driver at all (second part).
*/
static int pci_pm_reenable_device(struct pci_dev *pci_dev)
{
int retval;
/* if the device was enabled before suspend, reenable */
retval = pci_reenable_device(pci_dev);
/*
* if the device was busmaster before the suspend, make it busmaster
* again
*/
if (pci_dev->is_busmaster)
pci_set_master(pci_dev);
return retval;
}
static int pci_legacy_suspend(struct device *dev, pm_message_t state)
{
struct pci_dev * pci_dev = to_pci_dev(dev);
struct pci_driver * drv = pci_dev->driver;
if (drv && drv->suspend) {
pci_power_t prev = pci_dev->current_state;
int error;
error = drv->suspend(pci_dev, state);
suspend_report_result(drv->suspend, error);
if (error)
return error;
if (!pci_dev->state_saved && pci_dev->current_state != PCI_D0
&& pci_dev->current_state != PCI_UNKNOWN) {
WARN_ONCE(pci_dev->current_state != prev,
"PCI PM: Device state not saved by %pF\n",
drv->suspend);
}
}
pci_fixup_device(pci_fixup_suspend, pci_dev);
return 0;
}
static int pci_legacy_suspend_late(struct device *dev, pm_message_t state)
{
struct pci_dev * pci_dev = to_pci_dev(dev);
struct pci_driver * drv = pci_dev->driver;
if (drv && drv->suspend_late) {
pci_power_t prev = pci_dev->current_state;
int error;
error = drv->suspend_late(pci_dev, state);
suspend_report_result(drv->suspend_late, error);
if (error)
return error;
if (!pci_dev->state_saved && pci_dev->current_state != PCI_D0
&& pci_dev->current_state != PCI_UNKNOWN) {
WARN_ONCE(pci_dev->current_state != prev,
"PCI PM: Device state not saved by %pF\n",
drv->suspend_late);
return 0;
}
}
if (!pci_dev->state_saved)
pci_save_state(pci_dev);
pci_pm_set_unknown_state(pci_dev);
return 0;
}
static int pci_legacy_resume_early(struct device *dev)
{
struct pci_dev * pci_dev = to_pci_dev(dev);
struct pci_driver * drv = pci_dev->driver;
return drv && drv->resume_early ?
drv->resume_early(pci_dev) : 0;
}
static int pci_legacy_resume(struct device *dev)
{
struct pci_dev * pci_dev = to_pci_dev(dev);
struct pci_driver * drv = pci_dev->driver;
pci_fixup_device(pci_fixup_resume, pci_dev);
return drv && drv->resume ?
drv->resume(pci_dev) : pci_pm_reenable_device(pci_dev);
}
/* Auxiliary functions used by the new power management framework */
static void pci_pm_default_resume(struct pci_dev *pci_dev)
{
pci_fixup_device(pci_fixup_resume, pci_dev);
if (!pci_is_bridge(pci_dev))
pci_enable_wake(pci_dev, PCI_D0, false);
}
static void pci_pm_default_suspend(struct pci_dev *pci_dev)
{
/* Disable non-bridge devices without PM support */
if (!pci_is_bridge(pci_dev))
pci_disable_enabled_device(pci_dev);
}
static bool pci_has_legacy_pm_support(struct pci_dev *pci_dev)
{
struct pci_driver *drv = pci_dev->driver;
bool ret = drv && (drv->suspend || drv->suspend_late || drv->resume
|| drv->resume_early);
/*
* Legacy PM support is used by default, so warn if the new framework is
* supported as well. Drivers are supposed to support either the
* former, or the latter, but not both at the same time.
*/
WARN(ret && drv->driver.pm, "driver %s device %04x:%04x\n",
drv->name, pci_dev->vendor, pci_dev->device);
return ret;
}
/* New power management framework */
static int pci_pm_prepare(struct device *dev)
{
struct device_driver *drv = dev->driver;
int error = 0;
/*
* PCI devices suspended at run time need to be resumed at this
* point, because in general it is necessary to reconfigure them for
* system suspend. Namely, if the device is supposed to wake up the
* system from the sleep state, we may need to reconfigure it for this
* purpose. In turn, if the device is not supposed to wake up the
* system from the sleep state, we'll have to prevent it from signaling
* wake-up.
*/
pm_runtime_resume(dev);
if (drv && drv->pm && drv->pm->prepare)
error = drv->pm->prepare(dev);
return error;
}
static void pci_pm_complete(struct device *dev)
{
struct device_driver *drv = dev->driver;
if (drv && drv->pm && drv->pm->complete)
drv->pm->complete(dev);
}
#else /* !CONFIG_PM_SLEEP */
#define pci_pm_prepare NULL
#define pci_pm_complete NULL
#endif /* !CONFIG_PM_SLEEP */
#ifdef CONFIG_SUSPEND
static int pci_pm_suspend(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_suspend(dev, PMSG_SUSPEND);
if (!pm) {
pci_pm_default_suspend(pci_dev);
goto Fixup;
}
if (pm->suspend) {
pci_power_t prev = pci_dev->current_state;
int error;
error = pm->suspend(dev);
suspend_report_result(pm->suspend, error);
if (error)
return error;
if (!pci_dev->state_saved && pci_dev->current_state != PCI_D0
&& pci_dev->current_state != PCI_UNKNOWN) {
WARN_ONCE(pci_dev->current_state != prev,
"PCI PM: State of device not saved by %pF\n",
pm->suspend);
}
}
Fixup:
pci_fixup_device(pci_fixup_suspend, pci_dev);
return 0;
}
static int pci_pm_suspend_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_suspend_late(dev, PMSG_SUSPEND);
if (!pm) {
pci_save_state(pci_dev);
return 0;
}
if (pm->suspend_noirq) {
pci_power_t prev = pci_dev->current_state;
int error;
error = pm->suspend_noirq(dev);
suspend_report_result(pm->suspend_noirq, error);
if (error)
return error;
if (!pci_dev->state_saved && pci_dev->current_state != PCI_D0
&& pci_dev->current_state != PCI_UNKNOWN) {
WARN_ONCE(pci_dev->current_state != prev,
"PCI PM: State of device not saved by %pF\n",
pm->suspend_noirq);
return 0;
}
}
if (!pci_dev->state_saved) {
pci_save_state(pci_dev);
if (!pci_is_bridge(pci_dev))
pci_prepare_to_sleep(pci_dev);
}
pci_pm_set_unknown_state(pci_dev);
return 0;
}
static int pci_pm_resume_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct device_driver *drv = dev->driver;
int error = 0;
pci_pm_default_resume_early(pci_dev);
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_resume_early(dev);
if (drv && drv->pm && drv->pm->resume_noirq)
error = drv->pm->resume_noirq(dev);
return error;
}
static int pci_pm_resume(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
int error = 0;
/*
* This is necessary for the suspend error path in which resume is
* called without restoring the standard config registers of the device.
*/
if (pci_dev->state_saved)
pci_restore_standard_config(pci_dev);
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_resume(dev);
pci_pm_default_resume(pci_dev);
if (pm) {
if (pm->resume)
error = pm->resume(dev);
} else {
pci_pm_reenable_device(pci_dev);
}
return error;
}
#else /* !CONFIG_SUSPEND */
#define pci_pm_suspend NULL
#define pci_pm_suspend_noirq NULL
#define pci_pm_resume NULL
#define pci_pm_resume_noirq NULL
#endif /* !CONFIG_SUSPEND */
#ifdef CONFIG_HIBERNATE_CALLBACKS
static int pci_pm_freeze(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_suspend(dev, PMSG_FREEZE);
if (!pm) {
pci_pm_default_suspend(pci_dev);
return 0;
}
if (pm->freeze) {
int error;
error = pm->freeze(dev);
suspend_report_result(pm->freeze, error);
if (error)
return error;
}
return 0;
}
static int pci_pm_freeze_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct device_driver *drv = dev->driver;
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_suspend_late(dev, PMSG_FREEZE);
if (drv && drv->pm && drv->pm->freeze_noirq) {
int error;
error = drv->pm->freeze_noirq(dev);
suspend_report_result(drv->pm->freeze_noirq, error);
if (error)
return error;
}
if (!pci_dev->state_saved)
pci_save_state(pci_dev);
pci_pm_set_unknown_state(pci_dev);
return 0;
}
static int pci_pm_thaw_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct device_driver *drv = dev->driver;
int error = 0;
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_resume_early(dev);
pci_update_current_state(pci_dev, PCI_D0);
if (drv && drv->pm && drv->pm->thaw_noirq)
error = drv->pm->thaw_noirq(dev);
return error;
}
static int pci_pm_thaw(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
int error = 0;
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_resume(dev);
if (pm) {
if (pm->thaw)
error = pm->thaw(dev);
} else {
pci_pm_reenable_device(pci_dev);
}
pci_dev->state_saved = false;
return error;
}
static int pci_pm_poweroff(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_suspend(dev, PMSG_HIBERNATE);
if (!pm) {
pci_pm_default_suspend(pci_dev);
goto Fixup;
}
if (pm->poweroff) {
int error;
error = pm->poweroff(dev);
suspend_report_result(pm->poweroff, error);
if (error)
return error;
}
Fixup:
pci_fixup_device(pci_fixup_suspend, pci_dev);
return 0;
}
static int pci_pm_poweroff_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct device_driver *drv = dev->driver;
if (pci_has_legacy_pm_support(to_pci_dev(dev)))
return pci_legacy_suspend_late(dev, PMSG_HIBERNATE);
if (!drv || !drv->pm)
return 0;
if (drv->pm->poweroff_noirq) {
int error;
error = drv->pm->poweroff_noirq(dev);
suspend_report_result(drv->pm->poweroff_noirq, error);
if (error)
return error;
}
if (!pci_dev->state_saved && !pci_is_bridge(pci_dev))
pci_prepare_to_sleep(pci_dev);
return 0;
}
static int pci_pm_restore_noirq(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct device_driver *drv = dev->driver;
int error = 0;
pci_pm_default_resume_early(pci_dev);
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_resume_early(dev);
if (drv && drv->pm && drv->pm->restore_noirq)
error = drv->pm->restore_noirq(dev);
return error;
}
static int pci_pm_restore(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
int error = 0;
/*
* This is necessary for the hibernation error path in which restore is
* called without restoring the standard config registers of the device.
*/
if (pci_dev->state_saved)
pci_restore_standard_config(pci_dev);
if (pci_has_legacy_pm_support(pci_dev))
return pci_legacy_resume(dev);
pci_pm_default_resume(pci_dev);
if (pm) {
if (pm->restore)
error = pm->restore(dev);
} else {
pci_pm_reenable_device(pci_dev);
}
return error;
}
#else /* !CONFIG_HIBERNATE_CALLBACKS */
#define pci_pm_freeze NULL
#define pci_pm_freeze_noirq NULL
#define pci_pm_thaw NULL
#define pci_pm_thaw_noirq NULL
#define pci_pm_poweroff NULL
#define pci_pm_poweroff_noirq NULL
#define pci_pm_restore NULL
#define pci_pm_restore_noirq NULL
#endif /* !CONFIG_HIBERNATE_CALLBACKS */
#ifdef CONFIG_PM_RUNTIME
static int pci_pm_runtime_suspend(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
pci_power_t prev = pci_dev->current_state;
int error;
if (!pm || !pm->runtime_suspend)
return -ENOSYS;
error = pm->runtime_suspend(dev);
suspend_report_result(pm->runtime_suspend, error);
if (error)
return error;
pci_fixup_device(pci_fixup_suspend, pci_dev);
if (!pci_dev->state_saved && pci_dev->current_state != PCI_D0
&& pci_dev->current_state != PCI_UNKNOWN) {
WARN_ONCE(pci_dev->current_state != prev,
"PCI PM: State of device not saved by %pF\n",
pm->runtime_suspend);
return 0;
}
if (!pci_dev->state_saved)
pci_save_state(pci_dev);
pci_finish_runtime_suspend(pci_dev);
return 0;
}
static int pci_pm_runtime_resume(struct device *dev)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
if (!pm || !pm->runtime_resume)
return -ENOSYS;
pci_pm_default_resume_early(pci_dev);
__pci_enable_wake(pci_dev, PCI_D0, true, false);
pci_fixup_device(pci_fixup_resume, pci_dev);
return pm->runtime_resume(dev);
}
static int pci_pm_runtime_idle(struct device *dev)
{
const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
if (!pm)
return -ENOSYS;
if (pm->runtime_idle) {
int ret = pm->runtime_idle(dev);
if (ret)
return ret;
}
pm_runtime_suspend(dev);
return 0;
}
#else /* !CONFIG_PM_RUNTIME */
#define pci_pm_runtime_suspend NULL
#define pci_pm_runtime_resume NULL
#define pci_pm_runtime_idle NULL
#endif /* !CONFIG_PM_RUNTIME */
#ifdef CONFIG_PM
const struct dev_pm_ops pci_dev_pm_ops = {
.prepare = pci_pm_prepare,
.complete = pci_pm_complete,
.suspend = pci_pm_suspend,
.resume = pci_pm_resume,
.freeze = pci_pm_freeze,
.thaw = pci_pm_thaw,
.poweroff = pci_pm_poweroff,
.restore = pci_pm_restore,
.suspend_noirq = pci_pm_suspend_noirq,
.resume_noirq = pci_pm_resume_noirq,
.freeze_noirq = pci_pm_freeze_noirq,
.thaw_noirq = pci_pm_thaw_noirq,
.poweroff_noirq = pci_pm_poweroff_noirq,
.restore_noirq = pci_pm_restore_noirq,
.runtime_suspend = pci_pm_runtime_suspend,
.runtime_resume = pci_pm_runtime_resume,
.runtime_idle = pci_pm_runtime_idle,
};
#define PCI_PM_OPS_PTR (&pci_dev_pm_ops)
#else /* !COMFIG_PM_OPS */
#define PCI_PM_OPS_PTR NULL
#endif /* !COMFIG_PM_OPS */
/**
* __pci_register_driver - register a new pci driver
* @drv: the driver structure to register
* @owner: owner module of drv
* @mod_name: module name string
*
* Adds the driver structure to the list of registered drivers.
* Returns a negative value on error, otherwise 0.
* If no error occurred, the driver remains registered even if
* no device was claimed during registration.
*/
int __pci_register_driver(struct pci_driver *drv, struct module *owner,
const char *mod_name)
{
int error;
/* initialize common driver fields */
drv->driver.name = drv->name;
drv->driver.bus = &pci_bus_type;
drv->driver.owner = owner;
drv->driver.mod_name = mod_name;
spin_lock_init(&drv->dynids.lock);
INIT_LIST_HEAD(&drv->dynids.list);
/* register with core */
error = driver_register(&drv->driver);
if (error)
goto out;
error = pci_create_newid_files(drv);
if (error)
goto out_newid;
out:
return error;
out_newid:
driver_unregister(&drv->driver);
goto out;
}
/**
* pci_unregister_driver - unregister a pci driver
* @drv: the driver structure to unregister
*
* Deletes the driver structure from the list of registered PCI drivers,
* gives it a chance to clean up by calling its remove() function for
* each device it was responsible for, and marks those devices as
* driverless.
*/
void
pci_unregister_driver(struct pci_driver *drv)
{
pci_remove_newid_files(drv);
driver_unregister(&drv->driver);
pci_free_dynids(drv);
}
static struct pci_driver pci_compat_driver = {
.name = "compat"
};
/**
* pci_dev_driver - get the pci_driver of a device
* @dev: the device to query
*
* Returns the appropriate pci_driver structure or %NULL if there is no
* registered driver for the device.
*/
struct pci_driver *
pci_dev_driver(const struct pci_dev *dev)
{
if (dev->driver)
return dev->driver;
else {
int i;
for(i=0; i<=PCI_ROM_RESOURCE; i++)
if (dev->resource[i].flags & IORESOURCE_BUSY)
return &pci_compat_driver;
}
return NULL;
}
/**
* pci_bus_match - Tell if a PCI device structure has a matching PCI device id structure
* @dev: the PCI device structure to match against
* @drv: the device driver to search for matching PCI device id structures
*
* Used by a driver to check whether a PCI device present in the
* system is in its list of supported devices. Returns the matching
* pci_device_id structure or %NULL if there is no match.
*/
static int pci_bus_match(struct device *dev, struct device_driver *drv)
{
struct pci_dev *pci_dev = to_pci_dev(dev);
struct pci_driver *pci_drv = to_pci_driver(drv);
const struct pci_device_id *found_id;
found_id = pci_match_device(pci_drv, pci_dev);
if (found_id)
return 1;
return 0;
}
/**
* pci_dev_get - increments the reference count of the pci device structure
* @dev: the device being referenced
*
* Each live reference to a device should be refcounted.
*
* Drivers for PCI devices should normally record such references in
* their probe() methods, when they bind to a device, and release
* them by calling pci_dev_put(), in their disconnect() methods.
*
* A pointer to the device with the incremented reference counter is returned.
*/
struct pci_dev *pci_dev_get(struct pci_dev *dev)
{
if (dev)
get_device(&dev->dev);
return dev;
}
/**
* pci_dev_put - release a use of the pci device structure
* @dev: device that's been disconnected
*
* Must be called when a user of a device is finished with it. When the last
* user of the device calls this function, the memory of the device is freed.
*/
void pci_dev_put(struct pci_dev *dev)
{
if (dev)
put_device(&dev->dev);
}
#ifndef CONFIG_HOTPLUG
int pci_uevent(struct device *dev, struct kobj_uevent_env *env)
{
return -ENODEV;
}
#endif
struct bus_type pci_bus_type = {
.name = "pci",
.match = pci_bus_match,
.uevent = pci_uevent,
.probe = pci_device_probe,
.remove = pci_device_remove,
.shutdown = pci_device_shutdown,
.dev_attrs = pci_dev_attrs,
.bus_attrs = pci_bus_attrs,
.pm = PCI_PM_OPS_PTR,
};
static int __init pci_driver_init(void)
{
return bus_register(&pci_bus_type);
}
postcore_initcall(pci_driver_init);
EXPORT_SYMBOL_GPL(pci_add_dynid);
EXPORT_SYMBOL(pci_match_id);
EXPORT_SYMBOL(__pci_register_driver);
EXPORT_SYMBOL(pci_unregister_driver);
EXPORT_SYMBOL(pci_dev_driver);
EXPORT_SYMBOL(pci_bus_type);
EXPORT_SYMBOL(pci_dev_get);
EXPORT_SYMBOL(pci_dev_put);
| gpl-2.0 |
chucktr/vigor_aosp_kernel | drivers/media/radio/radio-rtrack2.c | 2687 | 7785 | /* RadioTrack II driver for Linux radio support (C) 1998 Ben Pfaff
*
* Based on RadioTrack I/RadioReveal (C) 1997 M. Kirkwood
* Converted to new API by Alan Cox <alan@lxorguk.ukuu.org.uk>
* Various bugfixes and enhancements by Russell Kroll <rkroll@exploits.org>
*
* TODO: Allow for more than one of these foolish entities :-)
*
* Converted to V4L2 API by Mauro Carvalho Chehab <mchehab@infradead.org>
*/
#include <linux/module.h> /* Modules */
#include <linux/init.h> /* Initdata */
#include <linux/ioport.h> /* request_region */
#include <linux/delay.h> /* udelay */
#include <linux/videodev2.h> /* kernel radio structs */
#include <linux/mutex.h>
#include <linux/version.h> /* for KERNEL_VERSION MACRO */
#include <linux/io.h> /* outb, outb_p */
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
MODULE_AUTHOR("Ben Pfaff");
MODULE_DESCRIPTION("A driver for the RadioTrack II radio card.");
MODULE_LICENSE("GPL");
#ifndef CONFIG_RADIO_RTRACK2_PORT
#define CONFIG_RADIO_RTRACK2_PORT -1
#endif
static int io = CONFIG_RADIO_RTRACK2_PORT;
static int radio_nr = -1;
module_param(io, int, 0);
MODULE_PARM_DESC(io, "I/O address of the RadioTrack card (0x20c or 0x30c)");
module_param(radio_nr, int, 0);
#define RADIO_VERSION KERNEL_VERSION(0, 0, 2)
struct rtrack2
{
struct v4l2_device v4l2_dev;
struct video_device vdev;
int io;
unsigned long curfreq;
int muted;
struct mutex lock;
};
static struct rtrack2 rtrack2_card;
/* local things */
static void rt_mute(struct rtrack2 *dev)
{
if (dev->muted)
return;
mutex_lock(&dev->lock);
outb(1, dev->io);
mutex_unlock(&dev->lock);
dev->muted = 1;
}
static void rt_unmute(struct rtrack2 *dev)
{
if(dev->muted == 0)
return;
mutex_lock(&dev->lock);
outb(0, dev->io);
mutex_unlock(&dev->lock);
dev->muted = 0;
}
static void zero(struct rtrack2 *dev)
{
outb_p(1, dev->io);
outb_p(3, dev->io);
outb_p(1, dev->io);
}
static void one(struct rtrack2 *dev)
{
outb_p(5, dev->io);
outb_p(7, dev->io);
outb_p(5, dev->io);
}
static int rt_setfreq(struct rtrack2 *dev, unsigned long freq)
{
int i;
mutex_lock(&dev->lock);
dev->curfreq = freq;
freq = freq / 200 + 856;
outb_p(0xc8, dev->io);
outb_p(0xc9, dev->io);
outb_p(0xc9, dev->io);
for (i = 0; i < 10; i++)
zero(dev);
for (i = 14; i >= 0; i--)
if (freq & (1 << i))
one(dev);
else
zero(dev);
outb_p(0xc8, dev->io);
if (!dev->muted)
outb_p(0, dev->io);
mutex_unlock(&dev->lock);
return 0;
}
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *v)
{
strlcpy(v->driver, "radio-rtrack2", sizeof(v->driver));
strlcpy(v->card, "RadioTrack II", sizeof(v->card));
strlcpy(v->bus_info, "ISA", sizeof(v->bus_info));
v->version = RADIO_VERSION;
v->capabilities = V4L2_CAP_TUNER | V4L2_CAP_RADIO;
return 0;
}
static int vidioc_s_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
return v->index ? -EINVAL : 0;
}
static int rt_getsigstr(struct rtrack2 *dev)
{
int sig = 1;
mutex_lock(&dev->lock);
if (inb(dev->io) & 2) /* bit set = no signal present */
sig = 0;
mutex_unlock(&dev->lock);
return sig;
}
static int vidioc_g_tuner(struct file *file, void *priv,
struct v4l2_tuner *v)
{
struct rtrack2 *rt = video_drvdata(file);
if (v->index > 0)
return -EINVAL;
strlcpy(v->name, "FM", sizeof(v->name));
v->type = V4L2_TUNER_RADIO;
v->rangelow = 88 * 16000;
v->rangehigh = 108 * 16000;
v->rxsubchans = V4L2_TUNER_SUB_MONO;
v->capability = V4L2_TUNER_CAP_LOW;
v->audmode = V4L2_TUNER_MODE_MONO;
v->signal = 0xFFFF * rt_getsigstr(rt);
return 0;
}
static int vidioc_s_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct rtrack2 *rt = video_drvdata(file);
if (f->tuner != 0 || f->type != V4L2_TUNER_RADIO)
return -EINVAL;
rt_setfreq(rt, f->frequency);
return 0;
}
static int vidioc_g_frequency(struct file *file, void *priv,
struct v4l2_frequency *f)
{
struct rtrack2 *rt = video_drvdata(file);
if (f->tuner != 0)
return -EINVAL;
f->type = V4L2_TUNER_RADIO;
f->frequency = rt->curfreq;
return 0;
}
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
switch (qc->id) {
case V4L2_CID_AUDIO_MUTE:
return v4l2_ctrl_query_fill(qc, 0, 1, 1, 1);
case V4L2_CID_AUDIO_VOLUME:
return v4l2_ctrl_query_fill(qc, 0, 65535, 65535, 65535);
}
return -EINVAL;
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct rtrack2 *rt = video_drvdata(file);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
ctrl->value = rt->muted;
return 0;
case V4L2_CID_AUDIO_VOLUME:
if (rt->muted)
ctrl->value = 0;
else
ctrl->value = 65535;
return 0;
}
return -EINVAL;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct rtrack2 *rt = video_drvdata(file);
switch (ctrl->id) {
case V4L2_CID_AUDIO_MUTE:
if (ctrl->value)
rt_mute(rt);
else
rt_unmute(rt);
return 0;
case V4L2_CID_AUDIO_VOLUME:
if (ctrl->value)
rt_unmute(rt);
else
rt_mute(rt);
return 0;
}
return -EINVAL;
}
static int vidioc_g_input(struct file *filp, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
static int vidioc_s_input(struct file *filp, void *priv, unsigned int i)
{
return i ? -EINVAL : 0;
}
static int vidioc_g_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
a->index = 0;
strlcpy(a->name, "Radio", sizeof(a->name));
a->capability = V4L2_AUDCAP_STEREO;
return 0;
}
static int vidioc_s_audio(struct file *file, void *priv,
struct v4l2_audio *a)
{
return a->index ? -EINVAL : 0;
}
static const struct v4l2_file_operations rtrack2_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops rtrack2_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_g_tuner = vidioc_g_tuner,
.vidioc_s_tuner = vidioc_s_tuner,
.vidioc_g_frequency = vidioc_g_frequency,
.vidioc_s_frequency = vidioc_s_frequency,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_g_audio = vidioc_g_audio,
.vidioc_s_audio = vidioc_s_audio,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
};
static int __init rtrack2_init(void)
{
struct rtrack2 *dev = &rtrack2_card;
struct v4l2_device *v4l2_dev = &dev->v4l2_dev;
int res;
strlcpy(v4l2_dev->name, "rtrack2", sizeof(v4l2_dev->name));
dev->io = io;
if (dev->io == -1) {
v4l2_err(v4l2_dev, "You must set an I/O address with io=0x20c or io=0x30c\n");
return -EINVAL;
}
if (!request_region(dev->io, 4, "rtrack2")) {
v4l2_err(v4l2_dev, "port 0x%x already in use\n", dev->io);
return -EBUSY;
}
res = v4l2_device_register(NULL, v4l2_dev);
if (res < 0) {
release_region(dev->io, 4);
v4l2_err(v4l2_dev, "Could not register v4l2_device\n");
return res;
}
strlcpy(dev->vdev.name, v4l2_dev->name, sizeof(dev->vdev.name));
dev->vdev.v4l2_dev = v4l2_dev;
dev->vdev.fops = &rtrack2_fops;
dev->vdev.ioctl_ops = &rtrack2_ioctl_ops;
dev->vdev.release = video_device_release_empty;
video_set_drvdata(&dev->vdev, dev);
/* mute card - prevents noisy bootups */
outb(1, dev->io);
dev->muted = 1;
mutex_init(&dev->lock);
if (video_register_device(&dev->vdev, VFL_TYPE_RADIO, radio_nr) < 0) {
v4l2_device_unregister(v4l2_dev);
release_region(dev->io, 4);
return -EINVAL;
}
v4l2_info(v4l2_dev, "AIMSlab Radiotrack II card driver.\n");
return 0;
}
static void __exit rtrack2_exit(void)
{
struct rtrack2 *dev = &rtrack2_card;
video_unregister_device(&dev->vdev);
v4l2_device_unregister(&dev->v4l2_dev);
release_region(dev->io, 4);
}
module_init(rtrack2_init);
module_exit(rtrack2_exit);
| gpl-2.0 |
nspierbundel/amlogic-common | sound/pci/oxygen/virtuoso.c | 2687 | 3166 | /*
* C-Media CMI8788 driver for Asus Xonar cards
*
* Copyright (c) Clemens Ladisch <clemens@ladisch.de>
*
*
* This driver is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2.
*
* This driver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this driver; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/pci.h>
#include <linux/delay.h>
#include <sound/core.h>
#include <sound/initval.h>
#include <sound/pcm.h>
#include "xonar.h"
MODULE_AUTHOR("Clemens Ladisch <clemens@ladisch.de>");
MODULE_DESCRIPTION("Asus Virtuoso driver");
MODULE_LICENSE("GPL v2");
MODULE_SUPPORTED_DEVICE("{{Asus,AV66},{Asus,AV100},{Asus,AV200}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "card index");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "enable card");
static DEFINE_PCI_DEVICE_TABLE(xonar_ids) = {
{ OXYGEN_PCI_SUBID(0x1043, 0x8269) },
{ OXYGEN_PCI_SUBID(0x1043, 0x8275) },
{ OXYGEN_PCI_SUBID(0x1043, 0x82b7) },
{ OXYGEN_PCI_SUBID(0x1043, 0x8314) },
{ OXYGEN_PCI_SUBID(0x1043, 0x8327) },
{ OXYGEN_PCI_SUBID(0x1043, 0x834f) },
{ OXYGEN_PCI_SUBID(0x1043, 0x835c) },
{ OXYGEN_PCI_SUBID(0x1043, 0x835d) },
{ OXYGEN_PCI_SUBID(0x1043, 0x835e) },
{ OXYGEN_PCI_SUBID(0x1043, 0x838e) },
{ OXYGEN_PCI_SUBID_BROKEN_EEPROM },
{ }
};
MODULE_DEVICE_TABLE(pci, xonar_ids);
static int __devinit get_xonar_model(struct oxygen *chip,
const struct pci_device_id *id)
{
if (get_xonar_pcm179x_model(chip, id) >= 0)
return 0;
if (get_xonar_cs43xx_model(chip, id) >= 0)
return 0;
if (get_xonar_wm87x6_model(chip, id) >= 0)
return 0;
return -EINVAL;
}
static int __devinit xonar_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
int err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
++dev;
return -ENOENT;
}
err = oxygen_pci_probe(pci, index[dev], id[dev], THIS_MODULE,
xonar_ids, get_xonar_model);
if (err >= 0)
++dev;
return err;
}
static struct pci_driver xonar_driver = {
.name = "AV200",
.id_table = xonar_ids,
.probe = xonar_probe,
.remove = __devexit_p(oxygen_pci_remove),
#ifdef CONFIG_PM
.suspend = oxygen_pci_suspend,
.resume = oxygen_pci_resume,
#endif
.shutdown = oxygen_pci_shutdown,
};
static int __init alsa_card_xonar_init(void)
{
return pci_register_driver(&xonar_driver);
}
static void __exit alsa_card_xonar_exit(void)
{
pci_unregister_driver(&xonar_driver);
}
module_init(alsa_card_xonar_init)
module_exit(alsa_card_xonar_exit)
| gpl-2.0 |
1N4148/android_kernel_samsung_golden | drivers/media/rc/keymaps/rc-pixelview-mk12.c | 2943 | 2138 | /* rc-pixelview-mk12.h - Keytable for pixelview Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
/*
* Keytable for MK-F12 IR remote provided together with Pixelview
* Ultra Pro Remote Controller. Uses NEC extended format.
*/
static struct rc_map_table pixelview_mk12[] = {
{ 0x866b03, KEY_TUNER }, /* Timeshift */
{ 0x866b1e, KEY_POWER2 }, /* power */
{ 0x866b01, KEY_1 },
{ 0x866b0b, KEY_2 },
{ 0x866b1b, KEY_3 },
{ 0x866b05, KEY_4 },
{ 0x866b09, KEY_5 },
{ 0x866b15, KEY_6 },
{ 0x866b06, KEY_7 },
{ 0x866b0a, KEY_8 },
{ 0x866b12, KEY_9 },
{ 0x866b02, KEY_0 },
{ 0x866b13, KEY_AGAIN }, /* loop */
{ 0x866b10, KEY_DIGITS }, /* +100 */
{ 0x866b00, KEY_VIDEO }, /* source */
{ 0x866b18, KEY_MUTE }, /* mute */
{ 0x866b19, KEY_CAMERA }, /* snapshot */
{ 0x866b1a, KEY_SEARCH }, /* scan */
{ 0x866b16, KEY_CHANNELUP }, /* chn + */
{ 0x866b14, KEY_CHANNELDOWN }, /* chn - */
{ 0x866b1f, KEY_VOLUMEUP }, /* vol + */
{ 0x866b17, KEY_VOLUMEDOWN }, /* vol - */
{ 0x866b1c, KEY_ZOOM }, /* zoom */
{ 0x866b04, KEY_REWIND },
{ 0x866b0e, KEY_RECORD },
{ 0x866b0c, KEY_FORWARD },
{ 0x866b1d, KEY_STOP },
{ 0x866b08, KEY_PLAY },
{ 0x866b0f, KEY_PAUSE },
{ 0x866b0d, KEY_TV },
{ 0x866b07, KEY_RADIO }, /* FM */
};
static struct rc_map_list pixelview_map = {
.map = {
.scan = pixelview_mk12,
.size = ARRAY_SIZE(pixelview_mk12),
.rc_type = RC_TYPE_NEC,
.name = RC_MAP_PIXELVIEW_MK12,
}
};
static int __init init_rc_map_pixelview(void)
{
return rc_map_register(&pixelview_map);
}
static void __exit exit_rc_map_pixelview(void)
{
rc_map_unregister(&pixelview_map);
}
module_init(init_rc_map_pixelview)
module_exit(exit_rc_map_pixelview)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
varunchitre15/android_kernel_sony_tianchi | crypto/aead.c | 2943 | 14365 | /*
* AEAD: Authenticated Encryption with Associated Data
*
* This file provides API support for AEAD algorithms.
*
* Copyright (c) 2007 Herbert Xu <herbert@gondor.apana.org.au>
*
* 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 <crypto/internal/aead.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/rtnetlink.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/cryptouser.h>
#include <net/netlink.h>
#include "internal.h"
static int setkey_unaligned(struct crypto_aead *tfm, const u8 *key,
unsigned int keylen)
{
struct aead_alg *aead = crypto_aead_alg(tfm);
unsigned long alignmask = crypto_aead_alignmask(tfm);
int ret;
u8 *buffer, *alignbuffer;
unsigned long absize;
absize = keylen + alignmask;
buffer = kmalloc(absize, GFP_ATOMIC);
if (!buffer)
return -ENOMEM;
alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1);
memcpy(alignbuffer, key, keylen);
ret = aead->setkey(tfm, alignbuffer, keylen);
memset(alignbuffer, 0, keylen);
kfree(buffer);
return ret;
}
static int setkey(struct crypto_aead *tfm, const u8 *key, unsigned int keylen)
{
struct aead_alg *aead = crypto_aead_alg(tfm);
unsigned long alignmask = crypto_aead_alignmask(tfm);
if ((unsigned long)key & alignmask)
return setkey_unaligned(tfm, key, keylen);
return aead->setkey(tfm, key, keylen);
}
int crypto_aead_setauthsize(struct crypto_aead *tfm, unsigned int authsize)
{
struct aead_tfm *crt = crypto_aead_crt(tfm);
int err;
if (authsize > crypto_aead_alg(tfm)->maxauthsize)
return -EINVAL;
if (crypto_aead_alg(tfm)->setauthsize) {
err = crypto_aead_alg(tfm)->setauthsize(crt->base, authsize);
if (err)
return err;
}
crypto_aead_crt(crt->base)->authsize = authsize;
crt->authsize = authsize;
return 0;
}
EXPORT_SYMBOL_GPL(crypto_aead_setauthsize);
static unsigned int crypto_aead_ctxsize(struct crypto_alg *alg, u32 type,
u32 mask)
{
return alg->cra_ctxsize;
}
static int no_givcrypt(struct aead_givcrypt_request *req)
{
return -ENOSYS;
}
static int crypto_init_aead_ops(struct crypto_tfm *tfm, u32 type, u32 mask)
{
struct aead_alg *alg = &tfm->__crt_alg->cra_aead;
struct aead_tfm *crt = &tfm->crt_aead;
if (max(alg->maxauthsize, alg->ivsize) > PAGE_SIZE / 8)
return -EINVAL;
crt->setkey = tfm->__crt_alg->cra_flags & CRYPTO_ALG_GENIV ?
alg->setkey : setkey;
crt->encrypt = alg->encrypt;
crt->decrypt = alg->decrypt;
crt->givencrypt = alg->givencrypt ?: no_givcrypt;
crt->givdecrypt = alg->givdecrypt ?: no_givcrypt;
crt->base = __crypto_aead_cast(tfm);
crt->ivsize = alg->ivsize;
crt->authsize = alg->maxauthsize;
return 0;
}
#ifdef CONFIG_NET
static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_aead raead;
struct aead_alg *aead = &alg->cra_aead;
snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "aead");
snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s",
aead->geniv ?: "<built-in>");
raead.blocksize = alg->cra_blocksize;
raead.maxauthsize = aead->maxauthsize;
raead.ivsize = aead->ivsize;
NLA_PUT(skb, CRYPTOCFGA_REPORT_AEAD,
sizeof(struct crypto_report_aead), &raead);
return 0;
nla_put_failure:
return -EMSGSIZE;
}
#else
static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg)
{
return -ENOSYS;
}
#endif
static void crypto_aead_show(struct seq_file *m, struct crypto_alg *alg)
__attribute__ ((unused));
static void crypto_aead_show(struct seq_file *m, struct crypto_alg *alg)
{
struct aead_alg *aead = &alg->cra_aead;
seq_printf(m, "type : aead\n");
seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ?
"yes" : "no");
seq_printf(m, "blocksize : %u\n", alg->cra_blocksize);
seq_printf(m, "ivsize : %u\n", aead->ivsize);
seq_printf(m, "maxauthsize : %u\n", aead->maxauthsize);
seq_printf(m, "geniv : %s\n", aead->geniv ?: "<built-in>");
}
const struct crypto_type crypto_aead_type = {
.ctxsize = crypto_aead_ctxsize,
.init = crypto_init_aead_ops,
#ifdef CONFIG_PROC_FS
.show = crypto_aead_show,
#endif
.report = crypto_aead_report,
};
EXPORT_SYMBOL_GPL(crypto_aead_type);
static int aead_null_givencrypt(struct aead_givcrypt_request *req)
{
return crypto_aead_encrypt(&req->areq);
}
static int aead_null_givdecrypt(struct aead_givcrypt_request *req)
{
return crypto_aead_decrypt(&req->areq);
}
static int crypto_init_nivaead_ops(struct crypto_tfm *tfm, u32 type, u32 mask)
{
struct aead_alg *alg = &tfm->__crt_alg->cra_aead;
struct aead_tfm *crt = &tfm->crt_aead;
if (max(alg->maxauthsize, alg->ivsize) > PAGE_SIZE / 8)
return -EINVAL;
crt->setkey = setkey;
crt->encrypt = alg->encrypt;
crt->decrypt = alg->decrypt;
if (!alg->ivsize) {
crt->givencrypt = aead_null_givencrypt;
crt->givdecrypt = aead_null_givdecrypt;
}
crt->base = __crypto_aead_cast(tfm);
crt->ivsize = alg->ivsize;
crt->authsize = alg->maxauthsize;
return 0;
}
#ifdef CONFIG_NET
static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_aead raead;
struct aead_alg *aead = &alg->cra_aead;
snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "nivaead");
snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv);
raead.blocksize = alg->cra_blocksize;
raead.maxauthsize = aead->maxauthsize;
raead.ivsize = aead->ivsize;
NLA_PUT(skb, CRYPTOCFGA_REPORT_AEAD,
sizeof(struct crypto_report_aead), &raead);
return 0;
nla_put_failure:
return -EMSGSIZE;
}
#else
static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg)
{
return -ENOSYS;
}
#endif
static void crypto_nivaead_show(struct seq_file *m, struct crypto_alg *alg)
__attribute__ ((unused));
static void crypto_nivaead_show(struct seq_file *m, struct crypto_alg *alg)
{
struct aead_alg *aead = &alg->cra_aead;
seq_printf(m, "type : nivaead\n");
seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ?
"yes" : "no");
seq_printf(m, "blocksize : %u\n", alg->cra_blocksize);
seq_printf(m, "ivsize : %u\n", aead->ivsize);
seq_printf(m, "maxauthsize : %u\n", aead->maxauthsize);
seq_printf(m, "geniv : %s\n", aead->geniv);
}
const struct crypto_type crypto_nivaead_type = {
.ctxsize = crypto_aead_ctxsize,
.init = crypto_init_nivaead_ops,
#ifdef CONFIG_PROC_FS
.show = crypto_nivaead_show,
#endif
.report = crypto_nivaead_report,
};
EXPORT_SYMBOL_GPL(crypto_nivaead_type);
static int crypto_grab_nivaead(struct crypto_aead_spawn *spawn,
const char *name, u32 type, u32 mask)
{
struct crypto_alg *alg;
int err;
type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV);
type |= CRYPTO_ALG_TYPE_AEAD;
mask |= CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV;
alg = crypto_alg_mod_lookup(name, type, mask);
if (IS_ERR(alg))
return PTR_ERR(alg);
err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask);
crypto_mod_put(alg);
return err;
}
struct crypto_instance *aead_geniv_alloc(struct crypto_template *tmpl,
struct rtattr **tb, u32 type,
u32 mask)
{
const char *name;
struct crypto_aead_spawn *spawn;
struct crypto_attr_type *algt;
struct crypto_instance *inst;
struct crypto_alg *alg;
int err;
algt = crypto_get_attr_type(tb);
err = PTR_ERR(algt);
if (IS_ERR(algt))
return ERR_PTR(err);
if ((algt->type ^ (CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_GENIV)) &
algt->mask)
return ERR_PTR(-EINVAL);
name = crypto_attr_alg_name(tb[1]);
err = PTR_ERR(name);
if (IS_ERR(name))
return ERR_PTR(err);
inst = kzalloc(sizeof(*inst) + sizeof(*spawn), GFP_KERNEL);
if (!inst)
return ERR_PTR(-ENOMEM);
spawn = crypto_instance_ctx(inst);
/* Ignore async algorithms if necessary. */
mask |= crypto_requires_sync(algt->type, algt->mask);
crypto_set_aead_spawn(spawn, inst);
err = crypto_grab_nivaead(spawn, name, type, mask);
if (err)
goto err_free_inst;
alg = crypto_aead_spawn_alg(spawn);
err = -EINVAL;
if (!alg->cra_aead.ivsize)
goto err_drop_alg;
/*
* This is only true if we're constructing an algorithm with its
* default IV generator. For the default generator we elide the
* template name and double-check the IV generator.
*/
if (algt->mask & CRYPTO_ALG_GENIV) {
if (strcmp(tmpl->name, alg->cra_aead.geniv))
goto err_drop_alg;
memcpy(inst->alg.cra_name, alg->cra_name, CRYPTO_MAX_ALG_NAME);
memcpy(inst->alg.cra_driver_name, alg->cra_driver_name,
CRYPTO_MAX_ALG_NAME);
} else {
err = -ENAMETOOLONG;
if (snprintf(inst->alg.cra_name, CRYPTO_MAX_ALG_NAME,
"%s(%s)", tmpl->name, alg->cra_name) >=
CRYPTO_MAX_ALG_NAME)
goto err_drop_alg;
if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME,
"%s(%s)", tmpl->name, alg->cra_driver_name) >=
CRYPTO_MAX_ALG_NAME)
goto err_drop_alg;
}
inst->alg.cra_flags = CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_GENIV;
inst->alg.cra_flags |= alg->cra_flags & CRYPTO_ALG_ASYNC;
inst->alg.cra_priority = alg->cra_priority;
inst->alg.cra_blocksize = alg->cra_blocksize;
inst->alg.cra_alignmask = alg->cra_alignmask;
inst->alg.cra_type = &crypto_aead_type;
inst->alg.cra_aead.ivsize = alg->cra_aead.ivsize;
inst->alg.cra_aead.maxauthsize = alg->cra_aead.maxauthsize;
inst->alg.cra_aead.geniv = alg->cra_aead.geniv;
inst->alg.cra_aead.setkey = alg->cra_aead.setkey;
inst->alg.cra_aead.setauthsize = alg->cra_aead.setauthsize;
inst->alg.cra_aead.encrypt = alg->cra_aead.encrypt;
inst->alg.cra_aead.decrypt = alg->cra_aead.decrypt;
out:
return inst;
err_drop_alg:
crypto_drop_aead(spawn);
err_free_inst:
kfree(inst);
inst = ERR_PTR(err);
goto out;
}
EXPORT_SYMBOL_GPL(aead_geniv_alloc);
void aead_geniv_free(struct crypto_instance *inst)
{
crypto_drop_aead(crypto_instance_ctx(inst));
kfree(inst);
}
EXPORT_SYMBOL_GPL(aead_geniv_free);
int aead_geniv_init(struct crypto_tfm *tfm)
{
struct crypto_instance *inst = (void *)tfm->__crt_alg;
struct crypto_aead *aead;
aead = crypto_spawn_aead(crypto_instance_ctx(inst));
if (IS_ERR(aead))
return PTR_ERR(aead);
tfm->crt_aead.base = aead;
tfm->crt_aead.reqsize += crypto_aead_reqsize(aead);
return 0;
}
EXPORT_SYMBOL_GPL(aead_geniv_init);
void aead_geniv_exit(struct crypto_tfm *tfm)
{
crypto_free_aead(tfm->crt_aead.base);
}
EXPORT_SYMBOL_GPL(aead_geniv_exit);
static int crypto_nivaead_default(struct crypto_alg *alg, u32 type, u32 mask)
{
struct rtattr *tb[3];
struct {
struct rtattr attr;
struct crypto_attr_type data;
} ptype;
struct {
struct rtattr attr;
struct crypto_attr_alg data;
} palg;
struct crypto_template *tmpl;
struct crypto_instance *inst;
struct crypto_alg *larval;
const char *geniv;
int err;
larval = crypto_larval_lookup(alg->cra_driver_name,
CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_GENIV,
CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV);
err = PTR_ERR(larval);
if (IS_ERR(larval))
goto out;
err = -EAGAIN;
if (!crypto_is_larval(larval))
goto drop_larval;
ptype.attr.rta_len = sizeof(ptype);
ptype.attr.rta_type = CRYPTOA_TYPE;
ptype.data.type = type | CRYPTO_ALG_GENIV;
/* GENIV tells the template that we're making a default geniv. */
ptype.data.mask = mask | CRYPTO_ALG_GENIV;
tb[0] = &ptype.attr;
palg.attr.rta_len = sizeof(palg);
palg.attr.rta_type = CRYPTOA_ALG;
/* Must use the exact name to locate ourselves. */
memcpy(palg.data.name, alg->cra_driver_name, CRYPTO_MAX_ALG_NAME);
tb[1] = &palg.attr;
tb[2] = NULL;
geniv = alg->cra_aead.geniv;
tmpl = crypto_lookup_template(geniv);
err = -ENOENT;
if (!tmpl)
goto kill_larval;
inst = tmpl->alloc(tb);
err = PTR_ERR(inst);
if (IS_ERR(inst))
goto put_tmpl;
if ((err = crypto_register_instance(tmpl, inst))) {
tmpl->free(inst);
goto put_tmpl;
}
/* Redo the lookup to use the instance we just registered. */
err = -EAGAIN;
put_tmpl:
crypto_tmpl_put(tmpl);
kill_larval:
crypto_larval_kill(larval);
drop_larval:
crypto_mod_put(larval);
out:
crypto_mod_put(alg);
return err;
}
struct crypto_alg *crypto_lookup_aead(const char *name, u32 type, u32 mask)
{
struct crypto_alg *alg;
alg = crypto_alg_mod_lookup(name, type, mask);
if (IS_ERR(alg))
return alg;
if (alg->cra_type == &crypto_aead_type)
return alg;
if (!alg->cra_aead.ivsize)
return alg;
crypto_mod_put(alg);
alg = crypto_alg_mod_lookup(name, type | CRYPTO_ALG_TESTED,
mask & ~CRYPTO_ALG_TESTED);
if (IS_ERR(alg))
return alg;
if (alg->cra_type == &crypto_aead_type) {
if ((alg->cra_flags ^ type ^ ~mask) & CRYPTO_ALG_TESTED) {
crypto_mod_put(alg);
alg = ERR_PTR(-ENOENT);
}
return alg;
}
BUG_ON(!alg->cra_aead.ivsize);
return ERR_PTR(crypto_nivaead_default(alg, type, mask));
}
EXPORT_SYMBOL_GPL(crypto_lookup_aead);
int crypto_grab_aead(struct crypto_aead_spawn *spawn, const char *name,
u32 type, u32 mask)
{
struct crypto_alg *alg;
int err;
type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV);
type |= CRYPTO_ALG_TYPE_AEAD;
mask &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV);
mask |= CRYPTO_ALG_TYPE_MASK;
alg = crypto_lookup_aead(name, type, mask);
if (IS_ERR(alg))
return PTR_ERR(alg);
err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask);
crypto_mod_put(alg);
return err;
}
EXPORT_SYMBOL_GPL(crypto_grab_aead);
struct crypto_aead *crypto_alloc_aead(const char *alg_name, u32 type, u32 mask)
{
struct crypto_tfm *tfm;
int err;
type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV);
type |= CRYPTO_ALG_TYPE_AEAD;
mask &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV);
mask |= CRYPTO_ALG_TYPE_MASK;
for (;;) {
struct crypto_alg *alg;
alg = crypto_lookup_aead(alg_name, type, mask);
if (IS_ERR(alg)) {
err = PTR_ERR(alg);
goto err;
}
tfm = __crypto_alloc_tfm(alg, type, mask);
if (!IS_ERR(tfm))
return __crypto_aead_cast(tfm);
crypto_mod_put(alg);
err = PTR_ERR(tfm);
err:
if (err != -EAGAIN)
break;
if (signal_pending(current)) {
err = -EINTR;
break;
}
}
return ERR_PTR(err);
}
EXPORT_SYMBOL_GPL(crypto_alloc_aead);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Authenticated Encryption with Associated Data (AEAD)");
| gpl-2.0 |
SlimRoms/kernel_samsung_crespo | drivers/media/rc/keymaps/rc-pixelview-mk12.c | 2943 | 2138 | /* rc-pixelview-mk12.h - Keytable for pixelview Remote Controller
*
* keymap imported from ir-keymaps.c
*
* Copyright (c) 2010 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
/*
* Keytable for MK-F12 IR remote provided together with Pixelview
* Ultra Pro Remote Controller. Uses NEC extended format.
*/
static struct rc_map_table pixelview_mk12[] = {
{ 0x866b03, KEY_TUNER }, /* Timeshift */
{ 0x866b1e, KEY_POWER2 }, /* power */
{ 0x866b01, KEY_1 },
{ 0x866b0b, KEY_2 },
{ 0x866b1b, KEY_3 },
{ 0x866b05, KEY_4 },
{ 0x866b09, KEY_5 },
{ 0x866b15, KEY_6 },
{ 0x866b06, KEY_7 },
{ 0x866b0a, KEY_8 },
{ 0x866b12, KEY_9 },
{ 0x866b02, KEY_0 },
{ 0x866b13, KEY_AGAIN }, /* loop */
{ 0x866b10, KEY_DIGITS }, /* +100 */
{ 0x866b00, KEY_VIDEO }, /* source */
{ 0x866b18, KEY_MUTE }, /* mute */
{ 0x866b19, KEY_CAMERA }, /* snapshot */
{ 0x866b1a, KEY_SEARCH }, /* scan */
{ 0x866b16, KEY_CHANNELUP }, /* chn + */
{ 0x866b14, KEY_CHANNELDOWN }, /* chn - */
{ 0x866b1f, KEY_VOLUMEUP }, /* vol + */
{ 0x866b17, KEY_VOLUMEDOWN }, /* vol - */
{ 0x866b1c, KEY_ZOOM }, /* zoom */
{ 0x866b04, KEY_REWIND },
{ 0x866b0e, KEY_RECORD },
{ 0x866b0c, KEY_FORWARD },
{ 0x866b1d, KEY_STOP },
{ 0x866b08, KEY_PLAY },
{ 0x866b0f, KEY_PAUSE },
{ 0x866b0d, KEY_TV },
{ 0x866b07, KEY_RADIO }, /* FM */
};
static struct rc_map_list pixelview_map = {
.map = {
.scan = pixelview_mk12,
.size = ARRAY_SIZE(pixelview_mk12),
.rc_type = RC_TYPE_NEC,
.name = RC_MAP_PIXELVIEW_MK12,
}
};
static int __init init_rc_map_pixelview(void)
{
return rc_map_register(&pixelview_map);
}
static void __exit exit_rc_map_pixelview(void)
{
rc_map_unregister(&pixelview_map);
}
module_init(init_rc_map_pixelview)
module_exit(exit_rc_map_pixelview)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
snandlal/samsung_kernel | drivers/watchdog/ks8695_wdt.c | 3199 | 7579 | /*
* Watchdog driver for Kendin/Micrel KS8695.
*
* (C) 2007 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/bitops.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/platform_device.h>
#include <linux/types.h>
#include <linux/watchdog.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <mach/hardware.h>
#include <mach/regs-timer.h>
#define WDT_DEFAULT_TIME 5 /* seconds */
#define WDT_MAX_TIME 171 /* seconds */
static int wdt_time = WDT_DEFAULT_TIME;
static int nowayout = WATCHDOG_NOWAYOUT;
module_param(wdt_time, int, 0);
MODULE_PARM_DESC(wdt_time, "Watchdog time in seconds. (default="
__MODULE_STRING(WDT_DEFAULT_TIME) ")");
#ifdef CONFIG_WATCHDOG_NOWAYOUT
module_param(nowayout, int, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
#endif
static unsigned long ks8695wdt_busy;
static spinlock_t ks8695_lock;
/* ......................................................................... */
/*
* Disable the watchdog.
*/
static inline void ks8695_wdt_stop(void)
{
unsigned long tmcon;
spin_lock(&ks8695_lock);
/* disable timer0 */
tmcon = __raw_readl(KS8695_TMR_VA + KS8695_TMCON);
__raw_writel(tmcon & ~TMCON_T0EN, KS8695_TMR_VA + KS8695_TMCON);
spin_unlock(&ks8695_lock);
}
/*
* Enable and reset the watchdog.
*/
static inline void ks8695_wdt_start(void)
{
unsigned long tmcon;
unsigned long tval = wdt_time * KS8695_CLOCK_RATE;
spin_lock(&ks8695_lock);
/* disable timer0 */
tmcon = __raw_readl(KS8695_TMR_VA + KS8695_TMCON);
__raw_writel(tmcon & ~TMCON_T0EN, KS8695_TMR_VA + KS8695_TMCON);
/* program timer0 */
__raw_writel(tval | T0TC_WATCHDOG, KS8695_TMR_VA + KS8695_T0TC);
/* re-enable timer0 */
tmcon = __raw_readl(KS8695_TMR_VA + KS8695_TMCON);
__raw_writel(tmcon | TMCON_T0EN, KS8695_TMR_VA + KS8695_TMCON);
spin_unlock(&ks8695_lock);
}
/*
* Reload the watchdog timer. (ie, pat the watchdog)
*/
static inline void ks8695_wdt_reload(void)
{
unsigned long tmcon;
spin_lock(&ks8695_lock);
/* disable, then re-enable timer0 */
tmcon = __raw_readl(KS8695_TMR_VA + KS8695_TMCON);
__raw_writel(tmcon & ~TMCON_T0EN, KS8695_TMR_VA + KS8695_TMCON);
__raw_writel(tmcon | TMCON_T0EN, KS8695_TMR_VA + KS8695_TMCON);
spin_unlock(&ks8695_lock);
}
/*
* Change the watchdog time interval.
*/
static int ks8695_wdt_settimeout(int new_time)
{
/*
* All counting occurs at KS8695_CLOCK_RATE / 128 = 0.256 Hz
*
* Since WDV is a 16-bit counter, the maximum period is
* 65536 / 0.256 = 256 seconds.
*/
if ((new_time <= 0) || (new_time > WDT_MAX_TIME))
return -EINVAL;
/* Set new watchdog time. It will be used when
ks8695_wdt_start() is called. */
wdt_time = new_time;
return 0;
}
/* ......................................................................... */
/*
* Watchdog device is opened, and watchdog starts running.
*/
static int ks8695_wdt_open(struct inode *inode, struct file *file)
{
if (test_and_set_bit(0, &ks8695wdt_busy))
return -EBUSY;
ks8695_wdt_start();
return nonseekable_open(inode, file);
}
/*
* Close the watchdog device.
* If CONFIG_WATCHDOG_NOWAYOUT is NOT defined then the watchdog is also
* disabled.
*/
static int ks8695_wdt_close(struct inode *inode, struct file *file)
{
/* Disable the watchdog when file is closed */
if (!nowayout)
ks8695_wdt_stop();
clear_bit(0, &ks8695wdt_busy);
return 0;
}
static const struct watchdog_info ks8695_wdt_info = {
.identity = "ks8695 watchdog",
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING,
};
/*
* Handle commands from user-space.
*/
static long ks8695_wdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
void __user *argp = (void __user *)arg;
int __user *p = argp;
int new_value;
switch (cmd) {
case WDIOC_GETSUPPORT:
return copy_to_user(argp, &ks8695_wdt_info,
sizeof(ks8695_wdt_info)) ? -EFAULT : 0;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
return put_user(0, p);
case WDIOC_SETOPTIONS:
if (get_user(new_value, p))
return -EFAULT;
if (new_value & WDIOS_DISABLECARD)
ks8695_wdt_stop();
if (new_value & WDIOS_ENABLECARD)
ks8695_wdt_start();
return 0;
case WDIOC_KEEPALIVE:
ks8695_wdt_reload(); /* pat the watchdog */
return 0;
case WDIOC_SETTIMEOUT:
if (get_user(new_value, p))
return -EFAULT;
if (ks8695_wdt_settimeout(new_value))
return -EINVAL;
/* Enable new time value */
ks8695_wdt_start();
/* Return current value */
return put_user(wdt_time, p);
case WDIOC_GETTIMEOUT:
return put_user(wdt_time, p);
default:
return -ENOTTY;
}
}
/*
* Pat the watchdog whenever device is written to.
*/
static ssize_t ks8695_wdt_write(struct file *file, const char *data,
size_t len, loff_t *ppos)
{
ks8695_wdt_reload(); /* pat the watchdog */
return len;
}
/* ......................................................................... */
static const struct file_operations ks8695wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.unlocked_ioctl = ks8695_wdt_ioctl,
.open = ks8695_wdt_open,
.release = ks8695_wdt_close,
.write = ks8695_wdt_write,
};
static struct miscdevice ks8695wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &ks8695wdt_fops,
};
static int __devinit ks8695wdt_probe(struct platform_device *pdev)
{
int res;
if (ks8695wdt_miscdev.parent)
return -EBUSY;
ks8695wdt_miscdev.parent = &pdev->dev;
res = misc_register(&ks8695wdt_miscdev);
if (res)
return res;
printk(KERN_INFO "KS8695 Watchdog Timer enabled (%d seconds%s)\n",
wdt_time, nowayout ? ", nowayout" : "");
return 0;
}
static int __devexit ks8695wdt_remove(struct platform_device *pdev)
{
int res;
res = misc_deregister(&ks8695wdt_miscdev);
if (!res)
ks8695wdt_miscdev.parent = NULL;
return res;
}
static void ks8695wdt_shutdown(struct platform_device *pdev)
{
ks8695_wdt_stop();
}
#ifdef CONFIG_PM
static int ks8695wdt_suspend(struct platform_device *pdev, pm_message_t message)
{
ks8695_wdt_stop();
return 0;
}
static int ks8695wdt_resume(struct platform_device *pdev)
{
if (ks8695wdt_busy)
ks8695_wdt_start();
return 0;
}
#else
#define ks8695wdt_suspend NULL
#define ks8695wdt_resume NULL
#endif
static struct platform_driver ks8695wdt_driver = {
.probe = ks8695wdt_probe,
.remove = __devexit_p(ks8695wdt_remove),
.shutdown = ks8695wdt_shutdown,
.suspend = ks8695wdt_suspend,
.resume = ks8695wdt_resume,
.driver = {
.name = "ks8695_wdt",
.owner = THIS_MODULE,
},
};
static int __init ks8695_wdt_init(void)
{
spin_lock_init(&ks8695_lock);
/* Check that the heartbeat value is within range;
if not reset to the default */
if (ks8695_wdt_settimeout(wdt_time)) {
ks8695_wdt_settimeout(WDT_DEFAULT_TIME);
pr_info("ks8695_wdt: wdt_time value must be 1 <= wdt_time <= %i"
", using %d\n", wdt_time, WDT_MAX_TIME);
}
return platform_driver_register(&ks8695wdt_driver);
}
static void __exit ks8695_wdt_exit(void)
{
platform_driver_unregister(&ks8695wdt_driver);
}
module_init(ks8695_wdt_init);
module_exit(ks8695_wdt_exit);
MODULE_AUTHOR("Andrew Victor");
MODULE_DESCRIPTION("Watchdog driver for KS8695");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
MODULE_ALIAS("platform:ks8695_wdt");
| gpl-2.0 |
dtuchsch/linux-preempt_rt | drivers/hid/hid-elecom.c | 3967 | 1239 | /*
* HID driver for Elecom BM084 (bluetooth mouse).
* Removes a non-existing horizontal wheel from
* the HID descriptor.
* (This module is based on "hid-ortek".)
*
* Copyright (c) 2010 Richard Nauber <Richard.Nauber@gmail.com>
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include "hid-ids.h"
static __u8 *elecom_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
if (*rsize >= 48 && rdesc[46] == 0x05 && rdesc[47] == 0x0c) {
hid_info(hdev, "Fixing up Elecom BM084 report descriptor\n");
rdesc[47] = 0x00;
}
return rdesc;
}
static const struct hid_device_id elecom_devices[] = {
{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_ELECOM, USB_DEVICE_ID_ELECOM_BM084)},
{ }
};
MODULE_DEVICE_TABLE(hid, elecom_devices);
static struct hid_driver elecom_driver = {
.name = "elecom",
.id_table = elecom_devices,
.report_fixup = elecom_report_fixup
};
module_hid_driver(elecom_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
CyanogenMod/lge-kernel-star | arch/parisc/kernel/drivers.c | 4479 | 24367 | /*
* drivers.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Copyright (c) 1999 The Puffin Group
* Copyright (c) 2001 Matthew Wilcox for Hewlett Packard
* Copyright (c) 2001 Helge Deller <deller@gmx.de>
* Copyright (c) 2001,2002 Ryan Bradetich
* Copyright (c) 2004-2005 Thibaut VARENE <varenet@parisc-linux.org>
*
* The file handles registering devices and drivers, then matching them.
* It's the closest we get to a dating agency.
*
* If you're thinking about modifying this file, here are some gotchas to
* bear in mind:
* - 715/Mirage device paths have a dummy device between Lasi and its children
* - The EISA adapter may show up as a sibling or child of Wax
* - Dino has an optionally functional serial port. If firmware enables it,
* it shows up as a child of Dino. If firmware disables it, the buswalk
* finds it and it shows up as a child of Cujo
* - Dino has both parisc and pci devices as children
* - parisc devices are discovered in a random order, including children
* before parents in some cases.
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <asm/hardware.h>
#include <asm/io.h>
#include <asm/pdc.h>
#include <asm/parisc-device.h>
/* See comments in include/asm-parisc/pci.h */
struct hppa_dma_ops *hppa_dma_ops __read_mostly;
EXPORT_SYMBOL(hppa_dma_ops);
static struct device root = {
.init_name = "parisc",
};
static inline int check_dev(struct device *dev)
{
if (dev->bus == &parisc_bus_type) {
struct parisc_device *pdev;
pdev = to_parisc_device(dev);
return pdev->id.hw_type != HPHW_FAULTY;
}
return 1;
}
static struct device *
parse_tree_node(struct device *parent, int index, struct hardware_path *modpath);
struct recurse_struct {
void * obj;
int (*fn)(struct device *, void *);
};
static int descend_children(struct device * dev, void * data)
{
struct recurse_struct * recurse_data = (struct recurse_struct *)data;
if (recurse_data->fn(dev, recurse_data->obj))
return 1;
else
return device_for_each_child(dev, recurse_data, descend_children);
}
/**
* for_each_padev - Iterate over all devices in the tree
* @fn: Function to call for each device.
* @data: Data to pass to the called function.
*
* This performs a depth-first traversal of the tree, calling the
* function passed for each node. It calls the function for parents
* before children.
*/
static int for_each_padev(int (*fn)(struct device *, void *), void * data)
{
struct recurse_struct recurse_data = {
.obj = data,
.fn = fn,
};
return device_for_each_child(&root, &recurse_data, descend_children);
}
/**
* match_device - Report whether this driver can handle this device
* @driver: the PA-RISC driver to try
* @dev: the PA-RISC device to try
*/
static int match_device(struct parisc_driver *driver, struct parisc_device *dev)
{
const struct parisc_device_id *ids;
for (ids = driver->id_table; ids->sversion; ids++) {
if ((ids->sversion != SVERSION_ANY_ID) &&
(ids->sversion != dev->id.sversion))
continue;
if ((ids->hw_type != HWTYPE_ANY_ID) &&
(ids->hw_type != dev->id.hw_type))
continue;
if ((ids->hversion != HVERSION_ANY_ID) &&
(ids->hversion != dev->id.hversion))
continue;
return 1;
}
return 0;
}
static int parisc_driver_probe(struct device *dev)
{
int rc;
struct parisc_device *pa_dev = to_parisc_device(dev);
struct parisc_driver *pa_drv = to_parisc_driver(dev->driver);
rc = pa_drv->probe(pa_dev);
if (!rc)
pa_dev->driver = pa_drv;
return rc;
}
static int parisc_driver_remove(struct device *dev)
{
struct parisc_device *pa_dev = to_parisc_device(dev);
struct parisc_driver *pa_drv = to_parisc_driver(dev->driver);
if (pa_drv->remove)
pa_drv->remove(pa_dev);
return 0;
}
/**
* register_parisc_driver - Register this driver if it can handle a device
* @driver: the PA-RISC driver to try
*/
int register_parisc_driver(struct parisc_driver *driver)
{
/* FIXME: we need this because apparently the sti
* driver can be registered twice */
if(driver->drv.name) {
printk(KERN_WARNING
"BUG: skipping previously registered driver %s\n",
driver->name);
return 1;
}
if (!driver->probe) {
printk(KERN_WARNING
"BUG: driver %s has no probe routine\n",
driver->name);
return 1;
}
driver->drv.bus = &parisc_bus_type;
/* We install our own probe and remove routines */
WARN_ON(driver->drv.probe != NULL);
WARN_ON(driver->drv.remove != NULL);
driver->drv.name = driver->name;
return driver_register(&driver->drv);
}
EXPORT_SYMBOL(register_parisc_driver);
struct match_count {
struct parisc_driver * driver;
int count;
};
static int match_and_count(struct device * dev, void * data)
{
struct match_count * m = data;
struct parisc_device * pdev = to_parisc_device(dev);
if (check_dev(dev)) {
if (match_device(m->driver, pdev))
m->count++;
}
return 0;
}
/**
* count_parisc_driver - count # of devices this driver would match
* @driver: the PA-RISC driver to try
*
* Use by IOMMU support to "guess" the right size IOPdir.
* Formula is something like memsize/(num_iommu * entry_size).
*/
int count_parisc_driver(struct parisc_driver *driver)
{
struct match_count m = {
.driver = driver,
.count = 0,
};
for_each_padev(match_and_count, &m);
return m.count;
}
/**
* unregister_parisc_driver - Unregister this driver from the list of drivers
* @driver: the PA-RISC driver to unregister
*/
int unregister_parisc_driver(struct parisc_driver *driver)
{
driver_unregister(&driver->drv);
return 0;
}
EXPORT_SYMBOL(unregister_parisc_driver);
struct find_data {
unsigned long hpa;
struct parisc_device * dev;
};
static int find_device(struct device * dev, void * data)
{
struct parisc_device * pdev = to_parisc_device(dev);
struct find_data * d = (struct find_data*)data;
if (check_dev(dev)) {
if (pdev->hpa.start == d->hpa) {
d->dev = pdev;
return 1;
}
}
return 0;
}
static struct parisc_device *find_device_by_addr(unsigned long hpa)
{
struct find_data d = {
.hpa = hpa,
};
int ret;
ret = for_each_padev(find_device, &d);
return ret ? d.dev : NULL;
}
/**
* find_pa_parent_type - Find a parent of a specific type
* @dev: The device to start searching from
* @type: The device type to search for.
*
* Walks up the device tree looking for a device of the specified type.
* If it finds it, it returns it. If not, it returns NULL.
*/
const struct parisc_device *
find_pa_parent_type(const struct parisc_device *padev, int type)
{
const struct device *dev = &padev->dev;
while (dev != &root) {
struct parisc_device *candidate = to_parisc_device(dev);
if (candidate->id.hw_type == type)
return candidate;
dev = dev->parent;
}
return NULL;
}
#ifdef CONFIG_PCI
static inline int is_pci_dev(struct device *dev)
{
return dev->bus == &pci_bus_type;
}
#else
static inline int is_pci_dev(struct device *dev)
{
return 0;
}
#endif
/*
* get_node_path fills in @path with the firmware path to the device.
* Note that if @node is a parisc device, we don't fill in the 'mod' field.
* This is because both callers pass the parent and fill in the mod
* themselves. If @node is a PCI device, we do fill it in, even though this
* is inconsistent.
*/
static void get_node_path(struct device *dev, struct hardware_path *path)
{
int i = 5;
memset(&path->bc, -1, 6);
if (is_pci_dev(dev)) {
unsigned int devfn = to_pci_dev(dev)->devfn;
path->mod = PCI_FUNC(devfn);
path->bc[i--] = PCI_SLOT(devfn);
dev = dev->parent;
}
while (dev != &root) {
if (is_pci_dev(dev)) {
unsigned int devfn = to_pci_dev(dev)->devfn;
path->bc[i--] = PCI_SLOT(devfn) | (PCI_FUNC(devfn)<< 5);
} else if (dev->bus == &parisc_bus_type) {
path->bc[i--] = to_parisc_device(dev)->hw_path;
}
dev = dev->parent;
}
}
static char *print_hwpath(struct hardware_path *path, char *output)
{
int i;
for (i = 0; i < 6; i++) {
if (path->bc[i] == -1)
continue;
output += sprintf(output, "%u/", (unsigned char) path->bc[i]);
}
output += sprintf(output, "%u", (unsigned char) path->mod);
return output;
}
/**
* print_pa_hwpath - Returns hardware path for PA devices
* dev: The device to return the path for
* output: Pointer to a previously-allocated array to place the path in.
*
* This function fills in the output array with a human-readable path
* to a PA device. This string is compatible with that used by PDC, and
* may be printed on the outside of the box.
*/
char *print_pa_hwpath(struct parisc_device *dev, char *output)
{
struct hardware_path path;
get_node_path(dev->dev.parent, &path);
path.mod = dev->hw_path;
return print_hwpath(&path, output);
}
EXPORT_SYMBOL(print_pa_hwpath);
#if defined(CONFIG_PCI) || defined(CONFIG_ISA)
/**
* get_pci_node_path - Determines the hardware path for a PCI device
* @pdev: The device to return the path for
* @path: Pointer to a previously-allocated array to place the path in.
*
* This function fills in the hardware_path structure with the route to
* the specified PCI device. This structure is suitable for passing to
* PDC calls.
*/
void get_pci_node_path(struct pci_dev *pdev, struct hardware_path *path)
{
get_node_path(&pdev->dev, path);
}
EXPORT_SYMBOL(get_pci_node_path);
/**
* print_pci_hwpath - Returns hardware path for PCI devices
* dev: The device to return the path for
* output: Pointer to a previously-allocated array to place the path in.
*
* This function fills in the output array with a human-readable path
* to a PCI device. This string is compatible with that used by PDC, and
* may be printed on the outside of the box.
*/
char *print_pci_hwpath(struct pci_dev *dev, char *output)
{
struct hardware_path path;
get_pci_node_path(dev, &path);
return print_hwpath(&path, output);
}
EXPORT_SYMBOL(print_pci_hwpath);
#endif /* defined(CONFIG_PCI) || defined(CONFIG_ISA) */
static void setup_bus_id(struct parisc_device *padev)
{
struct hardware_path path;
char name[20];
char *output = name;
int i;
get_node_path(padev->dev.parent, &path);
for (i = 0; i < 6; i++) {
if (path.bc[i] == -1)
continue;
output += sprintf(output, "%u:", (unsigned char) path.bc[i]);
}
sprintf(output, "%u", (unsigned char) padev->hw_path);
dev_set_name(&padev->dev, name);
}
struct parisc_device * create_tree_node(char id, struct device *parent)
{
struct parisc_device *dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return NULL;
dev->hw_path = id;
dev->id.hw_type = HPHW_FAULTY;
dev->dev.parent = parent;
setup_bus_id(dev);
dev->dev.bus = &parisc_bus_type;
dev->dma_mask = 0xffffffffUL; /* PARISC devices are 32-bit */
/* make the generic dma mask a pointer to the parisc one */
dev->dev.dma_mask = &dev->dma_mask;
dev->dev.coherent_dma_mask = dev->dma_mask;
if (device_register(&dev->dev)) {
kfree(dev);
return NULL;
}
return dev;
}
struct match_id_data {
char id;
struct parisc_device * dev;
};
static int match_by_id(struct device * dev, void * data)
{
struct parisc_device * pdev = to_parisc_device(dev);
struct match_id_data * d = data;
if (pdev->hw_path == d->id) {
d->dev = pdev;
return 1;
}
return 0;
}
/**
* alloc_tree_node - returns a device entry in the iotree
* @parent: the parent node in the tree
* @id: the element of the module path for this entry
*
* Checks all the children of @parent for a matching @id. If none
* found, it allocates a new device and returns it.
*/
static struct parisc_device * alloc_tree_node(struct device *parent, char id)
{
struct match_id_data d = {
.id = id,
};
if (device_for_each_child(parent, &d, match_by_id))
return d.dev;
else
return create_tree_node(id, parent);
}
static struct parisc_device *create_parisc_device(struct hardware_path *modpath)
{
int i;
struct device *parent = &root;
for (i = 0; i < 6; i++) {
if (modpath->bc[i] == -1)
continue;
parent = &alloc_tree_node(parent, modpath->bc[i])->dev;
}
return alloc_tree_node(parent, modpath->mod);
}
struct parisc_device *
alloc_pa_dev(unsigned long hpa, struct hardware_path *mod_path)
{
int status;
unsigned long bytecnt;
u8 iodc_data[32];
struct parisc_device *dev;
const char *name;
/* Check to make sure this device has not already been added - Ryan */
if (find_device_by_addr(hpa) != NULL)
return NULL;
status = pdc_iodc_read(&bytecnt, hpa, 0, &iodc_data, 32);
if (status != PDC_OK)
return NULL;
dev = create_parisc_device(mod_path);
if (dev->id.hw_type != HPHW_FAULTY) {
printk(KERN_ERR "Two devices have hardware path [%s]. "
"IODC data for second device: "
"%02x%02x%02x%02x%02x%02x\n"
"Rearranging GSC cards sometimes helps\n",
parisc_pathname(dev), iodc_data[0], iodc_data[1],
iodc_data[3], iodc_data[4], iodc_data[5], iodc_data[6]);
return NULL;
}
dev->id.hw_type = iodc_data[3] & 0x1f;
dev->id.hversion = (iodc_data[0] << 4) | ((iodc_data[1] & 0xf0) >> 4);
dev->id.hversion_rev = iodc_data[1] & 0x0f;
dev->id.sversion = ((iodc_data[4] & 0x0f) << 16) |
(iodc_data[5] << 8) | iodc_data[6];
dev->hpa.name = parisc_pathname(dev);
dev->hpa.start = hpa;
/* This is awkward. The STI spec says that gfx devices may occupy
* 32MB or 64MB. Unfortunately, we don't know how to tell whether
* it's the former or the latter. Assumptions either way can hurt us.
*/
if (hpa == 0xf4000000 || hpa == 0xf8000000) {
dev->hpa.end = hpa + 0x03ffffff;
} else if (hpa == 0xf6000000 || hpa == 0xfa000000) {
dev->hpa.end = hpa + 0x01ffffff;
} else {
dev->hpa.end = hpa + 0xfff;
}
dev->hpa.flags = IORESOURCE_MEM;
name = parisc_hardware_description(&dev->id);
if (name) {
strlcpy(dev->name, name, sizeof(dev->name));
}
/* Silently fail things like mouse ports which are subsumed within
* the keyboard controller
*/
if ((hpa & 0xfff) == 0 && insert_resource(&iomem_resource, &dev->hpa))
printk("Unable to claim HPA %lx for device %s\n",
hpa, name);
return dev;
}
static int parisc_generic_match(struct device *dev, struct device_driver *drv)
{
return match_device(to_parisc_driver(drv), to_parisc_device(dev));
}
static ssize_t make_modalias(struct device *dev, char *buf)
{
const struct parisc_device *padev = to_parisc_device(dev);
const struct parisc_device_id *id = &padev->id;
return sprintf(buf, "parisc:t%02Xhv%04Xrev%02Xsv%08X\n",
(u8)id->hw_type, (u16)id->hversion, (u8)id->hversion_rev,
(u32)id->sversion);
}
static int parisc_uevent(struct device *dev, struct kobj_uevent_env *env)
{
const struct parisc_device *padev;
char modalias[40];
if (!dev)
return -ENODEV;
padev = to_parisc_device(dev);
if (!padev)
return -ENODEV;
if (add_uevent_var(env, "PARISC_NAME=%s", padev->name))
return -ENOMEM;
make_modalias(dev, modalias);
if (add_uevent_var(env, "MODALIAS=%s", modalias))
return -ENOMEM;
return 0;
}
#define pa_dev_attr(name, field, format_string) \
static ssize_t name##_show(struct device *dev, struct device_attribute *attr, char *buf) \
{ \
struct parisc_device *padev = to_parisc_device(dev); \
return sprintf(buf, format_string, padev->field); \
}
#define pa_dev_attr_id(field, format) pa_dev_attr(field, id.field, format)
pa_dev_attr(irq, irq, "%u\n");
pa_dev_attr_id(hw_type, "0x%02x\n");
pa_dev_attr(rev, id.hversion_rev, "0x%x\n");
pa_dev_attr_id(hversion, "0x%03x\n");
pa_dev_attr_id(sversion, "0x%05x\n");
static ssize_t modalias_show(struct device *dev, struct device_attribute *attr, char *buf)
{
return make_modalias(dev, buf);
}
static struct device_attribute parisc_device_attrs[] = {
__ATTR_RO(irq),
__ATTR_RO(hw_type),
__ATTR_RO(rev),
__ATTR_RO(hversion),
__ATTR_RO(sversion),
__ATTR_RO(modalias),
__ATTR_NULL,
};
struct bus_type parisc_bus_type = {
.name = "parisc",
.match = parisc_generic_match,
.uevent = parisc_uevent,
.dev_attrs = parisc_device_attrs,
.probe = parisc_driver_probe,
.remove = parisc_driver_remove,
};
/**
* register_parisc_device - Locate a driver to manage this device.
* @dev: The parisc device.
*
* Search the driver list for a driver that is willing to manage
* this device.
*/
int register_parisc_device(struct parisc_device *dev)
{
if (!dev)
return 0;
if (dev->driver)
return 1;
return 0;
}
/**
* match_pci_device - Matches a pci device against a given hardware path
* entry.
* @dev: the generic device (known to be contained by a pci_dev).
* @index: the current BC index
* @modpath: the hardware path.
* @return: true if the device matches the hardware path.
*/
static int match_pci_device(struct device *dev, int index,
struct hardware_path *modpath)
{
struct pci_dev *pdev = to_pci_dev(dev);
int id;
if (index == 5) {
/* we are at the end of the path, and on the actual device */
unsigned int devfn = pdev->devfn;
return ((modpath->bc[5] == PCI_SLOT(devfn)) &&
(modpath->mod == PCI_FUNC(devfn)));
}
id = PCI_SLOT(pdev->devfn) | (PCI_FUNC(pdev->devfn) << 5);
return (modpath->bc[index] == id);
}
/**
* match_parisc_device - Matches a parisc device against a given hardware
* path entry.
* @dev: the generic device (known to be contained by a parisc_device).
* @index: the current BC index
* @modpath: the hardware path.
* @return: true if the device matches the hardware path.
*/
static int match_parisc_device(struct device *dev, int index,
struct hardware_path *modpath)
{
struct parisc_device *curr = to_parisc_device(dev);
char id = (index == 6) ? modpath->mod : modpath->bc[index];
return (curr->hw_path == id);
}
struct parse_tree_data {
int index;
struct hardware_path * modpath;
struct device * dev;
};
static int check_parent(struct device * dev, void * data)
{
struct parse_tree_data * d = data;
if (check_dev(dev)) {
if (dev->bus == &parisc_bus_type) {
if (match_parisc_device(dev, d->index, d->modpath))
d->dev = dev;
} else if (is_pci_dev(dev)) {
if (match_pci_device(dev, d->index, d->modpath))
d->dev = dev;
} else if (dev->bus == NULL) {
/* we are on a bus bridge */
struct device *new = parse_tree_node(dev, d->index, d->modpath);
if (new)
d->dev = new;
}
}
return d->dev != NULL;
}
/**
* parse_tree_node - returns a device entry in the iotree
* @parent: the parent node in the tree
* @index: the current BC index
* @modpath: the hardware_path struct to match a device against
* @return: The corresponding device if found, NULL otherwise.
*
* Checks all the children of @parent for a matching @id. If none
* found, it returns NULL.
*/
static struct device *
parse_tree_node(struct device *parent, int index, struct hardware_path *modpath)
{
struct parse_tree_data d = {
.index = index,
.modpath = modpath,
};
struct recurse_struct recurse_data = {
.obj = &d,
.fn = check_parent,
};
if (device_for_each_child(parent, &recurse_data, descend_children))
/* nothing */;
return d.dev;
}
/**
* hwpath_to_device - Finds the generic device corresponding to a given hardware path.
* @modpath: the hardware path.
* @return: The target device, NULL if not found.
*/
struct device *hwpath_to_device(struct hardware_path *modpath)
{
int i;
struct device *parent = &root;
for (i = 0; i < 6; i++) {
if (modpath->bc[i] == -1)
continue;
parent = parse_tree_node(parent, i, modpath);
if (!parent)
return NULL;
}
if (is_pci_dev(parent)) /* pci devices already parse MOD */
return parent;
else
return parse_tree_node(parent, 6, modpath);
}
EXPORT_SYMBOL(hwpath_to_device);
/**
* device_to_hwpath - Populates the hwpath corresponding to the given device.
* @param dev the target device
* @param path pointer to a previously allocated hwpath struct to be filled in
*/
void device_to_hwpath(struct device *dev, struct hardware_path *path)
{
struct parisc_device *padev;
if (dev->bus == &parisc_bus_type) {
padev = to_parisc_device(dev);
get_node_path(dev->parent, path);
path->mod = padev->hw_path;
} else if (is_pci_dev(dev)) {
get_node_path(dev, path);
}
}
EXPORT_SYMBOL(device_to_hwpath);
#define BC_PORT_MASK 0x8
#define BC_LOWER_PORT 0x8
#define BUS_CONVERTER(dev) \
((dev->id.hw_type == HPHW_IOA) || (dev->id.hw_type == HPHW_BCPORT))
#define IS_LOWER_PORT(dev) \
((gsc_readl(dev->hpa.start + offsetof(struct bc_module, io_status)) \
& BC_PORT_MASK) == BC_LOWER_PORT)
#define MAX_NATIVE_DEVICES 64
#define NATIVE_DEVICE_OFFSET 0x1000
#define FLEX_MASK F_EXTEND(0xfffc0000)
#define IO_IO_LOW offsetof(struct bc_module, io_io_low)
#define IO_IO_HIGH offsetof(struct bc_module, io_io_high)
#define READ_IO_IO_LOW(dev) (unsigned long)(signed int)gsc_readl(dev->hpa.start + IO_IO_LOW)
#define READ_IO_IO_HIGH(dev) (unsigned long)(signed int)gsc_readl(dev->hpa.start + IO_IO_HIGH)
static void walk_native_bus(unsigned long io_io_low, unsigned long io_io_high,
struct device *parent);
void walk_lower_bus(struct parisc_device *dev)
{
unsigned long io_io_low, io_io_high;
if (!BUS_CONVERTER(dev) || IS_LOWER_PORT(dev))
return;
if (dev->id.hw_type == HPHW_IOA) {
io_io_low = (unsigned long)(signed int)(READ_IO_IO_LOW(dev) << 16);
io_io_high = io_io_low + MAX_NATIVE_DEVICES * NATIVE_DEVICE_OFFSET;
} else {
io_io_low = (READ_IO_IO_LOW(dev) + ~FLEX_MASK) & FLEX_MASK;
io_io_high = (READ_IO_IO_HIGH(dev)+ ~FLEX_MASK) & FLEX_MASK;
}
walk_native_bus(io_io_low, io_io_high, &dev->dev);
}
/**
* walk_native_bus -- Probe a bus for devices
* @io_io_low: Base address of this bus.
* @io_io_high: Last address of this bus.
* @parent: The parent bus device.
*
* A native bus (eg Runway or GSC) may have up to 64 devices on it,
* spaced at intervals of 0x1000 bytes. PDC may not inform us of these
* devices, so we have to probe for them. Unfortunately, we may find
* devices which are not physically connected (such as extra serial &
* keyboard ports). This problem is not yet solved.
*/
static void walk_native_bus(unsigned long io_io_low, unsigned long io_io_high,
struct device *parent)
{
int i, devices_found = 0;
unsigned long hpa = io_io_low;
struct hardware_path path;
get_node_path(parent, &path);
do {
for(i = 0; i < MAX_NATIVE_DEVICES; i++, hpa += NATIVE_DEVICE_OFFSET) {
struct parisc_device *dev;
/* Was the device already added by Firmware? */
dev = find_device_by_addr(hpa);
if (!dev) {
path.mod = i;
dev = alloc_pa_dev(hpa, &path);
if (!dev)
continue;
register_parisc_device(dev);
devices_found++;
}
walk_lower_bus(dev);
}
} while(!devices_found && hpa < io_io_high);
}
#define CENTRAL_BUS_ADDR F_EXTEND(0xfff80000)
/**
* walk_central_bus - Find devices attached to the central bus
*
* PDC doesn't tell us about all devices in the system. This routine
* finds devices connected to the central bus.
*/
void walk_central_bus(void)
{
walk_native_bus(CENTRAL_BUS_ADDR,
CENTRAL_BUS_ADDR + (MAX_NATIVE_DEVICES * NATIVE_DEVICE_OFFSET),
&root);
}
static void print_parisc_device(struct parisc_device *dev)
{
char hw_path[64];
static int count;
print_pa_hwpath(dev, hw_path);
printk(KERN_INFO "%d. %s at 0x%p [%s] { %d, 0x%x, 0x%.3x, 0x%.5x }",
++count, dev->name, (void*) dev->hpa.start, hw_path, dev->id.hw_type,
dev->id.hversion_rev, dev->id.hversion, dev->id.sversion);
if (dev->num_addrs) {
int k;
printk(", additional addresses: ");
for (k = 0; k < dev->num_addrs; k++)
printk("0x%lx ", dev->addr[k]);
}
printk("\n");
}
/**
* init_parisc_bus - Some preparation to be done before inventory
*/
void init_parisc_bus(void)
{
if (bus_register(&parisc_bus_type))
panic("Could not register PA-RISC bus type\n");
if (device_register(&root))
panic("Could not register PA-RISC root device\n");
get_device(&root);
}
static int print_one_device(struct device * dev, void * data)
{
struct parisc_device * pdev = to_parisc_device(dev);
if (check_dev(dev))
print_parisc_device(pdev);
return 0;
}
/**
* print_parisc_devices - Print out a list of devices found in this system
*/
void print_parisc_devices(void)
{
for_each_padev(print_one_device, NULL);
}
| gpl-2.0 |
javelinanddart/kernel_zte_draconis | arch/arm/mach-s3c64xx/common.c | 4735 | 9320 | /*
* Copyright (c) 2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* Copyright 2008 Openmoko, Inc.
* Copyright 2008 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
* http://armlinux.simtec.co.uk/
*
* Common Codes for S3C64XX machines
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/dma-mapping.h>
#include <linux/irq.h>
#include <linux/gpio.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/hardware/vic.h>
#include <asm/system_misc.h>
#include <mach/map.h>
#include <mach/hardware.h>
#include <mach/regs-gpio.h>
#include <plat/cpu.h>
#include <plat/clock.h>
#include <plat/devs.h>
#include <plat/pm.h>
#include <plat/gpio-cfg.h>
#include <plat/irq-uart.h>
#include <plat/irq-vic-timer.h>
#include <plat/regs-irqtype.h>
#include <plat/regs-serial.h>
#include <plat/watchdog-reset.h>
#include "common.h"
/* uart registration process */
static void __init s3c64xx_init_uarts(struct s3c2410_uartcfg *cfg, int no)
{
s3c24xx_init_uartdevs("s3c6400-uart", s3c64xx_uart_resources, cfg, no);
}
/* table of supported CPUs */
static const char name_s3c6400[] = "S3C6400";
static const char name_s3c6410[] = "S3C6410";
static struct cpu_table cpu_ids[] __initdata = {
{
.idcode = S3C6400_CPU_ID,
.idmask = S3C64XX_CPU_MASK,
.map_io = s3c6400_map_io,
.init_clocks = s3c6400_init_clocks,
.init_uarts = s3c64xx_init_uarts,
.init = s3c6400_init,
.name = name_s3c6400,
}, {
.idcode = S3C6410_CPU_ID,
.idmask = S3C64XX_CPU_MASK,
.map_io = s3c6410_map_io,
.init_clocks = s3c6410_init_clocks,
.init_uarts = s3c64xx_init_uarts,
.init = s3c6410_init,
.name = name_s3c6410,
},
};
/* minimal IO mapping */
/* see notes on uart map in arch/arm/mach-s3c64xx/include/mach/debug-macro.S */
#define UART_OFFS (S3C_PA_UART & 0xfffff)
static struct map_desc s3c_iodesc[] __initdata = {
{
.virtual = (unsigned long)S3C_VA_SYS,
.pfn = __phys_to_pfn(S3C64XX_PA_SYSCON),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S3C_VA_MEM,
.pfn = __phys_to_pfn(S3C64XX_PA_SROM),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)(S3C_VA_UART + UART_OFFS),
.pfn = __phys_to_pfn(S3C_PA_UART),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)VA_VIC0,
.pfn = __phys_to_pfn(S3C64XX_PA_VIC0),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)VA_VIC1,
.pfn = __phys_to_pfn(S3C64XX_PA_VIC1),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S3C_VA_TIMER,
.pfn = __phys_to_pfn(S3C_PA_TIMER),
.length = SZ_16K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S3C64XX_VA_GPIO,
.pfn = __phys_to_pfn(S3C64XX_PA_GPIO),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S3C64XX_VA_MODEM,
.pfn = __phys_to_pfn(S3C64XX_PA_MODEM),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S3C_VA_WATCHDOG,
.pfn = __phys_to_pfn(S3C64XX_PA_WATCHDOG),
.length = SZ_4K,
.type = MT_DEVICE,
}, {
.virtual = (unsigned long)S3C_VA_USB_HSPHY,
.pfn = __phys_to_pfn(S3C64XX_PA_USB_HSPHY),
.length = SZ_1K,
.type = MT_DEVICE,
},
};
static struct bus_type s3c64xx_subsys = {
.name = "s3c64xx-core",
.dev_name = "s3c64xx-core",
};
static struct device s3c64xx_dev = {
.bus = &s3c64xx_subsys,
};
/* read cpu identification code */
void __init s3c64xx_init_io(struct map_desc *mach_desc, int size)
{
/* initialise the io descriptors we need for initialisation */
iotable_init(s3c_iodesc, ARRAY_SIZE(s3c_iodesc));
iotable_init(mach_desc, size);
init_consistent_dma_size(SZ_8M);
/* detect cpu id */
s3c64xx_init_cpu();
s3c_init_cpu(samsung_cpu_id, cpu_ids, ARRAY_SIZE(cpu_ids));
}
static __init int s3c64xx_dev_init(void)
{
subsys_system_register(&s3c64xx_subsys, NULL);
return device_register(&s3c64xx_dev);
}
core_initcall(s3c64xx_dev_init);
/*
* setup the sources the vic should advertise resume
* for, even though it is not doing the wake
* (set_irq_wake needs to be valid)
*/
#define IRQ_VIC0_RESUME (1 << (IRQ_RTC_TIC - IRQ_VIC0_BASE))
#define IRQ_VIC1_RESUME (1 << (IRQ_RTC_ALARM - IRQ_VIC1_BASE) | \
1 << (IRQ_PENDN - IRQ_VIC1_BASE) | \
1 << (IRQ_HSMMC0 - IRQ_VIC1_BASE) | \
1 << (IRQ_HSMMC1 - IRQ_VIC1_BASE) | \
1 << (IRQ_HSMMC2 - IRQ_VIC1_BASE))
void __init s3c64xx_init_irq(u32 vic0_valid, u32 vic1_valid)
{
printk(KERN_DEBUG "%s: initialising interrupts\n", __func__);
/* initialise the pair of VICs */
vic_init(VA_VIC0, IRQ_VIC0_BASE, vic0_valid, IRQ_VIC0_RESUME);
vic_init(VA_VIC1, IRQ_VIC1_BASE, vic1_valid, IRQ_VIC1_RESUME);
/* add the timer sub-irqs */
s3c_init_vic_timer_irq(5, IRQ_TIMER0);
}
#define eint_offset(irq) ((irq) - IRQ_EINT(0))
#define eint_irq_to_bit(irq) ((u32)(1 << eint_offset(irq)))
static inline void s3c_irq_eint_mask(struct irq_data *data)
{
u32 mask;
mask = __raw_readl(S3C64XX_EINT0MASK);
mask |= (u32)data->chip_data;
__raw_writel(mask, S3C64XX_EINT0MASK);
}
static void s3c_irq_eint_unmask(struct irq_data *data)
{
u32 mask;
mask = __raw_readl(S3C64XX_EINT0MASK);
mask &= ~((u32)data->chip_data);
__raw_writel(mask, S3C64XX_EINT0MASK);
}
static inline void s3c_irq_eint_ack(struct irq_data *data)
{
__raw_writel((u32)data->chip_data, S3C64XX_EINT0PEND);
}
static void s3c_irq_eint_maskack(struct irq_data *data)
{
/* compiler should in-line these */
s3c_irq_eint_mask(data);
s3c_irq_eint_ack(data);
}
static int s3c_irq_eint_set_type(struct irq_data *data, unsigned int type)
{
int offs = eint_offset(data->irq);
int pin, pin_val;
int shift;
u32 ctrl, mask;
u32 newvalue = 0;
void __iomem *reg;
if (offs > 27)
return -EINVAL;
if (offs <= 15)
reg = S3C64XX_EINT0CON0;
else
reg = S3C64XX_EINT0CON1;
switch (type) {
case IRQ_TYPE_NONE:
printk(KERN_WARNING "No edge setting!\n");
break;
case IRQ_TYPE_EDGE_RISING:
newvalue = S3C2410_EXTINT_RISEEDGE;
break;
case IRQ_TYPE_EDGE_FALLING:
newvalue = S3C2410_EXTINT_FALLEDGE;
break;
case IRQ_TYPE_EDGE_BOTH:
newvalue = S3C2410_EXTINT_BOTHEDGE;
break;
case IRQ_TYPE_LEVEL_LOW:
newvalue = S3C2410_EXTINT_LOWLEV;
break;
case IRQ_TYPE_LEVEL_HIGH:
newvalue = S3C2410_EXTINT_HILEV;
break;
default:
printk(KERN_ERR "No such irq type %d", type);
return -1;
}
if (offs <= 15)
shift = (offs / 2) * 4;
else
shift = ((offs - 16) / 2) * 4;
mask = 0x7 << shift;
ctrl = __raw_readl(reg);
ctrl &= ~mask;
ctrl |= newvalue << shift;
__raw_writel(ctrl, reg);
/* set the GPIO pin appropriately */
if (offs < 16) {
pin = S3C64XX_GPN(offs);
pin_val = S3C_GPIO_SFN(2);
} else if (offs < 23) {
pin = S3C64XX_GPL(offs + 8 - 16);
pin_val = S3C_GPIO_SFN(3);
} else {
pin = S3C64XX_GPM(offs - 23);
pin_val = S3C_GPIO_SFN(3);
}
s3c_gpio_cfgpin(pin, pin_val);
return 0;
}
static struct irq_chip s3c_irq_eint = {
.name = "s3c-eint",
.irq_mask = s3c_irq_eint_mask,
.irq_unmask = s3c_irq_eint_unmask,
.irq_mask_ack = s3c_irq_eint_maskack,
.irq_ack = s3c_irq_eint_ack,
.irq_set_type = s3c_irq_eint_set_type,
.irq_set_wake = s3c_irqext_wake,
};
/* s3c_irq_demux_eint
*
* This function demuxes the IRQ from the group0 external interrupts,
* from IRQ_EINT(0) to IRQ_EINT(27). It is designed to be inlined into
* the specific handlers s3c_irq_demux_eintX_Y.
*/
static inline void s3c_irq_demux_eint(unsigned int start, unsigned int end)
{
u32 status = __raw_readl(S3C64XX_EINT0PEND);
u32 mask = __raw_readl(S3C64XX_EINT0MASK);
unsigned int irq;
status &= ~mask;
status >>= start;
status &= (1 << (end - start + 1)) - 1;
for (irq = IRQ_EINT(start); irq <= IRQ_EINT(end); irq++) {
if (status & 1)
generic_handle_irq(irq);
status >>= 1;
}
}
static void s3c_irq_demux_eint0_3(unsigned int irq, struct irq_desc *desc)
{
s3c_irq_demux_eint(0, 3);
}
static void s3c_irq_demux_eint4_11(unsigned int irq, struct irq_desc *desc)
{
s3c_irq_demux_eint(4, 11);
}
static void s3c_irq_demux_eint12_19(unsigned int irq, struct irq_desc *desc)
{
s3c_irq_demux_eint(12, 19);
}
static void s3c_irq_demux_eint20_27(unsigned int irq, struct irq_desc *desc)
{
s3c_irq_demux_eint(20, 27);
}
static int __init s3c64xx_init_irq_eint(void)
{
int irq;
for (irq = IRQ_EINT(0); irq <= IRQ_EINT(27); irq++) {
irq_set_chip_and_handler(irq, &s3c_irq_eint, handle_level_irq);
irq_set_chip_data(irq, (void *)eint_irq_to_bit(irq));
set_irq_flags(irq, IRQF_VALID);
}
irq_set_chained_handler(IRQ_EINT0_3, s3c_irq_demux_eint0_3);
irq_set_chained_handler(IRQ_EINT4_11, s3c_irq_demux_eint4_11);
irq_set_chained_handler(IRQ_EINT12_19, s3c_irq_demux_eint12_19);
irq_set_chained_handler(IRQ_EINT20_27, s3c_irq_demux_eint20_27);
return 0;
}
arch_initcall(s3c64xx_init_irq_eint);
void s3c64xx_restart(char mode, const char *cmd)
{
if (mode != 's')
arch_wdt_reset();
/* if all else fails, or mode was for soft, jump to 0 */
soft_restart(0);
}
| gpl-2.0 |
pec0ra/williams | sound/spi/at73c213.c | 4991 | 28217 | /*
* Driver for AT73C213 16-bit stereo DAC connected to Atmel SSC
*
* Copyright (C) 2006-2007 Atmel Norway
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
/*#define DEBUG*/
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <sound/initval.h>
#include <sound/control.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <linux/atmel-ssc.h>
#include <linux/spi/spi.h>
#include <linux/spi/at73c213.h>
#include "at73c213.h"
#define BITRATE_MIN 8000 /* Hardware limit? */
#define BITRATE_TARGET CONFIG_SND_AT73C213_TARGET_BITRATE
#define BITRATE_MAX 50000 /* Hardware limit. */
/* Initial (hardware reset) AT73C213 register values. */
static u8 snd_at73c213_original_image[18] =
{
0x00, /* 00 - CTRL */
0x05, /* 01 - LLIG */
0x05, /* 02 - RLIG */
0x08, /* 03 - LPMG */
0x08, /* 04 - RPMG */
0x00, /* 05 - LLOG */
0x00, /* 06 - RLOG */
0x22, /* 07 - OLC */
0x09, /* 08 - MC */
0x00, /* 09 - CSFC */
0x00, /* 0A - MISC */
0x00, /* 0B - */
0x00, /* 0C - PRECH */
0x05, /* 0D - AUXG */
0x00, /* 0E - */
0x00, /* 0F - */
0x00, /* 10 - RST */
0x00, /* 11 - PA_CTRL */
};
struct snd_at73c213 {
struct snd_card *card;
struct snd_pcm *pcm;
struct snd_pcm_substream *substream;
struct at73c213_board_info *board;
int irq;
int period;
unsigned long bitrate;
struct ssc_device *ssc;
struct spi_device *spi;
u8 spi_wbuffer[2];
u8 spi_rbuffer[2];
/* Image of the SPI registers in AT73C213. */
u8 reg_image[18];
/* Protect SSC registers against concurrent access. */
spinlock_t lock;
/* Protect mixer registers against concurrent access. */
struct mutex mixer_lock;
};
#define get_chip(card) ((struct snd_at73c213 *)card->private_data)
static int
snd_at73c213_write_reg(struct snd_at73c213 *chip, u8 reg, u8 val)
{
struct spi_message msg;
struct spi_transfer msg_xfer = {
.len = 2,
.cs_change = 0,
};
int retval;
spi_message_init(&msg);
chip->spi_wbuffer[0] = reg;
chip->spi_wbuffer[1] = val;
msg_xfer.tx_buf = chip->spi_wbuffer;
msg_xfer.rx_buf = chip->spi_rbuffer;
spi_message_add_tail(&msg_xfer, &msg);
retval = spi_sync(chip->spi, &msg);
if (!retval)
chip->reg_image[reg] = val;
return retval;
}
static struct snd_pcm_hardware snd_at73c213_playback_hw = {
.info = SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER,
.formats = SNDRV_PCM_FMTBIT_S16_BE,
.rates = SNDRV_PCM_RATE_CONTINUOUS,
.rate_min = 8000, /* Replaced by chip->bitrate later. */
.rate_max = 50000, /* Replaced by chip->bitrate later. */
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = 64 * 1024 - 1,
.period_bytes_min = 512,
.period_bytes_max = 64 * 1024 - 1,
.periods_min = 4,
.periods_max = 1024,
};
/*
* Calculate and set bitrate and divisions.
*/
static int snd_at73c213_set_bitrate(struct snd_at73c213 *chip)
{
unsigned long ssc_rate = clk_get_rate(chip->ssc->clk);
unsigned long dac_rate_new, ssc_div;
int status;
unsigned long ssc_div_max, ssc_div_min;
int max_tries;
/*
* We connect two clocks here, picking divisors so the I2S clocks
* out data at the same rate the DAC clocks it in ... and as close
* as practical to the desired target rate.
*
* The DAC master clock (MCLK) is programmable, and is either 256
* or (not here) 384 times the I2S output clock (BCLK).
*/
/* SSC clock / (bitrate * stereo * 16-bit). */
ssc_div = ssc_rate / (BITRATE_TARGET * 2 * 16);
ssc_div_min = ssc_rate / (BITRATE_MAX * 2 * 16);
ssc_div_max = ssc_rate / (BITRATE_MIN * 2 * 16);
max_tries = (ssc_div_max - ssc_div_min) / 2;
if (max_tries < 1)
max_tries = 1;
/* ssc_div must be even. */
ssc_div = (ssc_div + 1) & ~1UL;
if ((ssc_rate / (ssc_div * 2 * 16)) < BITRATE_MIN) {
ssc_div -= 2;
if ((ssc_rate / (ssc_div * 2 * 16)) > BITRATE_MAX)
return -ENXIO;
}
/* Search for a possible bitrate. */
do {
/* SSC clock / (ssc divider * 16-bit * stereo). */
if ((ssc_rate / (ssc_div * 2 * 16)) < BITRATE_MIN)
return -ENXIO;
/* 256 / (2 * 16) = 8 */
dac_rate_new = 8 * (ssc_rate / ssc_div);
status = clk_round_rate(chip->board->dac_clk, dac_rate_new);
if (status < 0)
return status;
/* Ignore difference smaller than 256 Hz. */
if ((status/256) == (dac_rate_new/256))
goto set_rate;
ssc_div += 2;
} while (--max_tries);
/* Not able to find a valid bitrate. */
return -ENXIO;
set_rate:
status = clk_set_rate(chip->board->dac_clk, status);
if (status < 0)
return status;
/* Set divider in SSC device. */
ssc_writel(chip->ssc->regs, CMR, ssc_div/2);
/* SSC clock / (ssc divider * 16-bit * stereo). */
chip->bitrate = ssc_rate / (ssc_div * 16 * 2);
dev_info(&chip->spi->dev,
"at73c213: supported bitrate is %lu (%lu divider)\n",
chip->bitrate, ssc_div);
return 0;
}
static int snd_at73c213_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int err;
/* ensure buffer_size is a multiple of period_size */
err = snd_pcm_hw_constraint_integer(runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (err < 0)
return err;
snd_at73c213_playback_hw.rate_min = chip->bitrate;
snd_at73c213_playback_hw.rate_max = chip->bitrate;
runtime->hw = snd_at73c213_playback_hw;
chip->substream = substream;
return 0;
}
static int snd_at73c213_pcm_close(struct snd_pcm_substream *substream)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
chip->substream = NULL;
return 0;
}
static int snd_at73c213_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *hw_params)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
int channels = params_channels(hw_params);
int val;
val = ssc_readl(chip->ssc->regs, TFMR);
val = SSC_BFINS(TFMR_DATNB, channels - 1, val);
ssc_writel(chip->ssc->regs, TFMR, val);
return snd_pcm_lib_malloc_pages(substream,
params_buffer_bytes(hw_params));
}
static int snd_at73c213_pcm_hw_free(struct snd_pcm_substream *substream)
{
return snd_pcm_lib_free_pages(substream);
}
static int snd_at73c213_pcm_prepare(struct snd_pcm_substream *substream)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
int block_size;
block_size = frames_to_bytes(runtime, runtime->period_size);
chip->period = 0;
ssc_writel(chip->ssc->regs, PDC_TPR,
(long)runtime->dma_addr);
ssc_writel(chip->ssc->regs, PDC_TCR,
runtime->period_size * runtime->channels);
ssc_writel(chip->ssc->regs, PDC_TNPR,
(long)runtime->dma_addr + block_size);
ssc_writel(chip->ssc->regs, PDC_TNCR,
runtime->period_size * runtime->channels);
return 0;
}
static int snd_at73c213_pcm_trigger(struct snd_pcm_substream *substream,
int cmd)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
int retval = 0;
spin_lock(&chip->lock);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
ssc_writel(chip->ssc->regs, IER, SSC_BIT(IER_ENDTX));
ssc_writel(chip->ssc->regs, PDC_PTCR, SSC_BIT(PDC_PTCR_TXTEN));
break;
case SNDRV_PCM_TRIGGER_STOP:
ssc_writel(chip->ssc->regs, PDC_PTCR, SSC_BIT(PDC_PTCR_TXTDIS));
ssc_writel(chip->ssc->regs, IDR, SSC_BIT(IDR_ENDTX));
break;
default:
dev_dbg(&chip->spi->dev, "spurious command %x\n", cmd);
retval = -EINVAL;
break;
}
spin_unlock(&chip->lock);
return retval;
}
static snd_pcm_uframes_t
snd_at73c213_pcm_pointer(struct snd_pcm_substream *substream)
{
struct snd_at73c213 *chip = snd_pcm_substream_chip(substream);
struct snd_pcm_runtime *runtime = substream->runtime;
snd_pcm_uframes_t pos;
unsigned long bytes;
bytes = ssc_readl(chip->ssc->regs, PDC_TPR)
- (unsigned long)runtime->dma_addr;
pos = bytes_to_frames(runtime, bytes);
if (pos >= runtime->buffer_size)
pos -= runtime->buffer_size;
return pos;
}
static struct snd_pcm_ops at73c213_playback_ops = {
.open = snd_at73c213_pcm_open,
.close = snd_at73c213_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.hw_params = snd_at73c213_pcm_hw_params,
.hw_free = snd_at73c213_pcm_hw_free,
.prepare = snd_at73c213_pcm_prepare,
.trigger = snd_at73c213_pcm_trigger,
.pointer = snd_at73c213_pcm_pointer,
};
static int __devinit snd_at73c213_pcm_new(struct snd_at73c213 *chip, int device)
{
struct snd_pcm *pcm;
int retval;
retval = snd_pcm_new(chip->card, chip->card->shortname,
device, 1, 0, &pcm);
if (retval < 0)
goto out;
pcm->private_data = chip;
pcm->info_flags = SNDRV_PCM_INFO_BLOCK_TRANSFER;
strcpy(pcm->name, "at73c213");
chip->pcm = pcm;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &at73c213_playback_ops);
retval = snd_pcm_lib_preallocate_pages_for_all(chip->pcm,
SNDRV_DMA_TYPE_DEV, &chip->ssc->pdev->dev,
64 * 1024, 64 * 1024);
out:
return retval;
}
static irqreturn_t snd_at73c213_interrupt(int irq, void *dev_id)
{
struct snd_at73c213 *chip = dev_id;
struct snd_pcm_runtime *runtime = chip->substream->runtime;
u32 status;
int offset;
int block_size;
int next_period;
int retval = IRQ_NONE;
spin_lock(&chip->lock);
block_size = frames_to_bytes(runtime, runtime->period_size);
status = ssc_readl(chip->ssc->regs, IMR);
if (status & SSC_BIT(IMR_ENDTX)) {
chip->period++;
if (chip->period == runtime->periods)
chip->period = 0;
next_period = chip->period + 1;
if (next_period == runtime->periods)
next_period = 0;
offset = block_size * next_period;
ssc_writel(chip->ssc->regs, PDC_TNPR,
(long)runtime->dma_addr + offset);
ssc_writel(chip->ssc->regs, PDC_TNCR,
runtime->period_size * runtime->channels);
retval = IRQ_HANDLED;
}
ssc_readl(chip->ssc->regs, IMR);
spin_unlock(&chip->lock);
if (status & SSC_BIT(IMR_ENDTX))
snd_pcm_period_elapsed(chip->substream);
return retval;
}
/*
* Mixer functions.
*/
static int snd_at73c213_mono_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
mutex_lock(&chip->mixer_lock);
ucontrol->value.integer.value[0] =
(chip->reg_image[reg] >> shift) & mask;
if (invert)
ucontrol->value.integer.value[0] =
mask - ucontrol->value.integer.value[0];
mutex_unlock(&chip->mixer_lock);
return 0;
}
static int snd_at73c213_mono_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
int change, retval;
unsigned short val;
val = (ucontrol->value.integer.value[0] & mask);
if (invert)
val = mask - val;
val <<= shift;
mutex_lock(&chip->mixer_lock);
val = (chip->reg_image[reg] & ~(mask << shift)) | val;
change = val != chip->reg_image[reg];
retval = snd_at73c213_write_reg(chip, reg, val);
mutex_unlock(&chip->mixer_lock);
if (retval)
return retval;
return change;
}
static int snd_at73c213_stereo_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
int mask = (kcontrol->private_value >> 24) & 0xff;
if (mask == 1)
uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
else
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int snd_at73c213_stereo_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
mutex_lock(&chip->mixer_lock);
ucontrol->value.integer.value[0] =
(chip->reg_image[left_reg] >> shift_left) & mask;
ucontrol->value.integer.value[1] =
(chip->reg_image[right_reg] >> shift_right) & mask;
if (invert) {
ucontrol->value.integer.value[0] =
mask - ucontrol->value.integer.value[0];
ucontrol->value.integer.value[1] =
mask - ucontrol->value.integer.value[1];
}
mutex_unlock(&chip->mixer_lock);
return 0;
}
static int snd_at73c213_stereo_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int left_reg = kcontrol->private_value & 0xff;
int right_reg = (kcontrol->private_value >> 8) & 0xff;
int shift_left = (kcontrol->private_value >> 16) & 0x07;
int shift_right = (kcontrol->private_value >> 19) & 0x07;
int mask = (kcontrol->private_value >> 24) & 0xff;
int invert = (kcontrol->private_value >> 22) & 1;
int change, retval;
unsigned short val1, val2;
val1 = ucontrol->value.integer.value[0] & mask;
val2 = ucontrol->value.integer.value[1] & mask;
if (invert) {
val1 = mask - val1;
val2 = mask - val2;
}
val1 <<= shift_left;
val2 <<= shift_right;
mutex_lock(&chip->mixer_lock);
val1 = (chip->reg_image[left_reg] & ~(mask << shift_left)) | val1;
val2 = (chip->reg_image[right_reg] & ~(mask << shift_right)) | val2;
change = val1 != chip->reg_image[left_reg]
|| val2 != chip->reg_image[right_reg];
retval = snd_at73c213_write_reg(chip, left_reg, val1);
if (retval) {
mutex_unlock(&chip->mixer_lock);
goto out;
}
retval = snd_at73c213_write_reg(chip, right_reg, val2);
if (retval) {
mutex_unlock(&chip->mixer_lock);
goto out;
}
mutex_unlock(&chip->mixer_lock);
return change;
out:
return retval;
}
#define snd_at73c213_mono_switch_info snd_ctl_boolean_mono_info
static int snd_at73c213_mono_switch_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
mutex_lock(&chip->mixer_lock);
ucontrol->value.integer.value[0] =
(chip->reg_image[reg] >> shift) & 0x01;
if (invert)
ucontrol->value.integer.value[0] =
0x01 - ucontrol->value.integer.value[0];
mutex_unlock(&chip->mixer_lock);
return 0;
}
static int snd_at73c213_mono_switch_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct snd_at73c213 *chip = snd_kcontrol_chip(kcontrol);
int reg = kcontrol->private_value & 0xff;
int shift = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
int change, retval;
unsigned short val;
if (ucontrol->value.integer.value[0])
val = mask;
else
val = 0;
if (invert)
val = mask - val;
val <<= shift;
mutex_lock(&chip->mixer_lock);
val |= (chip->reg_image[reg] & ~(mask << shift));
change = val != chip->reg_image[reg];
retval = snd_at73c213_write_reg(chip, reg, val);
mutex_unlock(&chip->mixer_lock);
if (retval)
return retval;
return change;
}
static int snd_at73c213_pa_volume_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = ((kcontrol->private_value >> 16) & 0xff) - 1;
return 0;
}
static int snd_at73c213_line_capture_volume_info(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 2;
/* When inverted will give values 0x10001 => 0. */
uinfo->value.integer.min = 14;
uinfo->value.integer.max = 31;
return 0;
}
static int snd_at73c213_aux_capture_volume_info(
struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
/* When inverted will give values 0x10001 => 0. */
uinfo->value.integer.min = 14;
uinfo->value.integer.max = 31;
return 0;
}
#define AT73C213_MONO_SWITCH(xname, xindex, reg, shift, mask, invert) \
{ \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = xname, \
.index = xindex, \
.info = snd_at73c213_mono_switch_info, \
.get = snd_at73c213_mono_switch_get, \
.put = snd_at73c213_mono_switch_put, \
.private_value = (reg | (shift << 8) | (mask << 16) | (invert << 24)) \
}
#define AT73C213_STEREO(xname, xindex, left_reg, right_reg, shift_left, shift_right, mask, invert) \
{ \
.iface = SNDRV_CTL_ELEM_IFACE_MIXER, \
.name = xname, \
.index = xindex, \
.info = snd_at73c213_stereo_info, \
.get = snd_at73c213_stereo_get, \
.put = snd_at73c213_stereo_put, \
.private_value = (left_reg | (right_reg << 8) \
| (shift_left << 16) | (shift_right << 19) \
| (mask << 24) | (invert << 22)) \
}
static struct snd_kcontrol_new snd_at73c213_controls[] __devinitdata = {
AT73C213_STEREO("Master Playback Volume", 0, DAC_LMPG, DAC_RMPG, 0, 0, 0x1f, 1),
AT73C213_STEREO("Master Playback Switch", 0, DAC_LMPG, DAC_RMPG, 5, 5, 1, 1),
AT73C213_STEREO("PCM Playback Volume", 0, DAC_LLOG, DAC_RLOG, 0, 0, 0x1f, 1),
AT73C213_STEREO("PCM Playback Switch", 0, DAC_LLOG, DAC_RLOG, 5, 5, 1, 1),
AT73C213_MONO_SWITCH("Mono PA Playback Switch", 0, DAC_CTRL, DAC_CTRL_ONPADRV,
0x01, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "PA Playback Volume",
.index = 0,
.info = snd_at73c213_pa_volume_info,
.get = snd_at73c213_mono_get,
.put = snd_at73c213_mono_put,
.private_value = PA_CTRL | (PA_CTRL_APAGAIN << 8) | \
(0x0f << 16) | (1 << 24),
},
AT73C213_MONO_SWITCH("PA High Gain Playback Switch", 0, PA_CTRL, PA_CTRL_APALP,
0x01, 1),
AT73C213_MONO_SWITCH("PA Playback Switch", 0, PA_CTRL, PA_CTRL_APAON, 0x01, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Aux Capture Volume",
.index = 0,
.info = snd_at73c213_aux_capture_volume_info,
.get = snd_at73c213_mono_get,
.put = snd_at73c213_mono_put,
.private_value = DAC_AUXG | (0 << 8) | (0x1f << 16) | (1 << 24),
},
AT73C213_MONO_SWITCH("Aux Capture Switch", 0, DAC_CTRL, DAC_CTRL_ONAUXIN,
0x01, 0),
{
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Line Capture Volume",
.index = 0,
.info = snd_at73c213_line_capture_volume_info,
.get = snd_at73c213_stereo_get,
.put = snd_at73c213_stereo_put,
.private_value = DAC_LLIG | (DAC_RLIG << 8) | (0 << 16) | (0 << 19)
| (0x1f << 24) | (1 << 22),
},
AT73C213_MONO_SWITCH("Line Capture Switch", 0, DAC_CTRL, 0, 0x03, 0),
};
static int __devinit snd_at73c213_mixer(struct snd_at73c213 *chip)
{
struct snd_card *card;
int errval, idx;
if (chip == NULL || chip->pcm == NULL)
return -EINVAL;
card = chip->card;
strcpy(card->mixername, chip->pcm->name);
for (idx = 0; idx < ARRAY_SIZE(snd_at73c213_controls); idx++) {
errval = snd_ctl_add(card,
snd_ctl_new1(&snd_at73c213_controls[idx],
chip));
if (errval < 0)
goto cleanup;
}
return 0;
cleanup:
for (idx = 1; idx < ARRAY_SIZE(snd_at73c213_controls) + 1; idx++) {
struct snd_kcontrol *kctl;
kctl = snd_ctl_find_numid(card, idx);
if (kctl)
snd_ctl_remove(card, kctl);
}
return errval;
}
/*
* Device functions
*/
static int __devinit snd_at73c213_ssc_init(struct snd_at73c213 *chip)
{
/*
* Continuous clock output.
* Starts on falling TF.
* Delay 1 cycle (1 bit).
* Periode is 16 bit (16 - 1).
*/
ssc_writel(chip->ssc->regs, TCMR,
SSC_BF(TCMR_CKO, 1)
| SSC_BF(TCMR_START, 4)
| SSC_BF(TCMR_STTDLY, 1)
| SSC_BF(TCMR_PERIOD, 16 - 1));
/*
* Data length is 16 bit (16 - 1).
* Transmit MSB first.
* Transmit 2 words each transfer.
* Frame sync length is 16 bit (16 - 1).
* Frame starts on negative pulse.
*/
ssc_writel(chip->ssc->regs, TFMR,
SSC_BF(TFMR_DATLEN, 16 - 1)
| SSC_BIT(TFMR_MSBF)
| SSC_BF(TFMR_DATNB, 1)
| SSC_BF(TFMR_FSLEN, 16 - 1)
| SSC_BF(TFMR_FSOS, 1));
return 0;
}
static int __devinit snd_at73c213_chip_init(struct snd_at73c213 *chip)
{
int retval;
unsigned char dac_ctrl = 0;
retval = snd_at73c213_set_bitrate(chip);
if (retval)
goto out;
/* Enable DAC master clock. */
clk_enable(chip->board->dac_clk);
/* Initialize at73c213 on SPI bus. */
retval = snd_at73c213_write_reg(chip, DAC_RST, 0x04);
if (retval)
goto out_clk;
msleep(1);
retval = snd_at73c213_write_reg(chip, DAC_RST, 0x03);
if (retval)
goto out_clk;
/* Precharge everything. */
retval = snd_at73c213_write_reg(chip, DAC_PRECH, 0xff);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, PA_CTRL, (1<<PA_CTRL_APAPRECH));
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_CTRL,
(1<<DAC_CTRL_ONLNOL) | (1<<DAC_CTRL_ONLNOR));
if (retval)
goto out_clk;
msleep(50);
/* Stop precharging PA. */
retval = snd_at73c213_write_reg(chip, PA_CTRL,
(1<<PA_CTRL_APALP) | 0x0f);
if (retval)
goto out_clk;
msleep(450);
/* Stop precharging DAC, turn on master power. */
retval = snd_at73c213_write_reg(chip, DAC_PRECH, (1<<DAC_PRECH_ONMSTR));
if (retval)
goto out_clk;
msleep(1);
/* Turn on DAC. */
dac_ctrl = (1<<DAC_CTRL_ONDACL) | (1<<DAC_CTRL_ONDACR)
| (1<<DAC_CTRL_ONLNOL) | (1<<DAC_CTRL_ONLNOR);
retval = snd_at73c213_write_reg(chip, DAC_CTRL, dac_ctrl);
if (retval)
goto out_clk;
/* Mute sound. */
retval = snd_at73c213_write_reg(chip, DAC_LMPG, 0x3f);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_RMPG, 0x3f);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_LLOG, 0x3f);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_RLOG, 0x3f);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_LLIG, 0x11);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_RLIG, 0x11);
if (retval)
goto out_clk;
retval = snd_at73c213_write_reg(chip, DAC_AUXG, 0x11);
if (retval)
goto out_clk;
/* Enable I2S device, i.e. clock output. */
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXEN));
goto out;
out_clk:
clk_disable(chip->board->dac_clk);
out:
return retval;
}
static int snd_at73c213_dev_free(struct snd_device *device)
{
struct snd_at73c213 *chip = device->device_data;
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXDIS));
if (chip->irq >= 0) {
free_irq(chip->irq, chip);
chip->irq = -1;
}
return 0;
}
static int __devinit snd_at73c213_dev_init(struct snd_card *card,
struct spi_device *spi)
{
static struct snd_device_ops ops = {
.dev_free = snd_at73c213_dev_free,
};
struct snd_at73c213 *chip = get_chip(card);
int irq, retval;
irq = chip->ssc->irq;
if (irq < 0)
return irq;
spin_lock_init(&chip->lock);
mutex_init(&chip->mixer_lock);
chip->card = card;
chip->irq = -1;
retval = request_irq(irq, snd_at73c213_interrupt, 0, "at73c213", chip);
if (retval) {
dev_dbg(&chip->spi->dev, "unable to request irq %d\n", irq);
goto out;
}
chip->irq = irq;
memcpy(&chip->reg_image, &snd_at73c213_original_image,
sizeof(snd_at73c213_original_image));
retval = snd_at73c213_ssc_init(chip);
if (retval)
goto out_irq;
retval = snd_at73c213_chip_init(chip);
if (retval)
goto out_irq;
retval = snd_at73c213_pcm_new(chip, 0);
if (retval)
goto out_irq;
retval = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
if (retval)
goto out_irq;
retval = snd_at73c213_mixer(chip);
if (retval)
goto out_snd_dev;
snd_card_set_dev(card, &spi->dev);
goto out;
out_snd_dev:
snd_device_free(card, chip);
out_irq:
free_irq(chip->irq, chip);
chip->irq = -1;
out:
return retval;
}
static int __devinit snd_at73c213_probe(struct spi_device *spi)
{
struct snd_card *card;
struct snd_at73c213 *chip;
struct at73c213_board_info *board;
int retval;
char id[16];
board = spi->dev.platform_data;
if (!board) {
dev_dbg(&spi->dev, "no platform_data\n");
return -ENXIO;
}
if (!board->dac_clk) {
dev_dbg(&spi->dev, "no DAC clk\n");
return -ENXIO;
}
if (IS_ERR(board->dac_clk)) {
dev_dbg(&spi->dev, "no DAC clk\n");
return PTR_ERR(board->dac_clk);
}
/* Allocate "card" using some unused identifiers. */
snprintf(id, sizeof id, "at73c213_%d", board->ssc_id);
retval = snd_card_create(-1, id, THIS_MODULE,
sizeof(struct snd_at73c213), &card);
if (retval < 0)
goto out;
chip = card->private_data;
chip->spi = spi;
chip->board = board;
chip->ssc = ssc_request(board->ssc_id);
if (IS_ERR(chip->ssc)) {
dev_dbg(&spi->dev, "could not get ssc%d device\n",
board->ssc_id);
retval = PTR_ERR(chip->ssc);
goto out_card;
}
retval = snd_at73c213_dev_init(card, spi);
if (retval)
goto out_ssc;
strcpy(card->driver, "at73c213");
strcpy(card->shortname, board->shortname);
sprintf(card->longname, "%s on irq %d", card->shortname, chip->irq);
retval = snd_card_register(card);
if (retval)
goto out_ssc;
dev_set_drvdata(&spi->dev, card);
goto out;
out_ssc:
ssc_free(chip->ssc);
out_card:
snd_card_free(card);
out:
return retval;
}
static int __devexit snd_at73c213_remove(struct spi_device *spi)
{
struct snd_card *card = dev_get_drvdata(&spi->dev);
struct snd_at73c213 *chip = card->private_data;
int retval;
/* Stop playback. */
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXDIS));
/* Mute sound. */
retval = snd_at73c213_write_reg(chip, DAC_LMPG, 0x3f);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_RMPG, 0x3f);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_LLOG, 0x3f);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_RLOG, 0x3f);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_LLIG, 0x11);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_RLIG, 0x11);
if (retval)
goto out;
retval = snd_at73c213_write_reg(chip, DAC_AUXG, 0x11);
if (retval)
goto out;
/* Turn off PA. */
retval = snd_at73c213_write_reg(chip, PA_CTRL,
chip->reg_image[PA_CTRL] | 0x0f);
if (retval)
goto out;
msleep(10);
retval = snd_at73c213_write_reg(chip, PA_CTRL,
(1 << PA_CTRL_APALP) | 0x0f);
if (retval)
goto out;
/* Turn off external DAC. */
retval = snd_at73c213_write_reg(chip, DAC_CTRL, 0x0c);
if (retval)
goto out;
msleep(2);
retval = snd_at73c213_write_reg(chip, DAC_CTRL, 0x00);
if (retval)
goto out;
/* Turn off master power. */
retval = snd_at73c213_write_reg(chip, DAC_PRECH, 0x00);
if (retval)
goto out;
out:
/* Stop DAC master clock. */
clk_disable(chip->board->dac_clk);
ssc_free(chip->ssc);
snd_card_free(card);
dev_set_drvdata(&spi->dev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int snd_at73c213_suspend(struct spi_device *spi, pm_message_t msg)
{
struct snd_card *card = dev_get_drvdata(&spi->dev);
struct snd_at73c213 *chip = card->private_data;
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXDIS));
clk_disable(chip->board->dac_clk);
return 0;
}
static int snd_at73c213_resume(struct spi_device *spi)
{
struct snd_card *card = dev_get_drvdata(&spi->dev);
struct snd_at73c213 *chip = card->private_data;
clk_enable(chip->board->dac_clk);
ssc_writel(chip->ssc->regs, CR, SSC_BIT(CR_TXEN));
return 0;
}
#else
#define snd_at73c213_suspend NULL
#define snd_at73c213_resume NULL
#endif
static struct spi_driver at73c213_driver = {
.driver = {
.name = "at73c213",
},
.probe = snd_at73c213_probe,
.suspend = snd_at73c213_suspend,
.resume = snd_at73c213_resume,
.remove = __devexit_p(snd_at73c213_remove),
};
module_spi_driver(at73c213_driver);
MODULE_AUTHOR("Hans-Christian Egtvedt <egtvedt@samfundet.no>");
MODULE_DESCRIPTION("Sound driver for AT73C213 with Atmel SSC");
MODULE_LICENSE("GPL");
| gpl-2.0 |
p12tic/tf700-kernel | kernel/utsname_sysctl.c | 4991 | 3054 | /*
* Copyright (C) 2007
*
* Author: Eric Biederman <ebiederm@xmision.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, version 2 of the
* License.
*/
#include <linux/export.h>
#include <linux/uts.h>
#include <linux/utsname.h>
#include <linux/sysctl.h>
#include <linux/wait.h>
static void *get_uts(ctl_table *table, int write)
{
char *which = table->data;
struct uts_namespace *uts_ns;
uts_ns = current->nsproxy->uts_ns;
which = (which - (char *)&init_uts_ns) + (char *)uts_ns;
if (!write)
down_read(&uts_sem);
else
down_write(&uts_sem);
return which;
}
static void put_uts(ctl_table *table, int write, void *which)
{
if (!write)
up_read(&uts_sem);
else
up_write(&uts_sem);
}
#ifdef CONFIG_PROC_SYSCTL
/*
* Special case of dostring for the UTS structure. This has locks
* to observe. Should this be in kernel/sys.c ????
*/
static int proc_do_uts_string(ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos)
{
struct ctl_table uts_table;
int r;
memcpy(&uts_table, table, sizeof(uts_table));
uts_table.data = get_uts(table, write);
r = proc_dostring(&uts_table,write,buffer,lenp, ppos);
put_uts(table, write, uts_table.data);
if (write)
proc_sys_poll_notify(table->poll);
return r;
}
#else
#define proc_do_uts_string NULL
#endif
static DEFINE_CTL_TABLE_POLL(hostname_poll);
static DEFINE_CTL_TABLE_POLL(domainname_poll);
static struct ctl_table uts_kern_table[] = {
{
.procname = "ostype",
.data = init_uts_ns.name.sysname,
.maxlen = sizeof(init_uts_ns.name.sysname),
.mode = 0444,
.proc_handler = proc_do_uts_string,
},
{
.procname = "osrelease",
.data = init_uts_ns.name.release,
.maxlen = sizeof(init_uts_ns.name.release),
.mode = 0444,
.proc_handler = proc_do_uts_string,
},
{
.procname = "version",
.data = init_uts_ns.name.version,
.maxlen = sizeof(init_uts_ns.name.version),
.mode = 0444,
.proc_handler = proc_do_uts_string,
},
{
.procname = "hostname",
.data = init_uts_ns.name.nodename,
.maxlen = sizeof(init_uts_ns.name.nodename),
.mode = 0644,
.proc_handler = proc_do_uts_string,
.poll = &hostname_poll,
},
{
.procname = "domainname",
.data = init_uts_ns.name.domainname,
.maxlen = sizeof(init_uts_ns.name.domainname),
.mode = 0644,
.proc_handler = proc_do_uts_string,
.poll = &domainname_poll,
},
{}
};
static struct ctl_table uts_root_table[] = {
{
.procname = "kernel",
.mode = 0555,
.child = uts_kern_table,
},
{}
};
#ifdef CONFIG_PROC_SYSCTL
/*
* Notify userspace about a change in a certain entry of uts_kern_table,
* identified by the parameter proc.
*/
void uts_proc_notify(enum uts_proc proc)
{
struct ctl_table *table = &uts_kern_table[proc];
proc_sys_poll_notify(table->poll);
}
#endif
static int __init utsname_sysctl_init(void)
{
register_sysctl_table(uts_root_table);
return 0;
}
__initcall(utsname_sysctl_init);
| gpl-2.0 |
xperiafan13-rom/FenoCAF-KERNEL | drivers/leds/leds-wm8350.c | 4991 | 5829 | /*
* LED driver for WM8350 driven LEDS.
*
* Copyright(C) 2007, 2008 Wolfson Microelectronics PLC.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/err.h>
#include <linux/mfd/wm8350/pmic.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <linux/module.h>
/* Microamps */
static const int isink_cur[] = {
4,
5,
6,
7,
8,
10,
11,
14,
16,
19,
23,
27,
32,
39,
46,
54,
65,
77,
92,
109,
130,
154,
183,
218,
259,
308,
367,
436,
518,
616,
733,
872,
1037,
1233,
1466,
1744,
2073,
2466,
2933,
3487,
4147,
4932,
5865,
6975,
8294,
9864,
11730,
13949,
16589,
19728,
23460,
27899,
33178,
39455,
46920,
55798,
66355,
78910,
93840,
111596,
132710,
157820,
187681,
223191
};
#define to_wm8350_led(led_cdev) \
container_of(led_cdev, struct wm8350_led, cdev)
static void wm8350_led_enable(struct wm8350_led *led)
{
int ret;
if (led->enabled)
return;
ret = regulator_enable(led->isink);
if (ret != 0) {
dev_err(led->cdev.dev, "Failed to enable ISINK: %d\n", ret);
return;
}
ret = regulator_enable(led->dcdc);
if (ret != 0) {
dev_err(led->cdev.dev, "Failed to enable DCDC: %d\n", ret);
regulator_disable(led->isink);
return;
}
led->enabled = 1;
}
static void wm8350_led_disable(struct wm8350_led *led)
{
int ret;
if (!led->enabled)
return;
ret = regulator_disable(led->dcdc);
if (ret != 0) {
dev_err(led->cdev.dev, "Failed to disable DCDC: %d\n", ret);
return;
}
ret = regulator_disable(led->isink);
if (ret != 0) {
dev_err(led->cdev.dev, "Failed to disable ISINK: %d\n", ret);
regulator_enable(led->dcdc);
return;
}
led->enabled = 0;
}
static void led_work(struct work_struct *work)
{
struct wm8350_led *led = container_of(work, struct wm8350_led, work);
int ret;
int uA;
unsigned long flags;
mutex_lock(&led->mutex);
spin_lock_irqsave(&led->value_lock, flags);
if (led->value == LED_OFF) {
spin_unlock_irqrestore(&led->value_lock, flags);
wm8350_led_disable(led);
goto out;
}
/* This scales linearly into the index of valid current
* settings which results in a linear scaling of perceived
* brightness due to the non-linear current settings provided
* by the hardware.
*/
uA = (led->max_uA_index * led->value) / LED_FULL;
spin_unlock_irqrestore(&led->value_lock, flags);
BUG_ON(uA >= ARRAY_SIZE(isink_cur));
ret = regulator_set_current_limit(led->isink, isink_cur[uA],
isink_cur[uA]);
if (ret != 0)
dev_err(led->cdev.dev, "Failed to set %duA: %d\n",
isink_cur[uA], ret);
wm8350_led_enable(led);
out:
mutex_unlock(&led->mutex);
}
static void wm8350_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct wm8350_led *led = to_wm8350_led(led_cdev);
unsigned long flags;
spin_lock_irqsave(&led->value_lock, flags);
led->value = value;
schedule_work(&led->work);
spin_unlock_irqrestore(&led->value_lock, flags);
}
static void wm8350_led_shutdown(struct platform_device *pdev)
{
struct wm8350_led *led = platform_get_drvdata(pdev);
mutex_lock(&led->mutex);
led->value = LED_OFF;
wm8350_led_disable(led);
mutex_unlock(&led->mutex);
}
static int wm8350_led_probe(struct platform_device *pdev)
{
struct regulator *isink, *dcdc;
struct wm8350_led *led;
struct wm8350_led_platform_data *pdata = pdev->dev.platform_data;
int ret, i;
if (pdata == NULL) {
dev_err(&pdev->dev, "no platform data\n");
return -ENODEV;
}
if (pdata->max_uA < isink_cur[0]) {
dev_err(&pdev->dev, "Invalid maximum current %duA\n",
pdata->max_uA);
return -EINVAL;
}
isink = regulator_get(&pdev->dev, "led_isink");
if (IS_ERR(isink)) {
printk(KERN_ERR "%s: can't get ISINK\n", __func__);
return PTR_ERR(isink);
}
dcdc = regulator_get(&pdev->dev, "led_vcc");
if (IS_ERR(dcdc)) {
printk(KERN_ERR "%s: can't get DCDC\n", __func__);
ret = PTR_ERR(dcdc);
goto err_isink;
}
led = devm_kzalloc(&pdev->dev, sizeof(*led), GFP_KERNEL);
if (led == NULL) {
ret = -ENOMEM;
goto err_dcdc;
}
led->cdev.brightness_set = wm8350_led_set;
led->cdev.default_trigger = pdata->default_trigger;
led->cdev.name = pdata->name;
led->cdev.flags |= LED_CORE_SUSPENDRESUME;
led->enabled = regulator_is_enabled(isink);
led->isink = isink;
led->dcdc = dcdc;
for (i = 0; i < ARRAY_SIZE(isink_cur) - 1; i++)
if (isink_cur[i] >= pdata->max_uA)
break;
led->max_uA_index = i;
if (pdata->max_uA != isink_cur[i])
dev_warn(&pdev->dev,
"Maximum current %duA is not directly supported,"
" check platform data\n",
pdata->max_uA);
spin_lock_init(&led->value_lock);
mutex_init(&led->mutex);
INIT_WORK(&led->work, led_work);
led->value = LED_OFF;
platform_set_drvdata(pdev, led);
ret = led_classdev_register(&pdev->dev, &led->cdev);
if (ret < 0)
goto err_dcdc;
return 0;
err_dcdc:
regulator_put(dcdc);
err_isink:
regulator_put(isink);
return ret;
}
static int wm8350_led_remove(struct platform_device *pdev)
{
struct wm8350_led *led = platform_get_drvdata(pdev);
led_classdev_unregister(&led->cdev);
flush_work_sync(&led->work);
wm8350_led_disable(led);
regulator_put(led->dcdc);
regulator_put(led->isink);
return 0;
}
static struct platform_driver wm8350_led_driver = {
.driver = {
.name = "wm8350-led",
.owner = THIS_MODULE,
},
.probe = wm8350_led_probe,
.remove = wm8350_led_remove,
.shutdown = wm8350_led_shutdown,
};
module_platform_driver(wm8350_led_driver);
MODULE_AUTHOR("Mark Brown");
MODULE_DESCRIPTION("WM8350 LED driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:wm8350-led");
| gpl-2.0 |
m7rom/android_kernel_htc_msm8960 | drivers/media/video/bt8xx/bttv-input.c | 5247 | 14049 | /*
*
* Copyright (c) 2003 Gerd Knorr
* Copyright (c) 2003 Pavel Machek
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/slab.h>
#include "bttv.h"
#include "bttvp.h"
static int ir_debug;
module_param(ir_debug, int, 0644);
static int ir_rc5_remote_gap = 885;
module_param(ir_rc5_remote_gap, int, 0644);
#undef dprintk
#define dprintk(fmt, ...) \
do { \
if (ir_debug >= 1) \
pr_info(fmt, ##__VA_ARGS__); \
} while (0)
#define DEVNAME "bttv-input"
#define MODULE_NAME "bttv"
/* ---------------------------------------------------------------------- */
static void ir_handle_key(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
u32 gpio,data;
/* read gpio value */
gpio = bttv_gpio_read(&btv->c);
if (ir->polling) {
if (ir->last_gpio == gpio)
return;
ir->last_gpio = gpio;
}
/* extract data */
data = ir_extract_bits(gpio, ir->mask_keycode);
dprintk("irq gpio=0x%x code=%d | %s%s%s\n",
gpio, data,
ir->polling ? "poll" : "irq",
(gpio & ir->mask_keydown) ? " down" : "",
(gpio & ir->mask_keyup) ? " up" : "");
if ((ir->mask_keydown && (gpio & ir->mask_keydown)) ||
(ir->mask_keyup && !(gpio & ir->mask_keyup))) {
rc_keydown_notimeout(ir->dev, data, 0);
} else {
/* HACK: Probably, ir->mask_keydown is missing
for this board */
if (btv->c.type == BTTV_BOARD_WINFAST2000)
rc_keydown_notimeout(ir->dev, data, 0);
rc_keyup(ir->dev);
}
}
static void ir_enltv_handle_key(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
u32 gpio, data, keyup;
/* read gpio value */
gpio = bttv_gpio_read(&btv->c);
/* extract data */
data = ir_extract_bits(gpio, ir->mask_keycode);
/* Check if it is keyup */
keyup = (gpio & ir->mask_keyup) ? 1 << 31 : 0;
if ((ir->last_gpio & 0x7f) != data) {
dprintk("gpio=0x%x code=%d | %s\n",
gpio, data,
(gpio & ir->mask_keyup) ? " up" : "up/down");
rc_keydown_notimeout(ir->dev, data, 0);
if (keyup)
rc_keyup(ir->dev);
} else {
if ((ir->last_gpio & 1 << 31) == keyup)
return;
dprintk("(cnt) gpio=0x%x code=%d | %s\n",
gpio, data,
(gpio & ir->mask_keyup) ? " up" : "down");
if (keyup)
rc_keyup(ir->dev);
else
rc_keydown_notimeout(ir->dev, data, 0);
}
ir->last_gpio = data | keyup;
}
static int bttv_rc5_irq(struct bttv *btv);
void bttv_input_irq(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
if (ir->rc5_gpio)
bttv_rc5_irq(btv);
else if (!ir->polling)
ir_handle_key(btv);
}
static void bttv_input_timer(unsigned long data)
{
struct bttv *btv = (struct bttv*)data;
struct bttv_ir *ir = btv->remote;
if (btv->c.type == BTTV_BOARD_ENLTV_FM_2)
ir_enltv_handle_key(btv);
else
ir_handle_key(btv);
mod_timer(&ir->timer, jiffies + msecs_to_jiffies(ir->polling));
}
/*
* FIXME: Nebula digi uses the legacy way to decode RC5, instead of relying
* on the rc-core way. As we need to be sure that both IRQ transitions are
* properly triggered, Better to touch it only with this hardware for
* testing.
*/
#define RC5_START(x) (((x) >> 12) & 3)
#define RC5_TOGGLE(x) (((x) >> 11) & 1)
#define RC5_ADDR(x) (((x) >> 6) & 31)
#define RC5_INSTR(x) ((x) & 63)
/* decode raw bit pattern to RC5 code */
static u32 bttv_rc5_decode(unsigned int code)
{
unsigned int org_code = code;
unsigned int pair;
unsigned int rc5 = 0;
int i;
for (i = 0; i < 14; ++i) {
pair = code & 0x3;
code >>= 2;
rc5 <<= 1;
switch (pair) {
case 0:
case 2:
break;
case 1:
rc5 |= 1;
break;
case 3:
dprintk("rc5_decode(%x) bad code\n",
org_code);
return 0;
}
}
dprintk("code=%x, rc5=%x, start=%x, toggle=%x, address=%x, "
"instr=%x\n", rc5, org_code, RC5_START(rc5),
RC5_TOGGLE(rc5), RC5_ADDR(rc5), RC5_INSTR(rc5));
return rc5;
}
static void bttv_rc5_timer_end(unsigned long data)
{
struct bttv_ir *ir = (struct bttv_ir *)data;
struct timeval tv;
u32 gap;
u32 rc5 = 0;
/* get time */
do_gettimeofday(&tv);
/* avoid overflow with gap >1s */
if (tv.tv_sec - ir->base_time.tv_sec > 1) {
gap = 200000;
} else {
gap = 1000000 * (tv.tv_sec - ir->base_time.tv_sec) +
tv.tv_usec - ir->base_time.tv_usec;
}
/* signal we're ready to start a new code */
ir->active = false;
/* Allow some timer jitter (RC5 is ~24ms anyway so this is ok) */
if (gap < 28000) {
dprintk("spurious timer_end\n");
return;
}
if (ir->last_bit < 20) {
/* ignore spurious codes (caused by light/other remotes) */
dprintk("short code: %x\n", ir->code);
} else {
ir->code = (ir->code << ir->shift_by) | 1;
rc5 = bttv_rc5_decode(ir->code);
/* two start bits? */
if (RC5_START(rc5) != ir->start) {
pr_info(DEVNAME ":"
" rc5 start bits invalid: %u\n", RC5_START(rc5));
/* right address? */
} else if (RC5_ADDR(rc5) == ir->addr) {
u32 toggle = RC5_TOGGLE(rc5);
u32 instr = RC5_INSTR(rc5);
/* Good code */
rc_keydown(ir->dev, instr, toggle);
dprintk("instruction %x, toggle %x\n",
instr, toggle);
}
}
}
static int bttv_rc5_irq(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
struct timeval tv;
u32 gpio;
u32 gap;
unsigned long current_jiffies;
/* read gpio port */
gpio = bttv_gpio_read(&btv->c);
/* get time of bit */
current_jiffies = jiffies;
do_gettimeofday(&tv);
/* avoid overflow with gap >1s */
if (tv.tv_sec - ir->base_time.tv_sec > 1) {
gap = 200000;
} else {
gap = 1000000 * (tv.tv_sec - ir->base_time.tv_sec) +
tv.tv_usec - ir->base_time.tv_usec;
}
dprintk("RC5 IRQ: gap %d us for %s\n",
gap, (gpio & 0x20) ? "mark" : "space");
/* remote IRQ? */
if (!(gpio & 0x20))
return 0;
/* active code => add bit */
if (ir->active) {
/* only if in the code (otherwise spurious IRQ or timer
late) */
if (ir->last_bit < 28) {
ir->last_bit = (gap - ir_rc5_remote_gap / 2) /
ir_rc5_remote_gap;
ir->code |= 1 << ir->last_bit;
}
/* starting new code */
} else {
ir->active = true;
ir->code = 0;
ir->base_time = tv;
ir->last_bit = 0;
mod_timer(&ir->timer, current_jiffies + msecs_to_jiffies(30));
}
/* toggle GPIO pin 4 to reset the irq */
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
bttv_gpio_write(&btv->c, gpio | (1 << 4));
return 1;
}
/* ---------------------------------------------------------------------- */
static void bttv_ir_start(struct bttv *btv, struct bttv_ir *ir)
{
if (ir->polling) {
setup_timer(&ir->timer, bttv_input_timer, (unsigned long)btv);
ir->timer.expires = jiffies + msecs_to_jiffies(1000);
add_timer(&ir->timer);
} else if (ir->rc5_gpio) {
/* set timer_end for code completion */
setup_timer(&ir->timer, bttv_rc5_timer_end, (unsigned long)ir);
ir->shift_by = 1;
ir->start = 3;
ir->addr = 0x0;
ir->rc5_remote_gap = ir_rc5_remote_gap;
}
}
static void bttv_ir_stop(struct bttv *btv)
{
if (btv->remote->polling)
del_timer_sync(&btv->remote->timer);
if (btv->remote->rc5_gpio) {
u32 gpio;
del_timer_sync(&btv->remote->timer);
gpio = bttv_gpio_read(&btv->c);
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
}
}
/*
* Get_key functions used by I2C remotes
*/
static int get_key_pv951(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char b;
/* poll IR chip */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
dprintk("read error\n");
return -EIO;
}
/* ignore 0xaa */
if (b==0xaa)
return 0;
dprintk("key %02x\n", b);
/*
* NOTE:
* lirc_i2c maps the pv951 code as:
* addr = 0x61D6
* cmd = bit_reverse (b)
* So, it seems that this device uses NEC extended
* I decided to not fix the table, due to two reasons:
* 1) Without the actual device, this is only a guess;
* 2) As the addr is not reported via I2C, nor can be changed,
* the device is bound to the vendor-provided RC.
*/
*ir_key = b;
*ir_raw = b;
return 1;
}
/* Instantiate the I2C IR receiver device, if present */
void __devinit init_bttv_i2c_ir(struct bttv *btv)
{
const unsigned short addr_list[] = {
0x1a, 0x18, 0x64, 0x30, 0x71,
I2C_CLIENT_END
};
struct i2c_board_info info;
if (0 != btv->i2c_rc)
return;
memset(&info, 0, sizeof(struct i2c_board_info));
memset(&btv->init_data, 0, sizeof(btv->init_data));
strlcpy(info.type, "ir_video", I2C_NAME_SIZE);
switch (btv->c.type) {
case BTTV_BOARD_PV951:
btv->init_data.name = "PV951";
btv->init_data.get_key = get_key_pv951;
btv->init_data.ir_codes = RC_MAP_PV951;
info.addr = 0x4b;
break;
default:
/*
* The external IR receiver is at i2c address 0x34 (0x35 for
* reads). Future Hauppauge cards will have an internal
* receiver at 0x30 (0x31 for reads). In theory, both can be
* fitted, and Hauppauge suggest an external overrides an
* internal.
* That's why we probe 0x1a (~0x34) first. CB
*/
i2c_new_probed_device(&btv->c.i2c_adap, &info, addr_list, NULL);
return;
}
if (btv->init_data.name)
info.platform_data = &btv->init_data;
i2c_new_device(&btv->c.i2c_adap, &info);
return;
}
int __devexit fini_bttv_i2c(struct bttv *btv)
{
if (0 != btv->i2c_rc)
return 0;
return i2c_del_adapter(&btv->c.i2c_adap);
}
int bttv_input_init(struct bttv *btv)
{
struct bttv_ir *ir;
char *ir_codes = NULL;
struct rc_dev *rc;
int err = -ENOMEM;
if (!btv->has_remote)
return -ENODEV;
ir = kzalloc(sizeof(*ir),GFP_KERNEL);
rc = rc_allocate_device();
if (!ir || !rc)
goto err_out_free;
/* detect & configure */
switch (btv->c.type) {
case BTTV_BOARD_AVERMEDIA:
case BTTV_BOARD_AVPHONE98:
case BTTV_BOARD_AVERMEDIA98:
ir_codes = RC_MAP_AVERMEDIA;
ir->mask_keycode = 0xf88000;
ir->mask_keydown = 0x010000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_AVDVBT_761:
case BTTV_BOARD_AVDVBT_771:
ir_codes = RC_MAP_AVERMEDIA_DVBT;
ir->mask_keycode = 0x0f00c0;
ir->mask_keydown = 0x000020;
ir->polling = 50; // ms
break;
case BTTV_BOARD_PXELVWPLTVPAK:
ir_codes = RC_MAP_PIXELVIEW;
ir->mask_keycode = 0x003e00;
ir->mask_keyup = 0x010000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_PV_M4900:
case BTTV_BOARD_PV_BT878P_9B:
case BTTV_BOARD_PV_BT878P_PLUS:
ir_codes = RC_MAP_PIXELVIEW;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x008000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_WINFAST2000:
ir_codes = RC_MAP_WINFAST;
ir->mask_keycode = 0x1f8;
break;
case BTTV_BOARD_MAGICTVIEW061:
case BTTV_BOARD_MAGICTVIEW063:
ir_codes = RC_MAP_WINFAST;
ir->mask_keycode = 0x0008e000;
ir->mask_keydown = 0x00200000;
break;
case BTTV_BOARD_APAC_VIEWCOMP:
ir_codes = RC_MAP_APAC_VIEWCOMP;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x008000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_ASKEY_CPH03X:
case BTTV_BOARD_CONCEPTRONIC_CTVFMI2:
case BTTV_BOARD_CONTVFMI:
ir_codes = RC_MAP_PIXELVIEW;
ir->mask_keycode = 0x001F00;
ir->mask_keyup = 0x006000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_NEBULA_DIGITV:
ir_codes = RC_MAP_NEBULA;
ir->rc5_gpio = true;
break;
case BTTV_BOARD_MACHTV_MAGICTV:
ir_codes = RC_MAP_APAC_VIEWCOMP;
ir->mask_keycode = 0x001F00;
ir->mask_keyup = 0x004000;
ir->polling = 50; /* ms */
break;
case BTTV_BOARD_KOZUMI_KTV_01C:
ir_codes = RC_MAP_PCTV_SEDNA;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x006000;
ir->polling = 50; /* ms */
break;
case BTTV_BOARD_ENLTV_FM_2:
ir_codes = RC_MAP_ENCORE_ENLTV2;
ir->mask_keycode = 0x00fd00;
ir->mask_keyup = 0x000080;
ir->polling = 1; /* ms */
ir->last_gpio = ir_extract_bits(bttv_gpio_read(&btv->c),
ir->mask_keycode);
break;
}
if (NULL == ir_codes) {
dprintk("Ooops: IR config error [card=%d]\n", btv->c.type);
err = -ENODEV;
goto err_out_free;
}
if (ir->rc5_gpio) {
u32 gpio;
/* enable remote irq */
bttv_gpio_inout(&btv->c, (1 << 4), 1 << 4);
gpio = bttv_gpio_read(&btv->c);
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
bttv_gpio_write(&btv->c, gpio | (1 << 4));
} else {
/* init hardware-specific stuff */
bttv_gpio_inout(&btv->c, ir->mask_keycode | ir->mask_keydown, 0);
}
/* init input device */
ir->dev = rc;
snprintf(ir->name, sizeof(ir->name), "bttv IR (card=%d)",
btv->c.type);
snprintf(ir->phys, sizeof(ir->phys), "pci-%s/ir0",
pci_name(btv->c.pci));
rc->input_name = ir->name;
rc->input_phys = ir->phys;
rc->input_id.bustype = BUS_PCI;
rc->input_id.version = 1;
if (btv->c.pci->subsystem_vendor) {
rc->input_id.vendor = btv->c.pci->subsystem_vendor;
rc->input_id.product = btv->c.pci->subsystem_device;
} else {
rc->input_id.vendor = btv->c.pci->vendor;
rc->input_id.product = btv->c.pci->device;
}
rc->dev.parent = &btv->c.pci->dev;
rc->map_name = ir_codes;
rc->driver_name = MODULE_NAME;
btv->remote = ir;
bttv_ir_start(btv, ir);
/* all done */
err = rc_register_device(rc);
if (err)
goto err_out_stop;
return 0;
err_out_stop:
bttv_ir_stop(btv);
btv->remote = NULL;
err_out_free:
rc_free_device(rc);
kfree(ir);
return err;
}
void bttv_input_fini(struct bttv *btv)
{
if (btv->remote == NULL)
return;
bttv_ir_stop(btv);
rc_unregister_device(btv->remote->dev);
kfree(btv->remote);
btv->remote = NULL;
}
| gpl-2.0 |
MadnessMod/kernel_msm | drivers/media/video/bt8xx/bttv-input.c | 5247 | 14049 | /*
*
* Copyright (c) 2003 Gerd Knorr
* Copyright (c) 2003 Pavel Machek
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/slab.h>
#include "bttv.h"
#include "bttvp.h"
static int ir_debug;
module_param(ir_debug, int, 0644);
static int ir_rc5_remote_gap = 885;
module_param(ir_rc5_remote_gap, int, 0644);
#undef dprintk
#define dprintk(fmt, ...) \
do { \
if (ir_debug >= 1) \
pr_info(fmt, ##__VA_ARGS__); \
} while (0)
#define DEVNAME "bttv-input"
#define MODULE_NAME "bttv"
/* ---------------------------------------------------------------------- */
static void ir_handle_key(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
u32 gpio,data;
/* read gpio value */
gpio = bttv_gpio_read(&btv->c);
if (ir->polling) {
if (ir->last_gpio == gpio)
return;
ir->last_gpio = gpio;
}
/* extract data */
data = ir_extract_bits(gpio, ir->mask_keycode);
dprintk("irq gpio=0x%x code=%d | %s%s%s\n",
gpio, data,
ir->polling ? "poll" : "irq",
(gpio & ir->mask_keydown) ? " down" : "",
(gpio & ir->mask_keyup) ? " up" : "");
if ((ir->mask_keydown && (gpio & ir->mask_keydown)) ||
(ir->mask_keyup && !(gpio & ir->mask_keyup))) {
rc_keydown_notimeout(ir->dev, data, 0);
} else {
/* HACK: Probably, ir->mask_keydown is missing
for this board */
if (btv->c.type == BTTV_BOARD_WINFAST2000)
rc_keydown_notimeout(ir->dev, data, 0);
rc_keyup(ir->dev);
}
}
static void ir_enltv_handle_key(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
u32 gpio, data, keyup;
/* read gpio value */
gpio = bttv_gpio_read(&btv->c);
/* extract data */
data = ir_extract_bits(gpio, ir->mask_keycode);
/* Check if it is keyup */
keyup = (gpio & ir->mask_keyup) ? 1 << 31 : 0;
if ((ir->last_gpio & 0x7f) != data) {
dprintk("gpio=0x%x code=%d | %s\n",
gpio, data,
(gpio & ir->mask_keyup) ? " up" : "up/down");
rc_keydown_notimeout(ir->dev, data, 0);
if (keyup)
rc_keyup(ir->dev);
} else {
if ((ir->last_gpio & 1 << 31) == keyup)
return;
dprintk("(cnt) gpio=0x%x code=%d | %s\n",
gpio, data,
(gpio & ir->mask_keyup) ? " up" : "down");
if (keyup)
rc_keyup(ir->dev);
else
rc_keydown_notimeout(ir->dev, data, 0);
}
ir->last_gpio = data | keyup;
}
static int bttv_rc5_irq(struct bttv *btv);
void bttv_input_irq(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
if (ir->rc5_gpio)
bttv_rc5_irq(btv);
else if (!ir->polling)
ir_handle_key(btv);
}
static void bttv_input_timer(unsigned long data)
{
struct bttv *btv = (struct bttv*)data;
struct bttv_ir *ir = btv->remote;
if (btv->c.type == BTTV_BOARD_ENLTV_FM_2)
ir_enltv_handle_key(btv);
else
ir_handle_key(btv);
mod_timer(&ir->timer, jiffies + msecs_to_jiffies(ir->polling));
}
/*
* FIXME: Nebula digi uses the legacy way to decode RC5, instead of relying
* on the rc-core way. As we need to be sure that both IRQ transitions are
* properly triggered, Better to touch it only with this hardware for
* testing.
*/
#define RC5_START(x) (((x) >> 12) & 3)
#define RC5_TOGGLE(x) (((x) >> 11) & 1)
#define RC5_ADDR(x) (((x) >> 6) & 31)
#define RC5_INSTR(x) ((x) & 63)
/* decode raw bit pattern to RC5 code */
static u32 bttv_rc5_decode(unsigned int code)
{
unsigned int org_code = code;
unsigned int pair;
unsigned int rc5 = 0;
int i;
for (i = 0; i < 14; ++i) {
pair = code & 0x3;
code >>= 2;
rc5 <<= 1;
switch (pair) {
case 0:
case 2:
break;
case 1:
rc5 |= 1;
break;
case 3:
dprintk("rc5_decode(%x) bad code\n",
org_code);
return 0;
}
}
dprintk("code=%x, rc5=%x, start=%x, toggle=%x, address=%x, "
"instr=%x\n", rc5, org_code, RC5_START(rc5),
RC5_TOGGLE(rc5), RC5_ADDR(rc5), RC5_INSTR(rc5));
return rc5;
}
static void bttv_rc5_timer_end(unsigned long data)
{
struct bttv_ir *ir = (struct bttv_ir *)data;
struct timeval tv;
u32 gap;
u32 rc5 = 0;
/* get time */
do_gettimeofday(&tv);
/* avoid overflow with gap >1s */
if (tv.tv_sec - ir->base_time.tv_sec > 1) {
gap = 200000;
} else {
gap = 1000000 * (tv.tv_sec - ir->base_time.tv_sec) +
tv.tv_usec - ir->base_time.tv_usec;
}
/* signal we're ready to start a new code */
ir->active = false;
/* Allow some timer jitter (RC5 is ~24ms anyway so this is ok) */
if (gap < 28000) {
dprintk("spurious timer_end\n");
return;
}
if (ir->last_bit < 20) {
/* ignore spurious codes (caused by light/other remotes) */
dprintk("short code: %x\n", ir->code);
} else {
ir->code = (ir->code << ir->shift_by) | 1;
rc5 = bttv_rc5_decode(ir->code);
/* two start bits? */
if (RC5_START(rc5) != ir->start) {
pr_info(DEVNAME ":"
" rc5 start bits invalid: %u\n", RC5_START(rc5));
/* right address? */
} else if (RC5_ADDR(rc5) == ir->addr) {
u32 toggle = RC5_TOGGLE(rc5);
u32 instr = RC5_INSTR(rc5);
/* Good code */
rc_keydown(ir->dev, instr, toggle);
dprintk("instruction %x, toggle %x\n",
instr, toggle);
}
}
}
static int bttv_rc5_irq(struct bttv *btv)
{
struct bttv_ir *ir = btv->remote;
struct timeval tv;
u32 gpio;
u32 gap;
unsigned long current_jiffies;
/* read gpio port */
gpio = bttv_gpio_read(&btv->c);
/* get time of bit */
current_jiffies = jiffies;
do_gettimeofday(&tv);
/* avoid overflow with gap >1s */
if (tv.tv_sec - ir->base_time.tv_sec > 1) {
gap = 200000;
} else {
gap = 1000000 * (tv.tv_sec - ir->base_time.tv_sec) +
tv.tv_usec - ir->base_time.tv_usec;
}
dprintk("RC5 IRQ: gap %d us for %s\n",
gap, (gpio & 0x20) ? "mark" : "space");
/* remote IRQ? */
if (!(gpio & 0x20))
return 0;
/* active code => add bit */
if (ir->active) {
/* only if in the code (otherwise spurious IRQ or timer
late) */
if (ir->last_bit < 28) {
ir->last_bit = (gap - ir_rc5_remote_gap / 2) /
ir_rc5_remote_gap;
ir->code |= 1 << ir->last_bit;
}
/* starting new code */
} else {
ir->active = true;
ir->code = 0;
ir->base_time = tv;
ir->last_bit = 0;
mod_timer(&ir->timer, current_jiffies + msecs_to_jiffies(30));
}
/* toggle GPIO pin 4 to reset the irq */
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
bttv_gpio_write(&btv->c, gpio | (1 << 4));
return 1;
}
/* ---------------------------------------------------------------------- */
static void bttv_ir_start(struct bttv *btv, struct bttv_ir *ir)
{
if (ir->polling) {
setup_timer(&ir->timer, bttv_input_timer, (unsigned long)btv);
ir->timer.expires = jiffies + msecs_to_jiffies(1000);
add_timer(&ir->timer);
} else if (ir->rc5_gpio) {
/* set timer_end for code completion */
setup_timer(&ir->timer, bttv_rc5_timer_end, (unsigned long)ir);
ir->shift_by = 1;
ir->start = 3;
ir->addr = 0x0;
ir->rc5_remote_gap = ir_rc5_remote_gap;
}
}
static void bttv_ir_stop(struct bttv *btv)
{
if (btv->remote->polling)
del_timer_sync(&btv->remote->timer);
if (btv->remote->rc5_gpio) {
u32 gpio;
del_timer_sync(&btv->remote->timer);
gpio = bttv_gpio_read(&btv->c);
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
}
}
/*
* Get_key functions used by I2C remotes
*/
static int get_key_pv951(struct IR_i2c *ir, u32 *ir_key, u32 *ir_raw)
{
unsigned char b;
/* poll IR chip */
if (1 != i2c_master_recv(ir->c, &b, 1)) {
dprintk("read error\n");
return -EIO;
}
/* ignore 0xaa */
if (b==0xaa)
return 0;
dprintk("key %02x\n", b);
/*
* NOTE:
* lirc_i2c maps the pv951 code as:
* addr = 0x61D6
* cmd = bit_reverse (b)
* So, it seems that this device uses NEC extended
* I decided to not fix the table, due to two reasons:
* 1) Without the actual device, this is only a guess;
* 2) As the addr is not reported via I2C, nor can be changed,
* the device is bound to the vendor-provided RC.
*/
*ir_key = b;
*ir_raw = b;
return 1;
}
/* Instantiate the I2C IR receiver device, if present */
void __devinit init_bttv_i2c_ir(struct bttv *btv)
{
const unsigned short addr_list[] = {
0x1a, 0x18, 0x64, 0x30, 0x71,
I2C_CLIENT_END
};
struct i2c_board_info info;
if (0 != btv->i2c_rc)
return;
memset(&info, 0, sizeof(struct i2c_board_info));
memset(&btv->init_data, 0, sizeof(btv->init_data));
strlcpy(info.type, "ir_video", I2C_NAME_SIZE);
switch (btv->c.type) {
case BTTV_BOARD_PV951:
btv->init_data.name = "PV951";
btv->init_data.get_key = get_key_pv951;
btv->init_data.ir_codes = RC_MAP_PV951;
info.addr = 0x4b;
break;
default:
/*
* The external IR receiver is at i2c address 0x34 (0x35 for
* reads). Future Hauppauge cards will have an internal
* receiver at 0x30 (0x31 for reads). In theory, both can be
* fitted, and Hauppauge suggest an external overrides an
* internal.
* That's why we probe 0x1a (~0x34) first. CB
*/
i2c_new_probed_device(&btv->c.i2c_adap, &info, addr_list, NULL);
return;
}
if (btv->init_data.name)
info.platform_data = &btv->init_data;
i2c_new_device(&btv->c.i2c_adap, &info);
return;
}
int __devexit fini_bttv_i2c(struct bttv *btv)
{
if (0 != btv->i2c_rc)
return 0;
return i2c_del_adapter(&btv->c.i2c_adap);
}
int bttv_input_init(struct bttv *btv)
{
struct bttv_ir *ir;
char *ir_codes = NULL;
struct rc_dev *rc;
int err = -ENOMEM;
if (!btv->has_remote)
return -ENODEV;
ir = kzalloc(sizeof(*ir),GFP_KERNEL);
rc = rc_allocate_device();
if (!ir || !rc)
goto err_out_free;
/* detect & configure */
switch (btv->c.type) {
case BTTV_BOARD_AVERMEDIA:
case BTTV_BOARD_AVPHONE98:
case BTTV_BOARD_AVERMEDIA98:
ir_codes = RC_MAP_AVERMEDIA;
ir->mask_keycode = 0xf88000;
ir->mask_keydown = 0x010000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_AVDVBT_761:
case BTTV_BOARD_AVDVBT_771:
ir_codes = RC_MAP_AVERMEDIA_DVBT;
ir->mask_keycode = 0x0f00c0;
ir->mask_keydown = 0x000020;
ir->polling = 50; // ms
break;
case BTTV_BOARD_PXELVWPLTVPAK:
ir_codes = RC_MAP_PIXELVIEW;
ir->mask_keycode = 0x003e00;
ir->mask_keyup = 0x010000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_PV_M4900:
case BTTV_BOARD_PV_BT878P_9B:
case BTTV_BOARD_PV_BT878P_PLUS:
ir_codes = RC_MAP_PIXELVIEW;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x008000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_WINFAST2000:
ir_codes = RC_MAP_WINFAST;
ir->mask_keycode = 0x1f8;
break;
case BTTV_BOARD_MAGICTVIEW061:
case BTTV_BOARD_MAGICTVIEW063:
ir_codes = RC_MAP_WINFAST;
ir->mask_keycode = 0x0008e000;
ir->mask_keydown = 0x00200000;
break;
case BTTV_BOARD_APAC_VIEWCOMP:
ir_codes = RC_MAP_APAC_VIEWCOMP;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x008000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_ASKEY_CPH03X:
case BTTV_BOARD_CONCEPTRONIC_CTVFMI2:
case BTTV_BOARD_CONTVFMI:
ir_codes = RC_MAP_PIXELVIEW;
ir->mask_keycode = 0x001F00;
ir->mask_keyup = 0x006000;
ir->polling = 50; // ms
break;
case BTTV_BOARD_NEBULA_DIGITV:
ir_codes = RC_MAP_NEBULA;
ir->rc5_gpio = true;
break;
case BTTV_BOARD_MACHTV_MAGICTV:
ir_codes = RC_MAP_APAC_VIEWCOMP;
ir->mask_keycode = 0x001F00;
ir->mask_keyup = 0x004000;
ir->polling = 50; /* ms */
break;
case BTTV_BOARD_KOZUMI_KTV_01C:
ir_codes = RC_MAP_PCTV_SEDNA;
ir->mask_keycode = 0x001f00;
ir->mask_keyup = 0x006000;
ir->polling = 50; /* ms */
break;
case BTTV_BOARD_ENLTV_FM_2:
ir_codes = RC_MAP_ENCORE_ENLTV2;
ir->mask_keycode = 0x00fd00;
ir->mask_keyup = 0x000080;
ir->polling = 1; /* ms */
ir->last_gpio = ir_extract_bits(bttv_gpio_read(&btv->c),
ir->mask_keycode);
break;
}
if (NULL == ir_codes) {
dprintk("Ooops: IR config error [card=%d]\n", btv->c.type);
err = -ENODEV;
goto err_out_free;
}
if (ir->rc5_gpio) {
u32 gpio;
/* enable remote irq */
bttv_gpio_inout(&btv->c, (1 << 4), 1 << 4);
gpio = bttv_gpio_read(&btv->c);
bttv_gpio_write(&btv->c, gpio & ~(1 << 4));
bttv_gpio_write(&btv->c, gpio | (1 << 4));
} else {
/* init hardware-specific stuff */
bttv_gpio_inout(&btv->c, ir->mask_keycode | ir->mask_keydown, 0);
}
/* init input device */
ir->dev = rc;
snprintf(ir->name, sizeof(ir->name), "bttv IR (card=%d)",
btv->c.type);
snprintf(ir->phys, sizeof(ir->phys), "pci-%s/ir0",
pci_name(btv->c.pci));
rc->input_name = ir->name;
rc->input_phys = ir->phys;
rc->input_id.bustype = BUS_PCI;
rc->input_id.version = 1;
if (btv->c.pci->subsystem_vendor) {
rc->input_id.vendor = btv->c.pci->subsystem_vendor;
rc->input_id.product = btv->c.pci->subsystem_device;
} else {
rc->input_id.vendor = btv->c.pci->vendor;
rc->input_id.product = btv->c.pci->device;
}
rc->dev.parent = &btv->c.pci->dev;
rc->map_name = ir_codes;
rc->driver_name = MODULE_NAME;
btv->remote = ir;
bttv_ir_start(btv, ir);
/* all done */
err = rc_register_device(rc);
if (err)
goto err_out_stop;
return 0;
err_out_stop:
bttv_ir_stop(btv);
btv->remote = NULL;
err_out_free:
rc_free_device(rc);
kfree(ir);
return err;
}
void bttv_input_fini(struct bttv *btv)
{
if (btv->remote == NULL)
return;
bttv_ir_stop(btv);
rc_unregister_device(btv->remote->dev);
kfree(btv->remote);
btv->remote = NULL;
}
| gpl-2.0 |
uoaerg/linux-ecn | drivers/tty/serial/suncore.c | 8831 | 5338 | /* suncore.c
*
* Common SUN serial routines. Based entirely
* upon drivers/sbus/char/sunserial.c which is:
*
* Copyright (C) 1997 Eddie C. Dost (ecd@skynet.be)
*
* Adaptation to new UART layer is:
*
* Copyright (C) 2002 David S. Miller (davem@redhat.com)
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/console.h>
#include <linux/tty.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/serial_core.h>
#include <linux/sunserialcore.h>
#include <linux/init.h>
#include <asm/prom.h>
static int sunserial_current_minor = 64;
int sunserial_register_minors(struct uart_driver *drv, int count)
{
int err = 0;
drv->minor = sunserial_current_minor;
drv->nr += count;
/* Register the driver on the first call */
if (drv->nr == count)
err = uart_register_driver(drv);
if (err == 0) {
sunserial_current_minor += count;
drv->tty_driver->name_base = drv->minor - 64;
}
return err;
}
EXPORT_SYMBOL(sunserial_register_minors);
void sunserial_unregister_minors(struct uart_driver *drv, int count)
{
drv->nr -= count;
sunserial_current_minor -= count;
if (drv->nr == 0)
uart_unregister_driver(drv);
}
EXPORT_SYMBOL(sunserial_unregister_minors);
int sunserial_console_match(struct console *con, struct device_node *dp,
struct uart_driver *drv, int line, bool ignore_line)
{
if (!con)
return 0;
drv->cons = con;
if (of_console_device != dp)
return 0;
if (!ignore_line) {
int off = 0;
if (of_console_options &&
*of_console_options == 'b')
off = 1;
if ((line & 1) != off)
return 0;
}
if (!console_set_on_cmdline) {
con->index = line;
add_preferred_console(con->name, line, NULL);
}
return 1;
}
EXPORT_SYMBOL(sunserial_console_match);
void sunserial_console_termios(struct console *con, struct device_node *uart_dp)
{
const char *mode, *s;
char mode_prop[] = "ttyX-mode";
int baud, bits, stop, cflag;
char parity;
if (!strcmp(uart_dp->name, "rsc") ||
!strcmp(uart_dp->name, "rsc-console") ||
!strcmp(uart_dp->name, "rsc-control")) {
mode = of_get_property(uart_dp,
"ssp-console-modes", NULL);
if (!mode)
mode = "115200,8,n,1,-";
} else if (!strcmp(uart_dp->name, "lom-console")) {
mode = "9600,8,n,1,-";
} else {
struct device_node *dp;
char c;
c = 'a';
if (of_console_options)
c = *of_console_options;
mode_prop[3] = c;
dp = of_find_node_by_path("/options");
mode = of_get_property(dp, mode_prop, NULL);
if (!mode)
mode = "9600,8,n,1,-";
}
cflag = CREAD | HUPCL | CLOCAL;
s = mode;
baud = simple_strtoul(s, NULL, 0);
s = strchr(s, ',');
bits = simple_strtoul(++s, NULL, 0);
s = strchr(s, ',');
parity = *(++s);
s = strchr(s, ',');
stop = simple_strtoul(++s, NULL, 0);
s = strchr(s, ',');
/* XXX handshake is not handled here. */
switch (baud) {
case 150: cflag |= B150; break;
case 300: cflag |= B300; break;
case 600: cflag |= B600; break;
case 1200: cflag |= B1200; break;
case 2400: cflag |= B2400; break;
case 4800: cflag |= B4800; break;
case 9600: cflag |= B9600; break;
case 19200: cflag |= B19200; break;
case 38400: cflag |= B38400; break;
case 57600: cflag |= B57600; break;
case 115200: cflag |= B115200; break;
case 230400: cflag |= B230400; break;
case 460800: cflag |= B460800; break;
default: baud = 9600; cflag |= B9600; break;
}
switch (bits) {
case 5: cflag |= CS5; break;
case 6: cflag |= CS6; break;
case 7: cflag |= CS7; break;
case 8: cflag |= CS8; break;
default: cflag |= CS8; break;
}
switch (parity) {
case 'o': cflag |= (PARENB | PARODD); break;
case 'e': cflag |= PARENB; break;
case 'n': default: break;
}
switch (stop) {
case 2: cflag |= CSTOPB; break;
case 1: default: break;
}
con->cflag = cflag;
}
/* Sun serial MOUSE auto baud rate detection. */
static struct mouse_baud_cflag {
int baud;
unsigned int cflag;
} mouse_baud_table[] = {
{ 1200, B1200 },
{ 2400, B2400 },
{ 4800, B4800 },
{ 9600, B9600 },
{ -1, ~0 },
{ -1, ~0 },
};
unsigned int suncore_mouse_baud_cflag_next(unsigned int cflag, int *new_baud)
{
int i;
for (i = 0; mouse_baud_table[i].baud != -1; i++)
if (mouse_baud_table[i].cflag == (cflag & CBAUD))
break;
i += 1;
if (mouse_baud_table[i].baud == -1)
i = 0;
*new_baud = mouse_baud_table[i].baud;
return mouse_baud_table[i].cflag;
}
EXPORT_SYMBOL(suncore_mouse_baud_cflag_next);
/* Basically, when the baud rate is wrong the mouse spits out
* breaks to us.
*/
int suncore_mouse_baud_detection(unsigned char ch, int is_break)
{
static int mouse_got_break = 0;
static int ctr = 0;
if (is_break) {
/* Let a few normal bytes go by before we jump the gun
* and say we need to try another baud rate.
*/
if (mouse_got_break && ctr < 8)
return 1;
/* Ok, we need to try another baud. */
ctr = 0;
mouse_got_break = 1;
return 2;
}
if (mouse_got_break) {
ctr++;
if (ch == 0x87) {
/* Correct baud rate determined. */
mouse_got_break = 0;
}
return 1;
}
return 0;
}
EXPORT_SYMBOL(suncore_mouse_baud_detection);
static int __init suncore_init(void)
{
return 0;
}
static void __exit suncore_exit(void)
{
}
module_init(suncore_init);
module_exit(suncore_exit);
MODULE_AUTHOR("Eddie C. Dost, David S. Miller");
MODULE_DESCRIPTION("Sun serial common layer");
MODULE_LICENSE("GPL");
| gpl-2.0 |
vibgyor2nee/822_disk_sch | drivers/net/wireless/b43legacy/ilt.c | 10623 | 10733 | /*
Broadcom B43legacy wireless driver
Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>,
Stefano Brivio <stefano.brivio@polimi.it>
Michael Buesch <m@bues.ch>
Danny van Dyk <kugelfang@gentoo.org>
Andreas Jaggi <andreas.jaggi@waterwave.ch>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "b43legacy.h"
#include "ilt.h"
#include "phy.h"
/**** Initial Internal Lookup Tables ****/
const u32 b43legacy_ilt_rotor[B43legacy_ILT_ROTOR_SIZE] = {
0xFEB93FFD, 0xFEC63FFD, /* 0 */
0xFED23FFD, 0xFEDF3FFD,
0xFEEC3FFE, 0xFEF83FFE,
0xFF053FFE, 0xFF113FFE,
0xFF1E3FFE, 0xFF2A3FFF, /* 8 */
0xFF373FFF, 0xFF443FFF,
0xFF503FFF, 0xFF5D3FFF,
0xFF693FFF, 0xFF763FFF,
0xFF824000, 0xFF8F4000, /* 16 */
0xFF9B4000, 0xFFA84000,
0xFFB54000, 0xFFC14000,
0xFFCE4000, 0xFFDA4000,
0xFFE74000, 0xFFF34000, /* 24 */
0x00004000, 0x000D4000,
0x00194000, 0x00264000,
0x00324000, 0x003F4000,
0x004B4000, 0x00584000, /* 32 */
0x00654000, 0x00714000,
0x007E4000, 0x008A3FFF,
0x00973FFF, 0x00A33FFF,
0x00B03FFF, 0x00BC3FFF, /* 40 */
0x00C93FFF, 0x00D63FFF,
0x00E23FFE, 0x00EF3FFE,
0x00FB3FFE, 0x01083FFE,
0x01143FFE, 0x01213FFD, /* 48 */
0x012E3FFD, 0x013A3FFD,
0x01473FFD,
};
const u32 b43legacy_ilt_retard[B43legacy_ILT_RETARD_SIZE] = {
0xDB93CB87, 0xD666CF64, /* 0 */
0xD1FDD358, 0xCDA6D826,
0xCA38DD9F, 0xC729E2B4,
0xC469E88E, 0xC26AEE2B,
0xC0DEF46C, 0xC073FA62, /* 8 */
0xC01D00D5, 0xC0760743,
0xC1560D1E, 0xC2E51369,
0xC4ED18FF, 0xC7AC1ED7,
0xCB2823B2, 0xCEFA28D9, /* 16 */
0xD2F62D3F, 0xD7BB3197,
0xDCE53568, 0xE1FE3875,
0xE7D13B35, 0xED663D35,
0xF39B3EC4, 0xF98E3FA7, /* 24 */
0x00004000, 0x06723FA7,
0x0C653EC4, 0x129A3D35,
0x182F3B35, 0x1E023875,
0x231B3568, 0x28453197, /* 32 */
0x2D0A2D3F, 0x310628D9,
0x34D823B2, 0x38541ED7,
0x3B1318FF, 0x3D1B1369,
0x3EAA0D1E, 0x3F8A0743, /* 40 */
0x3FE300D5, 0x3F8DFA62,
0x3F22F46C, 0x3D96EE2B,
0x3B97E88E, 0x38D7E2B4,
0x35C8DD9F, 0x325AD826, /* 48 */
0x2E03D358, 0x299ACF64,
0x246DCB87,
};
const u16 b43legacy_ilt_finefreqa[B43legacy_ILT_FINEFREQA_SIZE] = {
0x0082, 0x0082, 0x0102, 0x0182, /* 0 */
0x0202, 0x0282, 0x0302, 0x0382,
0x0402, 0x0482, 0x0502, 0x0582,
0x05E2, 0x0662, 0x06E2, 0x0762,
0x07E2, 0x0842, 0x08C2, 0x0942, /* 16 */
0x09C2, 0x0A22, 0x0AA2, 0x0B02,
0x0B82, 0x0BE2, 0x0C62, 0x0CC2,
0x0D42, 0x0DA2, 0x0E02, 0x0E62,
0x0EE2, 0x0F42, 0x0FA2, 0x1002, /* 32 */
0x1062, 0x10C2, 0x1122, 0x1182,
0x11E2, 0x1242, 0x12A2, 0x12E2,
0x1342, 0x13A2, 0x1402, 0x1442,
0x14A2, 0x14E2, 0x1542, 0x1582, /* 48 */
0x15E2, 0x1622, 0x1662, 0x16C1,
0x1701, 0x1741, 0x1781, 0x17E1,
0x1821, 0x1861, 0x18A1, 0x18E1,
0x1921, 0x1961, 0x19A1, 0x19E1, /* 64 */
0x1A21, 0x1A61, 0x1AA1, 0x1AC1,
0x1B01, 0x1B41, 0x1B81, 0x1BA1,
0x1BE1, 0x1C21, 0x1C41, 0x1C81,
0x1CA1, 0x1CE1, 0x1D01, 0x1D41, /* 80 */
0x1D61, 0x1DA1, 0x1DC1, 0x1E01,
0x1E21, 0x1E61, 0x1E81, 0x1EA1,
0x1EE1, 0x1F01, 0x1F21, 0x1F41,
0x1F81, 0x1FA1, 0x1FC1, 0x1FE1, /* 96 */
0x2001, 0x2041, 0x2061, 0x2081,
0x20A1, 0x20C1, 0x20E1, 0x2101,
0x2121, 0x2141, 0x2161, 0x2181,
0x21A1, 0x21C1, 0x21E1, 0x2201, /* 112 */
0x2221, 0x2241, 0x2261, 0x2281,
0x22A1, 0x22C1, 0x22C1, 0x22E1,
0x2301, 0x2321, 0x2341, 0x2361,
0x2361, 0x2381, 0x23A1, 0x23C1, /* 128 */
0x23E1, 0x23E1, 0x2401, 0x2421,
0x2441, 0x2441, 0x2461, 0x2481,
0x2481, 0x24A1, 0x24C1, 0x24C1,
0x24E1, 0x2501, 0x2501, 0x2521, /* 144 */
0x2541, 0x2541, 0x2561, 0x2561,
0x2581, 0x25A1, 0x25A1, 0x25C1,
0x25C1, 0x25E1, 0x2601, 0x2601,
0x2621, 0x2621, 0x2641, 0x2641, /* 160 */
0x2661, 0x2661, 0x2681, 0x2681,
0x26A1, 0x26A1, 0x26C1, 0x26C1,
0x26E1, 0x26E1, 0x2701, 0x2701,
0x2721, 0x2721, 0x2740, 0x2740, /* 176 */
0x2760, 0x2760, 0x2780, 0x2780,
0x2780, 0x27A0, 0x27A0, 0x27C0,
0x27C0, 0x27E0, 0x27E0, 0x27E0,
0x2800, 0x2800, 0x2820, 0x2820, /* 192 */
0x2820, 0x2840, 0x2840, 0x2840,
0x2860, 0x2860, 0x2880, 0x2880,
0x2880, 0x28A0, 0x28A0, 0x28A0,
0x28C0, 0x28C0, 0x28C0, 0x28E0, /* 208 */
0x28E0, 0x28E0, 0x2900, 0x2900,
0x2900, 0x2920, 0x2920, 0x2920,
0x2940, 0x2940, 0x2940, 0x2960,
0x2960, 0x2960, 0x2960, 0x2980, /* 224 */
0x2980, 0x2980, 0x29A0, 0x29A0,
0x29A0, 0x29A0, 0x29C0, 0x29C0,
0x29C0, 0x29E0, 0x29E0, 0x29E0,
0x29E0, 0x2A00, 0x2A00, 0x2A00, /* 240 */
0x2A00, 0x2A20, 0x2A20, 0x2A20,
0x2A20, 0x2A40, 0x2A40, 0x2A40,
0x2A40, 0x2A60, 0x2A60, 0x2A60,
};
const u16 b43legacy_ilt_finefreqg[B43legacy_ILT_FINEFREQG_SIZE] = {
0x0089, 0x02E9, 0x0409, 0x04E9, /* 0 */
0x05A9, 0x0669, 0x0709, 0x0789,
0x0829, 0x08A9, 0x0929, 0x0989,
0x0A09, 0x0A69, 0x0AC9, 0x0B29,
0x0BA9, 0x0BE9, 0x0C49, 0x0CA9, /* 16 */
0x0D09, 0x0D69, 0x0DA9, 0x0E09,
0x0E69, 0x0EA9, 0x0F09, 0x0F49,
0x0FA9, 0x0FE9, 0x1029, 0x1089,
0x10C9, 0x1109, 0x1169, 0x11A9, /* 32 */
0x11E9, 0x1229, 0x1289, 0x12C9,
0x1309, 0x1349, 0x1389, 0x13C9,
0x1409, 0x1449, 0x14A9, 0x14E9,
0x1529, 0x1569, 0x15A9, 0x15E9, /* 48 */
0x1629, 0x1669, 0x16A9, 0x16E8,
0x1728, 0x1768, 0x17A8, 0x17E8,
0x1828, 0x1868, 0x18A8, 0x18E8,
0x1928, 0x1968, 0x19A8, 0x19E8, /* 64 */
0x1A28, 0x1A68, 0x1AA8, 0x1AE8,
0x1B28, 0x1B68, 0x1BA8, 0x1BE8,
0x1C28, 0x1C68, 0x1CA8, 0x1CE8,
0x1D28, 0x1D68, 0x1DC8, 0x1E08, /* 80 */
0x1E48, 0x1E88, 0x1EC8, 0x1F08,
0x1F48, 0x1F88, 0x1FE8, 0x2028,
0x2068, 0x20A8, 0x2108, 0x2148,
0x2188, 0x21C8, 0x2228, 0x2268, /* 96 */
0x22C8, 0x2308, 0x2348, 0x23A8,
0x23E8, 0x2448, 0x24A8, 0x24E8,
0x2548, 0x25A8, 0x2608, 0x2668,
0x26C8, 0x2728, 0x2787, 0x27E7, /* 112 */
0x2847, 0x28C7, 0x2947, 0x29A7,
0x2A27, 0x2AC7, 0x2B47, 0x2BE7,
0x2CA7, 0x2D67, 0x2E47, 0x2F67,
0x3247, 0x3526, 0x3646, 0x3726, /* 128 */
0x3806, 0x38A6, 0x3946, 0x39E6,
0x3A66, 0x3AE6, 0x3B66, 0x3BC6,
0x3C45, 0x3CA5, 0x3D05, 0x3D85,
0x3DE5, 0x3E45, 0x3EA5, 0x3EE5, /* 144 */
0x3F45, 0x3FA5, 0x4005, 0x4045,
0x40A5, 0x40E5, 0x4145, 0x4185,
0x41E5, 0x4225, 0x4265, 0x42C5,
0x4305, 0x4345, 0x43A5, 0x43E5, /* 160 */
0x4424, 0x4464, 0x44C4, 0x4504,
0x4544, 0x4584, 0x45C4, 0x4604,
0x4644, 0x46A4, 0x46E4, 0x4724,
0x4764, 0x47A4, 0x47E4, 0x4824, /* 176 */
0x4864, 0x48A4, 0x48E4, 0x4924,
0x4964, 0x49A4, 0x49E4, 0x4A24,
0x4A64, 0x4AA4, 0x4AE4, 0x4B23,
0x4B63, 0x4BA3, 0x4BE3, 0x4C23, /* 192 */
0x4C63, 0x4CA3, 0x4CE3, 0x4D23,
0x4D63, 0x4DA3, 0x4DE3, 0x4E23,
0x4E63, 0x4EA3, 0x4EE3, 0x4F23,
0x4F63, 0x4FC3, 0x5003, 0x5043, /* 208 */
0x5083, 0x50C3, 0x5103, 0x5143,
0x5183, 0x51E2, 0x5222, 0x5262,
0x52A2, 0x52E2, 0x5342, 0x5382,
0x53C2, 0x5402, 0x5462, 0x54A2, /* 224 */
0x5502, 0x5542, 0x55A2, 0x55E2,
0x5642, 0x5682, 0x56E2, 0x5722,
0x5782, 0x57E1, 0x5841, 0x58A1,
0x5901, 0x5961, 0x59C1, 0x5A21, /* 240 */
0x5AA1, 0x5B01, 0x5B81, 0x5BE1,
0x5C61, 0x5D01, 0x5D80, 0x5E20,
0x5EE0, 0x5FA0, 0x6080, 0x61C0,
};
const u16 b43legacy_ilt_noisea2[B43legacy_ILT_NOISEA2_SIZE] = {
0x0001, 0x0001, 0x0001, 0xFFFE,
0xFFFE, 0x3FFF, 0x1000, 0x0393,
};
const u16 b43legacy_ilt_noisea3[B43legacy_ILT_NOISEA3_SIZE] = {
0x4C4C, 0x4C4C, 0x4C4C, 0x2D36,
0x4C4C, 0x4C4C, 0x4C4C, 0x2D36,
};
const u16 b43legacy_ilt_noiseg1[B43legacy_ILT_NOISEG1_SIZE] = {
0x013C, 0x01F5, 0x031A, 0x0631,
0x0001, 0x0001, 0x0001, 0x0001,
};
const u16 b43legacy_ilt_noiseg2[B43legacy_ILT_NOISEG2_SIZE] = {
0x5484, 0x3C40, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000,
};
const u16 b43legacy_ilt_noisescaleg1[B43legacy_ILT_NOISESCALEG_SIZE] = {
0x6C77, 0x5162, 0x3B40, 0x3335, /* 0 */
0x2F2D, 0x2A2A, 0x2527, 0x1F21,
0x1A1D, 0x1719, 0x1616, 0x1414,
0x1414, 0x1400, 0x1414, 0x1614,
0x1716, 0x1A19, 0x1F1D, 0x2521, /* 16 */
0x2A27, 0x2F2A, 0x332D, 0x3B35,
0x5140, 0x6C62, 0x0077,
};
const u16 b43legacy_ilt_noisescaleg2[B43legacy_ILT_NOISESCALEG_SIZE] = {
0xD8DD, 0xCBD4, 0xBCC0, 0XB6B7, /* 0 */
0xB2B0, 0xADAD, 0xA7A9, 0x9FA1,
0x969B, 0x9195, 0x8F8F, 0x8A8A,
0x8A8A, 0x8A00, 0x8A8A, 0x8F8A,
0x918F, 0x9695, 0x9F9B, 0xA7A1, /* 16 */
0xADA9, 0xB2AD, 0xB6B0, 0xBCB7,
0xCBC0, 0xD8D4, 0x00DD,
};
const u16 b43legacy_ilt_noisescaleg3[B43legacy_ILT_NOISESCALEG_SIZE] = {
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, /* 0 */
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4,
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4,
0xA4A4, 0xA400, 0xA4A4, 0xA4A4,
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4, /* 16 */
0xA4A4, 0xA4A4, 0xA4A4, 0xA4A4,
0xA4A4, 0xA4A4, 0x00A4,
};
const u16 b43legacy_ilt_sigmasqr1[B43legacy_ILT_SIGMASQR_SIZE] = {
0x007A, 0x0075, 0x0071, 0x006C, /* 0 */
0x0067, 0x0063, 0x005E, 0x0059,
0x0054, 0x0050, 0x004B, 0x0046,
0x0042, 0x003D, 0x003D, 0x003D,
0x003D, 0x003D, 0x003D, 0x003D, /* 16 */
0x003D, 0x003D, 0x003D, 0x003D,
0x003D, 0x003D, 0x0000, 0x003D,
0x003D, 0x003D, 0x003D, 0x003D,
0x003D, 0x003D, 0x003D, 0x003D, /* 32 */
0x003D, 0x003D, 0x003D, 0x003D,
0x0042, 0x0046, 0x004B, 0x0050,
0x0054, 0x0059, 0x005E, 0x0063,
0x0067, 0x006C, 0x0071, 0x0075, /* 48 */
0x007A,
};
const u16 b43legacy_ilt_sigmasqr2[B43legacy_ILT_SIGMASQR_SIZE] = {
0x00DE, 0x00DC, 0x00DA, 0x00D8, /* 0 */
0x00D6, 0x00D4, 0x00D2, 0x00CF,
0x00CD, 0x00CA, 0x00C7, 0x00C4,
0x00C1, 0x00BE, 0x00BE, 0x00BE,
0x00BE, 0x00BE, 0x00BE, 0x00BE, /* 16 */
0x00BE, 0x00BE, 0x00BE, 0x00BE,
0x00BE, 0x00BE, 0x0000, 0x00BE,
0x00BE, 0x00BE, 0x00BE, 0x00BE,
0x00BE, 0x00BE, 0x00BE, 0x00BE, /* 32 */
0x00BE, 0x00BE, 0x00BE, 0x00BE,
0x00C1, 0x00C4, 0x00C7, 0x00CA,
0x00CD, 0x00CF, 0x00D2, 0x00D4,
0x00D6, 0x00D8, 0x00DA, 0x00DC, /* 48 */
0x00DE,
};
/**** Helper functions to access the device Internal Lookup Tables ****/
void b43legacy_ilt_write(struct b43legacy_wldev *dev, u16 offset, u16 val)
{
b43legacy_phy_write(dev, B43legacy_PHY_ILT_G_CTRL, offset);
mmiowb();
b43legacy_phy_write(dev, B43legacy_PHY_ILT_G_DATA1, val);
}
void b43legacy_ilt_write32(struct b43legacy_wldev *dev, u16 offset, u32 val)
{
b43legacy_phy_write(dev, B43legacy_PHY_ILT_G_CTRL, offset);
mmiowb();
b43legacy_phy_write(dev, B43legacy_PHY_ILT_G_DATA2,
(val & 0xFFFF0000) >> 16);
b43legacy_phy_write(dev, B43legacy_PHY_ILT_G_DATA1,
val & 0x0000FFFF);
}
u16 b43legacy_ilt_read(struct b43legacy_wldev *dev, u16 offset)
{
b43legacy_phy_write(dev, B43legacy_PHY_ILT_G_CTRL, offset);
return b43legacy_phy_read(dev, B43legacy_PHY_ILT_G_DATA1);
}
| gpl-2.0 |
hafidzduddin/samsung_codina_kernel | arch/microblaze/kernel/selfmod.c | 11391 | 2674 | /*
* Copyright (C) 2007-2009 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2009 PetaLogix
*
* 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/interrupt.h>
#include <asm/selfmod.h>
#undef DEBUG
#if __GNUC__ > 3
#error GCC 4 unsupported SELFMOD. Please disable SELFMOD from menuconfig.
#endif
#define OPCODE_IMM 0xB0000000
#define OPCODE_LWI 0xE8000000
#define OPCODE_LWI_MASK 0xEC000000
#define OPCODE_RTSD 0xB60F0008 /* return from func: rtsd r15, 8 */
#define OPCODE_ADDIK 0x30000000
#define OPCODE_ADDIK_MASK 0xFC000000
#define IMM_BASE (OPCODE_IMM | (BARRIER_BASE_ADDR >> 16))
#define LWI_BASE (OPCODE_LWI | (BARRIER_BASE_ADDR & 0x0000ff00))
#define LWI_BASE_MASK (OPCODE_LWI_MASK | (BARRIER_BASE_ADDR & 0x0000ff00))
#define ADDIK_BASE (OPCODE_ADDIK | (BARRIER_BASE_ADDR & 0x0000ff00))
#define ADDIK_BASE_MASK (OPCODE_ADDIK_MASK | (BARRIER_BASE_ADDR & 0x0000ff00))
#define MODIFY_INSTR { \
pr_debug("%s: curr instr, (%d):0x%x, next(%d):0x%x\n", \
__func__, i, addr[i], i + 1, addr[i + 1]); \
addr[i] = OPCODE_IMM + (base >> 16); \
/* keep instruction opcode and add only last 16bits */ \
addr[i + 1] = (addr[i + 1] & 0xffff00ff) + (base & 0xffff); \
__invalidate_icache(addr[i]); \
__invalidate_icache(addr[i + 1]); \
pr_debug("%s: hack instr, (%d):0x%x, next(%d):0x%x\n", \
__func__, i, addr[i], i + 1, addr[i + 1]); }
/* NOTE
* self-modified part of code for improvement of interrupt controller
* save instruction in interrupt rutine
*/
void selfmod_function(const int *arr_fce, const unsigned int base)
{
unsigned int flags, i, j, *addr = NULL;
local_irq_save(flags);
__disable_icache();
/* zero terminated array */
for (j = 0; arr_fce[j] != 0; j++) {
/* get start address of function */
addr = (unsigned int *) arr_fce[j];
pr_debug("%s: func(%d) at 0x%x\n",
__func__, j, (unsigned int) addr);
for (i = 0; ; i++) {
pr_debug("%s: instruction code at %d: 0x%x\n",
__func__, i, addr[i]);
if (addr[i] == IMM_BASE) {
/* detecting of lwi (0xE8) or swi (0xF8) instr
* I can detect both opcode with one mask */
if ((addr[i + 1] & LWI_BASE_MASK) == LWI_BASE) {
MODIFY_INSTR;
} else /* detection addik for ack */
if ((addr[i + 1] & ADDIK_BASE_MASK) ==
ADDIK_BASE) {
MODIFY_INSTR;
}
} else if (addr[i] == OPCODE_RTSD) {
/* return from function means end of function */
pr_debug("%s: end of array %d\n", __func__, i);
break;
}
}
}
local_irq_restore(flags);
} /* end of self-modified code */
| gpl-2.0 |
dev-elixir/hx_wt88047 | arch/microblaze/kernel/selfmod.c | 11391 | 2674 | /*
* Copyright (C) 2007-2009 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2009 PetaLogix
*
* 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/interrupt.h>
#include <asm/selfmod.h>
#undef DEBUG
#if __GNUC__ > 3
#error GCC 4 unsupported SELFMOD. Please disable SELFMOD from menuconfig.
#endif
#define OPCODE_IMM 0xB0000000
#define OPCODE_LWI 0xE8000000
#define OPCODE_LWI_MASK 0xEC000000
#define OPCODE_RTSD 0xB60F0008 /* return from func: rtsd r15, 8 */
#define OPCODE_ADDIK 0x30000000
#define OPCODE_ADDIK_MASK 0xFC000000
#define IMM_BASE (OPCODE_IMM | (BARRIER_BASE_ADDR >> 16))
#define LWI_BASE (OPCODE_LWI | (BARRIER_BASE_ADDR & 0x0000ff00))
#define LWI_BASE_MASK (OPCODE_LWI_MASK | (BARRIER_BASE_ADDR & 0x0000ff00))
#define ADDIK_BASE (OPCODE_ADDIK | (BARRIER_BASE_ADDR & 0x0000ff00))
#define ADDIK_BASE_MASK (OPCODE_ADDIK_MASK | (BARRIER_BASE_ADDR & 0x0000ff00))
#define MODIFY_INSTR { \
pr_debug("%s: curr instr, (%d):0x%x, next(%d):0x%x\n", \
__func__, i, addr[i], i + 1, addr[i + 1]); \
addr[i] = OPCODE_IMM + (base >> 16); \
/* keep instruction opcode and add only last 16bits */ \
addr[i + 1] = (addr[i + 1] & 0xffff00ff) + (base & 0xffff); \
__invalidate_icache(addr[i]); \
__invalidate_icache(addr[i + 1]); \
pr_debug("%s: hack instr, (%d):0x%x, next(%d):0x%x\n", \
__func__, i, addr[i], i + 1, addr[i + 1]); }
/* NOTE
* self-modified part of code for improvement of interrupt controller
* save instruction in interrupt rutine
*/
void selfmod_function(const int *arr_fce, const unsigned int base)
{
unsigned int flags, i, j, *addr = NULL;
local_irq_save(flags);
__disable_icache();
/* zero terminated array */
for (j = 0; arr_fce[j] != 0; j++) {
/* get start address of function */
addr = (unsigned int *) arr_fce[j];
pr_debug("%s: func(%d) at 0x%x\n",
__func__, j, (unsigned int) addr);
for (i = 0; ; i++) {
pr_debug("%s: instruction code at %d: 0x%x\n",
__func__, i, addr[i]);
if (addr[i] == IMM_BASE) {
/* detecting of lwi (0xE8) or swi (0xF8) instr
* I can detect both opcode with one mask */
if ((addr[i + 1] & LWI_BASE_MASK) == LWI_BASE) {
MODIFY_INSTR;
} else /* detection addik for ack */
if ((addr[i + 1] & ADDIK_BASE_MASK) ==
ADDIK_BASE) {
MODIFY_INSTR;
}
} else if (addr[i] == OPCODE_RTSD) {
/* return from function means end of function */
pr_debug("%s: end of array %d\n", __func__, i);
break;
}
}
}
local_irq_restore(flags);
} /* end of self-modified code */
| gpl-2.0 |
TrustZoneGenericDriver/linux | drivers/staging/rtl8723au/hal/usb_halinit.c | 128 | 38733 | /******************************************************************************
*
* Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
******************************************************************************/
#define _HCI_HAL_INIT_C_
#include <osdep_service.h>
#include <drv_types.h>
#include <rtw_efuse.h>
#include <HalPwrSeqCmd.h>
#include <Hal8723PwrSeq.h>
#include <rtl8723a_hal.h>
#include <linux/ieee80211.h>
#include <usb_ops.h>
static void phy_SsPwrSwitch92CU(struct rtw_adapter *Adapter,
enum rt_rf_power_state eRFPowerState);
static void
_ConfigChipOutEP(struct rtw_adapter *pAdapter, u8 NumOutPipe)
{
u8 value8;
struct hal_data_8723a *pHalData = GET_HAL_DATA(pAdapter);
pHalData->OutEpQueueSel = 0;
pHalData->OutEpNumber = 0;
/* Normal and High queue */
value8 = rtl8723au_read8(pAdapter, (REG_NORMAL_SIE_EP + 1));
if (value8 & USB_NORMAL_SIE_EP_MASK) {
pHalData->OutEpQueueSel |= TX_SELE_HQ;
pHalData->OutEpNumber++;
}
if ((value8 >> USB_NORMAL_SIE_EP_SHIFT) & USB_NORMAL_SIE_EP_MASK) {
pHalData->OutEpQueueSel |= TX_SELE_NQ;
pHalData->OutEpNumber++;
}
/* Low queue */
value8 = rtl8723au_read8(pAdapter, (REG_NORMAL_SIE_EP + 2));
if (value8 & USB_NORMAL_SIE_EP_MASK) {
pHalData->OutEpQueueSel |= TX_SELE_LQ;
pHalData->OutEpNumber++;
}
/* TODO: Error recovery for this case */
/* RT_ASSERT((NumOutPipe == pHalData->OutEpNumber),
("Out EP number isn't match! %d(Descriptor) != %d (SIE reg)\n",
(u32)NumOutPipe, (u32)pHalData->OutEpNumber)); */
}
bool rtl8723au_chip_configure(struct rtw_adapter *padapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(padapter);
struct dvobj_priv *pdvobjpriv = adapter_to_dvobj(padapter);
u8 NumInPipe = pdvobjpriv->RtNumInPipes;
u8 NumOutPipe = pdvobjpriv->RtNumOutPipes;
_ConfigChipOutEP(padapter, NumOutPipe);
/* Normal chip with one IN and one OUT doesn't have interrupt IN EP. */
if (pHalData->OutEpNumber == 1) {
if (NumInPipe != 1)
return false;
}
return Hal_MappingOutPipe23a(padapter, NumOutPipe);
}
static int _InitPowerOn(struct rtw_adapter *padapter)
{
u16 value16;
u8 value8;
/* RSV_CTRL 0x1C[7:0] = 0x00
unlock ISO/CLK/Power control register */
rtl8723au_write8(padapter, REG_RSV_CTRL, 0x0);
/* HW Power on sequence */
if (!HalPwrSeqCmdParsing23a(padapter, PWR_CUT_ALL_MSK, PWR_FAB_ALL_MSK,
PWR_INTF_USB_MSK, rtl8723AU_card_enable_flow))
return _FAIL;
/* 0x04[19] = 1, suggest by Jackie 2011.05.09, reset 8051 */
value8 = rtl8723au_read8(padapter, REG_APS_FSMCO+2);
rtl8723au_write8(padapter, REG_APS_FSMCO + 2, value8 | BIT(3));
/* Enable MAC DMA/WMAC/SCHEDULE/SEC block */
/* Set CR bit10 to enable 32k calibration. Suggested by SD1 Gimmy.
Added by tynli. 2011.08.31. */
value16 = rtl8723au_read16(padapter, REG_CR);
value16 |= (HCI_TXDMA_EN | HCI_RXDMA_EN | TXDMA_EN | RXDMA_EN |
PROTOCOL_EN | SCHEDULE_EN | MACTXEN | MACRXEN |
ENSEC | CALTMR_EN);
rtl8723au_write16(padapter, REG_CR, value16);
/* for Efuse PG, suggest by Jackie 2011.11.23 */
PHY_SetBBReg(padapter, REG_EFUSE_CTRL, BIT(28)|BIT(29)|BIT(30), 0x06);
return _SUCCESS;
}
/* Shall USB interface init this? */
static void _InitInterrupt(struct rtw_adapter *Adapter)
{
u32 value32;
/* HISR - turn all on */
value32 = 0xFFFFFFFF;
rtl8723au_write32(Adapter, REG_HISR, value32);
/* HIMR - turn all on */
rtl8723au_write32(Adapter, REG_HIMR, value32);
}
static void _InitQueueReservedPage(struct rtw_adapter *Adapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
struct registry_priv *pregistrypriv = &Adapter->registrypriv;
u32 numHQ = 0;
u32 numLQ = 0;
u32 numNQ = 0;
u32 numPubQ;
u32 value32;
u8 value8;
bool bWiFiConfig = pregistrypriv->wifi_spec;
/* RT_ASSERT((outEPNum>= 2), ("for WMM , number of out-ep "
"must more than or equal to 2!\n")); */
numPubQ = bWiFiConfig ? WMM_NORMAL_PAGE_NUM_PUBQ : NORMAL_PAGE_NUM_PUBQ;
if (pHalData->OutEpQueueSel & TX_SELE_HQ) {
numHQ = bWiFiConfig ?
WMM_NORMAL_PAGE_NUM_HPQ : NORMAL_PAGE_NUM_HPQ;
}
if (pHalData->OutEpQueueSel & TX_SELE_LQ) {
numLQ = bWiFiConfig ?
WMM_NORMAL_PAGE_NUM_LPQ : NORMAL_PAGE_NUM_LPQ;
}
/* NOTE: This step shall be proceed before
writting REG_RQPN. */
if (pHalData->OutEpQueueSel & TX_SELE_NQ) {
numNQ = bWiFiConfig ?
WMM_NORMAL_PAGE_NUM_NPQ : NORMAL_PAGE_NUM_NPQ;
}
value8 = (u8)_NPQ(numNQ);
rtl8723au_write8(Adapter, REG_RQPN_NPQ, value8);
/* TX DMA */
value32 = _HPQ(numHQ) | _LPQ(numLQ) | _PUBQ(numPubQ) | LD_RQPN;
rtl8723au_write32(Adapter, REG_RQPN, value32);
}
static void _InitTxBufferBoundary(struct rtw_adapter *Adapter)
{
struct registry_priv *pregistrypriv = &Adapter->registrypriv;
u8 txpktbuf_bndy;
if (!pregistrypriv->wifi_spec)
txpktbuf_bndy = TX_PAGE_BOUNDARY;
else /* for WMM */
txpktbuf_bndy = WMM_NORMAL_TX_PAGE_BOUNDARY;
rtl8723au_write8(Adapter, REG_TXPKTBUF_BCNQ_BDNY, txpktbuf_bndy);
rtl8723au_write8(Adapter, REG_TXPKTBUF_MGQ_BDNY, txpktbuf_bndy);
rtl8723au_write8(Adapter, REG_TXPKTBUF_WMAC_LBK_BF_HD, txpktbuf_bndy);
rtl8723au_write8(Adapter, REG_TRXFF_BNDY, txpktbuf_bndy);
rtl8723au_write8(Adapter, REG_TDECTRL+1, txpktbuf_bndy);
}
static void _InitPageBoundary(struct rtw_adapter *Adapter)
{
/* RX Page Boundary */
/* srand(static_cast<unsigned int>(time(NULL))); */
u16 rxff_bndy = 0x27FF;/* rand() % 1) ? 0x27FF : 0x23FF; */
rtl8723au_write16(Adapter, (REG_TRXFF_BNDY + 2), rxff_bndy);
/* TODO: ?? shall we set tx boundary? */
}
static void
_InitNormalChipRegPriority(struct rtw_adapter *Adapter, u16 beQ, u16 bkQ,
u16 viQ, u16 voQ, u16 mgtQ, u16 hiQ)
{
u16 value16 = rtl8723au_read16(Adapter, REG_TRXDMA_CTRL) & 0x7;
value16 |= _TXDMA_BEQ_MAP(beQ) | _TXDMA_BKQ_MAP(bkQ) |
_TXDMA_VIQ_MAP(viQ) | _TXDMA_VOQ_MAP(voQ) |
_TXDMA_MGQ_MAP(mgtQ) | _TXDMA_HIQ_MAP(hiQ);
rtl8723au_write16(Adapter, REG_TRXDMA_CTRL, value16);
}
static void _InitNormalChipOneOutEpPriority(struct rtw_adapter *Adapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
u16 value = 0;
switch (pHalData->OutEpQueueSel) {
case TX_SELE_HQ:
value = QUEUE_HIGH;
break;
case TX_SELE_LQ:
value = QUEUE_LOW;
break;
case TX_SELE_NQ:
value = QUEUE_NORMAL;
break;
default:
/* RT_ASSERT(false, ("Shall not reach here!\n")); */
break;
}
_InitNormalChipRegPriority(Adapter, value, value, value,
value, value, value);
}
static void _InitNormalChipTwoOutEpPriority(struct rtw_adapter *Adapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
struct registry_priv *pregistrypriv = &Adapter->registrypriv;
u16 beQ, bkQ, viQ, voQ, mgtQ, hiQ;
u16 valueHi = 0;
u16 valueLow = 0;
switch (pHalData->OutEpQueueSel) {
case (TX_SELE_HQ | TX_SELE_LQ):
valueHi = QUEUE_HIGH;
valueLow = QUEUE_LOW;
break;
case (TX_SELE_NQ | TX_SELE_LQ):
valueHi = QUEUE_NORMAL;
valueLow = QUEUE_LOW;
break;
case (TX_SELE_HQ | TX_SELE_NQ):
valueHi = QUEUE_HIGH;
valueLow = QUEUE_NORMAL;
break;
default:
/* RT_ASSERT(false, ("Shall not reach here!\n")); */
break;
}
if (!pregistrypriv->wifi_spec) {
beQ = valueLow;
bkQ = valueLow;
viQ = valueHi;
voQ = valueHi;
mgtQ = valueHi;
hiQ = valueHi;
} else {/* for WMM , CONFIG_OUT_EP_WIFI_MODE */
beQ = valueLow;
bkQ = valueHi;
viQ = valueHi;
voQ = valueLow;
mgtQ = valueHi;
hiQ = valueHi;
}
_InitNormalChipRegPriority(Adapter, beQ, bkQ, viQ, voQ, mgtQ, hiQ);
}
static void _InitNormalChipThreeOutEpPriority(struct rtw_adapter *Adapter)
{
struct registry_priv *pregistrypriv = &Adapter->registrypriv;
u16 beQ, bkQ, viQ, voQ, mgtQ, hiQ;
if (!pregistrypriv->wifi_spec) {/* typical setting */
beQ = QUEUE_LOW;
bkQ = QUEUE_LOW;
viQ = QUEUE_NORMAL;
voQ = QUEUE_HIGH;
mgtQ = QUEUE_HIGH;
hiQ = QUEUE_HIGH;
} else {/* for WMM */
beQ = QUEUE_LOW;
bkQ = QUEUE_NORMAL;
viQ = QUEUE_NORMAL;
voQ = QUEUE_HIGH;
mgtQ = QUEUE_HIGH;
hiQ = QUEUE_HIGH;
}
_InitNormalChipRegPriority(Adapter, beQ, bkQ, viQ, voQ, mgtQ, hiQ);
}
static void _InitQueuePriority(struct rtw_adapter *Adapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
switch (pHalData->OutEpNumber) {
case 1:
_InitNormalChipOneOutEpPriority(Adapter);
break;
case 2:
_InitNormalChipTwoOutEpPriority(Adapter);
break;
case 3:
_InitNormalChipThreeOutEpPriority(Adapter);
break;
default:
/* RT_ASSERT(false, ("Shall not reach here!\n")); */
break;
}
}
static void _InitTransferPageSize(struct rtw_adapter *Adapter)
{
/* Tx page size is always 128. */
u8 value8;
value8 = _PSRX(PBP_128) | _PSTX(PBP_128);
rtl8723au_write8(Adapter, REG_PBP, value8);
}
static void _InitDriverInfoSize(struct rtw_adapter *Adapter, u8 drvInfoSize)
{
rtl8723au_write8(Adapter, REG_RX_DRVINFO_SZ, drvInfoSize);
}
static void _InitWMACSetting(struct rtw_adapter *Adapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
/* don't turn on AAP, it will allow all packets to driver */
pHalData->ReceiveConfig = RCR_APM | RCR_AM | RCR_AB | RCR_CBSSID_DATA |
RCR_CBSSID_BCN | RCR_APP_ICV | RCR_AMF |
RCR_HTC_LOC_CTRL | RCR_APP_MIC |
RCR_APP_PHYSTS;
/* some REG_RCR will be modified later by
phy_ConfigMACWithHeaderFile() */
rtl8723au_write32(Adapter, REG_RCR, pHalData->ReceiveConfig);
/* Accept all multicast address */
rtl8723au_write32(Adapter, REG_MAR, 0xFFFFFFFF);
rtl8723au_write32(Adapter, REG_MAR + 4, 0xFFFFFFFF);
/* Accept all data frames */
/* value16 = 0xFFFF; */
/* rtl8723au_write16(Adapter, REG_RXFLTMAP2, value16); */
/* 2010.09.08 hpfan */
/* Since ADF is removed from RCR, ps-poll will not be indicate
to driver, */
/* RxFilterMap should mask ps-poll to gurantee AP mode can
rx ps-poll. */
/* value16 = 0x400; */
/* rtl8723au_write16(Adapter, REG_RXFLTMAP1, value16); */
/* Accept all management frames */
/* value16 = 0xFFFF; */
/* rtl8723au_write16(Adapter, REG_RXFLTMAP0, value16); */
/* enable RX_SHIFT bits */
/* rtl8723au_write8(Adapter, REG_TRXDMA_CTRL, rtl8723au_read8(Adapter,
REG_TRXDMA_CTRL)|BIT(1)); */
}
static void _InitAdaptiveCtrl(struct rtw_adapter *Adapter)
{
u16 value16;
u32 value32;
/* Response Rate Set */
value32 = rtl8723au_read32(Adapter, REG_RRSR);
value32 &= ~RATE_BITMAP_ALL;
value32 |= RATE_RRSR_CCK_ONLY_1M;
rtl8723au_write32(Adapter, REG_RRSR, value32);
/* CF-END Threshold */
/* m_spIoBase->rtl8723au_write8(REG_CFEND_TH, 0x1); */
/* SIFS (used in NAV) */
value16 = _SPEC_SIFS_CCK(0x10) | _SPEC_SIFS_OFDM(0x10);
rtl8723au_write16(Adapter, REG_SPEC_SIFS, value16);
/* Retry Limit */
value16 = _LRL(0x30) | _SRL(0x30);
rtl8723au_write16(Adapter, REG_RL, value16);
}
static void _InitRateFallback(struct rtw_adapter *Adapter)
{
/* Set Data Auto Rate Fallback Retry Count register. */
rtl8723au_write32(Adapter, REG_DARFRC, 0x00000000);
rtl8723au_write32(Adapter, REG_DARFRC+4, 0x10080404);
rtl8723au_write32(Adapter, REG_RARFRC, 0x04030201);
rtl8723au_write32(Adapter, REG_RARFRC+4, 0x08070605);
}
static void _InitEDCA(struct rtw_adapter *Adapter)
{
/* Set Spec SIFS (used in NAV) */
rtl8723au_write16(Adapter, REG_SPEC_SIFS, 0x100a);
rtl8723au_write16(Adapter, REG_MAC_SPEC_SIFS, 0x100a);
/* Set SIFS for CCK */
rtl8723au_write16(Adapter, REG_SIFS_CTX, 0x100a);
/* Set SIFS for OFDM */
rtl8723au_write16(Adapter, REG_SIFS_TRX, 0x100a);
/* TXOP */
rtl8723au_write32(Adapter, REG_EDCA_BE_PARAM, 0x005EA42B);
rtl8723au_write32(Adapter, REG_EDCA_BK_PARAM, 0x0000A44F);
rtl8723au_write32(Adapter, REG_EDCA_VI_PARAM, 0x005EA324);
rtl8723au_write32(Adapter, REG_EDCA_VO_PARAM, 0x002FA226);
}
static void _InitRDGSetting(struct rtw_adapter *Adapter)
{
rtl8723au_write8(Adapter, REG_RD_CTRL, 0xFF);
rtl8723au_write16(Adapter, REG_RD_NAV_NXT, 0x200);
rtl8723au_write8(Adapter, REG_RD_RESP_PKT_TH, 0x05);
}
static void _InitRetryFunction(struct rtw_adapter *Adapter)
{
u8 value8;
value8 = rtl8723au_read8(Adapter, REG_FWHW_TXQ_CTRL);
value8 |= EN_AMPDU_RTY_NEW;
rtl8723au_write8(Adapter, REG_FWHW_TXQ_CTRL, value8);
/* Set ACK timeout */
rtl8723au_write8(Adapter, REG_ACKTO, 0x40);
}
static void _InitRFType(struct rtw_adapter *Adapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
bool is92CU = IS_92C_SERIAL(pHalData->VersionID);
pHalData->rf_chip = RF_6052;
if (!is92CU) {
pHalData->rf_type = RF_1T1R;
DBG_8723A("Set RF Chip ID to RF_6052 and RF type to 1T1R.\n");
return;
}
/* TODO: Consider that EEPROM set 92CU to 1T1R later. */
/* Force to overwrite setting according to chip version. Ignore
EEPROM setting. */
/* pHalData->RF_Type = is92CU ? RF_2T2R : RF_1T1R; */
MSG_8723A("Set RF Chip ID to RF_6052 and RF type to %d.\n",
pHalData->rf_type);
}
/* Set CCK and OFDM Block "ON" */
static void _BBTurnOnBlock(struct rtw_adapter *Adapter)
{
PHY_SetBBReg(Adapter, rFPGA0_RFMOD, bCCKEn, 0x1);
PHY_SetBBReg(Adapter, rFPGA0_RFMOD, bOFDMEn, 0x1);
}
#define MgntActSet_RF_State(...)
static void _RfPowerSave(struct rtw_adapter *padapter)
{
}
enum {
Antenna_Lfet = 1,
Antenna_Right = 2,
};
enum rt_rf_power_state RfOnOffDetect23a(struct rtw_adapter *pAdapter)
{
/* struct hal_data_8723a *pHalData = GET_HAL_DATA(pAdapter); */
u8 val8;
enum rt_rf_power_state rfpowerstate = rf_off;
rtl8723au_write8(pAdapter, REG_MAC_PINMUX_CFG,
rtl8723au_read8(pAdapter,
REG_MAC_PINMUX_CFG) & ~BIT(3));
val8 = rtl8723au_read8(pAdapter, REG_GPIO_IO_SEL);
DBG_8723A("GPIO_IN =%02x\n", val8);
rfpowerstate = (val8 & BIT(3)) ? rf_on : rf_off;
return rfpowerstate;
}
int rtl8723au_hal_init(struct rtw_adapter *Adapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
struct pwrctrl_priv *pwrctrlpriv = &Adapter->pwrctrlpriv;
struct registry_priv *pregistrypriv = &Adapter->registrypriv;
u8 val8 = 0;
u32 boundary;
int status = _SUCCESS;
bool mac_on;
unsigned long init_start_time = jiffies;
Adapter->hw_init_completed = false;
if (Adapter->pwrctrlpriv.bkeepfwalive) {
phy_SsPwrSwitch92CU(Adapter, rf_on);
if (pHalData->bIQKInitialized) {
rtl8723a_phy_iq_calibrate(Adapter, true);
} else {
rtl8723a_phy_iq_calibrate(Adapter, false);
pHalData->bIQKInitialized = true;
}
rtl8723a_odm_check_tx_power_tracking(Adapter);
rtl8723a_phy_lc_calibrate(Adapter);
goto exit;
}
/* Check if MAC has already power on. by tynli. 2011.05.27. */
val8 = rtl8723au_read8(Adapter, REG_CR);
RT_TRACE(_module_hci_hal_init_c_, _drv_info_,
("%s: REG_CR 0x100 = 0x%02x\n", __func__, val8));
/* Fix 92DU-VC S3 hang with the reason is that secondary mac is not
initialized. */
/* 0x100 value of first mac is 0xEA while 0x100 value of secondary
is 0x00 */
if (val8 == 0xEA) {
mac_on = false;
} else {
mac_on = true;
RT_TRACE(_module_hci_hal_init_c_, _drv_info_,
("%s: MAC has already power on\n", __func__));
}
status = _InitPowerOn(Adapter);
if (status == _FAIL) {
RT_TRACE(_module_hci_hal_init_c_, _drv_err_,
("Failed to init power on!\n"));
goto exit;
}
if (!pregistrypriv->wifi_spec) {
boundary = TX_PAGE_BOUNDARY;
} else {
/* for WMM */
boundary = WMM_NORMAL_TX_PAGE_BOUNDARY;
}
if (!mac_on) {
status = InitLLTTable23a(Adapter, boundary);
if (status == _FAIL) {
RT_TRACE(_module_hci_hal_init_c_, _drv_err_,
("Failed to init LLT table\n"));
goto exit;
}
}
if (pHalData->bRDGEnable)
_InitRDGSetting(Adapter);
status = rtl8723a_FirmwareDownload(Adapter);
if (status != _SUCCESS) {
Adapter->bFWReady = false;
pHalData->fw_ractrl = false;
DBG_8723A("fw download fail!\n");
goto exit;
} else {
Adapter->bFWReady = true;
pHalData->fw_ractrl = true;
DBG_8723A("fw download ok!\n");
}
rtl8723a_InitializeFirmwareVars(Adapter);
if (pwrctrlpriv->reg_rfoff == true) {
pwrctrlpriv->rf_pwrstate = rf_off;
}
/* 2010/08/09 MH We need to check if we need to turnon or off RF after detecting */
/* HW GPIO pin. Before PHY_RFConfig8192C. */
/* HalDetectPwrDownMode(Adapter); */
/* 2010/08/26 MH If Efuse does not support sective suspend then disable the function. */
/* HalDetectSelectiveSuspendMode(Adapter); */
/* Set RF type for BB/RF configuration */
_InitRFType(Adapter);/* _ReadRFType() */
/* Save target channel */
/* <Roger_Notes> Current Channel will be updated again later. */
pHalData->CurrentChannel = 6;/* default set to 6 */
status = PHY_MACConfig8723A(Adapter);
if (status == _FAIL) {
DBG_8723A("PHY_MACConfig8723A fault !!\n");
goto exit;
}
/* */
/* d. Initialize BB related configurations. */
/* */
status = PHY_BBConfig8723A(Adapter);
if (status == _FAIL) {
DBG_8723A("PHY_BBConfig8723A fault !!\n");
goto exit;
}
/* Add for tx power by rate fine tune. We need to call the function after BB config. */
/* Because the tx power by rate table is inited in BB config. */
status = PHY_RF6052_Config8723A(Adapter);
if (status == _FAIL) {
DBG_8723A("PHY_RF6052_Config8723A failed!!\n");
goto exit;
}
/* reducing 80M spur */
PHY_SetBBReg(Adapter, REG_AFE_XTAL_CTRL, bMaskDWord, 0x0381808d);
PHY_SetBBReg(Adapter, REG_AFE_PLL_CTRL, bMaskDWord, 0xf0ffff83);
PHY_SetBBReg(Adapter, REG_AFE_PLL_CTRL, bMaskDWord, 0xf0ffff82);
PHY_SetBBReg(Adapter, REG_AFE_PLL_CTRL, bMaskDWord, 0xf0ffff83);
/* RFSW Control */
PHY_SetBBReg(Adapter, rFPGA0_TxInfo, bMaskDWord, 0x00000003); /* 0x804[14]= 0 */
PHY_SetBBReg(Adapter, rFPGA0_XAB_RFInterfaceSW, bMaskDWord, 0x07000760); /* 0x870[6:5]= b'11 */
PHY_SetBBReg(Adapter, rFPGA0_XA_RFInterfaceOE, bMaskDWord, 0x66F60210); /* 0x860[6:5]= b'00 */
RT_TRACE(_module_hci_hal_init_c_, _drv_info_, ("%s: 0x870 = value 0x%x\n", __func__, PHY_QueryBBReg(Adapter, 0x870, bMaskDWord)));
/* */
/* Joseph Note: Keep RfRegChnlVal for later use. */
/* */
pHalData->RfRegChnlVal[0] = PHY_QueryRFReg(Adapter, RF_PATH_A,
RF_CHNLBW, bRFRegOffsetMask);
pHalData->RfRegChnlVal[1] = PHY_QueryRFReg(Adapter, RF_PATH_B,
RF_CHNLBW, bRFRegOffsetMask);
if (!mac_on) {
_InitQueueReservedPage(Adapter);
_InitTxBufferBoundary(Adapter);
}
_InitQueuePriority(Adapter);
_InitPageBoundary(Adapter);
_InitTransferPageSize(Adapter);
/* Get Rx PHY status in order to report RSSI and others. */
_InitDriverInfoSize(Adapter, DRVINFO_SZ);
_InitInterrupt(Adapter);
hw_var_set_macaddr(Adapter, Adapter->eeprompriv.mac_addr);
rtl8723a_set_media_status(Adapter, MSR_INFRA);
_InitWMACSetting(Adapter);
_InitAdaptiveCtrl(Adapter);
_InitEDCA(Adapter);
_InitRateFallback(Adapter);
_InitRetryFunction(Adapter);
rtl8723a_InitBeaconParameters(Adapter);
_BBTurnOnBlock(Adapter);
/* NicIFSetMacAddress(padapter, padapter->PermanentAddress); */
rtl8723a_cam_invalidate_all(Adapter);
/* 2010/12/17 MH We need to set TX power according to EFUSE content at first. */
PHY_SetTxPowerLevel8723A(Adapter, pHalData->CurrentChannel);
rtl8723a_InitAntenna_Selection(Adapter);
/* HW SEQ CTRL */
/* set 0x0 to 0xFF by tynli. Default enable HW SEQ NUM. */
rtl8723au_write8(Adapter, REG_HWSEQ_CTRL, 0xFF);
/* */
/* Disable BAR, suggested by Scott */
/* 2010.04.09 add by hpfan */
/* */
rtl8723au_write32(Adapter, REG_BAR_MODE_CTRL, 0x0201ffff);
if (pregistrypriv->wifi_spec)
rtl8723au_write16(Adapter, REG_FAST_EDCA_CTRL, 0);
/* Move by Neo for USB SS from above setp */
_RfPowerSave(Adapter);
/* 2010/08/26 MH Merge from 8192CE. */
/* sherry masked that it has been done in _RfPowerSave */
/* 20110927 */
/* recovery for 8192cu and 9723Au 20111017 */
if (pwrctrlpriv->rf_pwrstate == rf_on) {
if (pHalData->bIQKInitialized) {
rtl8723a_phy_iq_calibrate(Adapter, true);
} else {
rtl8723a_phy_iq_calibrate(Adapter, false);
pHalData->bIQKInitialized = true;
}
rtl8723a_odm_check_tx_power_tracking(Adapter);
rtl8723a_phy_lc_calibrate(Adapter);
rtl8723a_dual_antenna_detection(Adapter);
}
/* fixed USB interface interference issue */
rtl8723au_write8(Adapter, 0xfe40, 0xe0);
rtl8723au_write8(Adapter, 0xfe41, 0x8d);
rtl8723au_write8(Adapter, 0xfe42, 0x80);
rtl8723au_write32(Adapter, 0x20c, 0xfd0320);
/* Solve too many protocol error on USB bus */
if (!IS_81xxC_VENDOR_UMC_A_CUT(pHalData->VersionID)) {
/* 0xE6 = 0x94 */
rtl8723au_write8(Adapter, 0xFE40, 0xE6);
rtl8723au_write8(Adapter, 0xFE41, 0x94);
rtl8723au_write8(Adapter, 0xFE42, 0x80);
/* 0xE0 = 0x19 */
rtl8723au_write8(Adapter, 0xFE40, 0xE0);
rtl8723au_write8(Adapter, 0xFE41, 0x19);
rtl8723au_write8(Adapter, 0xFE42, 0x80);
/* 0xE5 = 0x91 */
rtl8723au_write8(Adapter, 0xFE40, 0xE5);
rtl8723au_write8(Adapter, 0xFE41, 0x91);
rtl8723au_write8(Adapter, 0xFE42, 0x80);
/* 0xE2 = 0x81 */
rtl8723au_write8(Adapter, 0xFE40, 0xE2);
rtl8723au_write8(Adapter, 0xFE41, 0x81);
rtl8723au_write8(Adapter, 0xFE42, 0x80);
}
/* _InitPABias(Adapter); */
/* Init BT hw config. */
rtl8723a_BT_init_hwconfig(Adapter);
rtl8723a_InitHalDm(Adapter);
val8 = ((WiFiNavUpperUs + HAL_8723A_NAV_UPPER_UNIT - 1) /
HAL_8723A_NAV_UPPER_UNIT);
rtl8723au_write8(Adapter, REG_NAV_UPPER, val8);
/* 2011/03/09 MH debug only, UMC-B cut pass 2500 S5 test, but we need to fin root cause. */
if (((rtl8723au_read32(Adapter, rFPGA0_RFMOD) & 0xFF000000) !=
0x83000000)) {
PHY_SetBBReg(Adapter, rFPGA0_RFMOD, BIT(24), 1);
RT_TRACE(_module_hci_hal_init_c_, _drv_err_, ("%s: IQK fail recorver\n", __func__));
}
/* ack for xmit mgmt frames. */
rtl8723au_write32(Adapter, REG_FWHW_TXQ_CTRL,
rtl8723au_read32(Adapter, REG_FWHW_TXQ_CTRL)|BIT(12));
exit:
if (status == _SUCCESS) {
Adapter->hw_init_completed = true;
if (Adapter->registrypriv.notch_filter == 1)
rtl8723a_notch_filter(Adapter, 1);
}
DBG_8723A("%s in %dms\n", __func__,
jiffies_to_msecs(jiffies - init_start_time));
return status;
}
static void phy_SsPwrSwitch92CU(struct rtw_adapter *Adapter,
enum rt_rf_power_state eRFPowerState)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
u8 sps0;
sps0 = rtl8723au_read8(Adapter, REG_SPS0_CTRL);
switch (eRFPowerState) {
case rf_on:
/* 1. Enable MAC Clock. Can not be enabled now. */
/* WriteXBYTE(REG_SYS_CLKR+1,
ReadXBYTE(REG_SYS_CLKR+1) | BIT(3)); */
/* 2. Force PWM, Enable SPS18_LDO_Marco_Block */
rtl8723au_write8(Adapter, REG_SPS0_CTRL,
sps0 | BIT(0) | BIT(3));
/* 3. restore BB, AFE control register. */
/* RF */
if (pHalData->rf_type == RF_2T2R)
PHY_SetBBReg(Adapter, rFPGA0_XAB_RFParameter,
0x380038, 1);
else
PHY_SetBBReg(Adapter, rFPGA0_XAB_RFParameter,
0x38, 1);
PHY_SetBBReg(Adapter, rOFDM0_TRxPathEnable, 0xf0, 1);
PHY_SetBBReg(Adapter, rFPGA0_RFMOD, BIT(1), 0);
/* AFE */
if (pHalData->rf_type == RF_2T2R)
PHY_SetBBReg(Adapter, rRx_Wait_CCA, bMaskDWord,
0x63DB25A0);
else if (pHalData->rf_type == RF_1T1R)
PHY_SetBBReg(Adapter, rRx_Wait_CCA, bMaskDWord,
0x631B25A0);
/* 4. issue 3-wire command that RF set to Rx idle
mode. This is used to re-write the RX idle mode. */
/* We can only prvide a usual value instead and then
HW will modify the value by itself. */
PHY_SetRFReg(Adapter, RF_PATH_A, 0, bRFRegOffsetMask, 0x32D95);
if (pHalData->rf_type == RF_2T2R) {
PHY_SetRFReg(Adapter, RF_PATH_B, 0,
bRFRegOffsetMask, 0x32D95);
}
break;
case rf_sleep:
case rf_off:
if (IS_81xxC_VENDOR_UMC_B_CUT(pHalData->VersionID))
sps0 &= ~BIT(0);
else
sps0 &= ~(BIT(0) | BIT(3));
RT_TRACE(_module_hal_init_c_, _drv_err_, ("SS LVL1\n"));
/* Disable RF and BB only for SelectSuspend. */
/* 1. Set BB/RF to shutdown. */
/* (1) Reg878[5:3]= 0 RF rx_code for
preamble power saving */
/* (2)Reg878[21:19]= 0 Turn off RF-B */
/* (3) RegC04[7:4]= 0 Turn off all paths
for packet detection */
/* (4) Reg800[1] = 1 enable preamble power saving */
Adapter->pwrctrlpriv.PS_BBRegBackup[PSBBREG_RF0] =
PHY_QueryBBReg(Adapter, rFPGA0_XAB_RFParameter,
bMaskDWord);
Adapter->pwrctrlpriv.PS_BBRegBackup[PSBBREG_RF1] =
PHY_QueryBBReg(Adapter, rOFDM0_TRxPathEnable,
bMaskDWord);
Adapter->pwrctrlpriv.PS_BBRegBackup[PSBBREG_RF2] =
PHY_QueryBBReg(Adapter, rFPGA0_RFMOD, bMaskDWord);
if (pHalData->rf_type == RF_2T2R) {
PHY_SetBBReg(Adapter, rFPGA0_XAB_RFParameter,
0x380038, 0);
} else if (pHalData->rf_type == RF_1T1R) {
PHY_SetBBReg(Adapter, rFPGA0_XAB_RFParameter, 0x38, 0);
}
PHY_SetBBReg(Adapter, rOFDM0_TRxPathEnable, 0xf0, 0);
PHY_SetBBReg(Adapter, rFPGA0_RFMOD, BIT(1), 1);
/* 2 .AFE control register to power down. bit[30:22] */
Adapter->pwrctrlpriv.PS_BBRegBackup[PSBBREG_AFE0] =
PHY_QueryBBReg(Adapter, rRx_Wait_CCA, bMaskDWord);
if (pHalData->rf_type == RF_2T2R)
PHY_SetBBReg(Adapter, rRx_Wait_CCA, bMaskDWord,
0x00DB25A0);
else if (pHalData->rf_type == RF_1T1R)
PHY_SetBBReg(Adapter, rRx_Wait_CCA, bMaskDWord,
0x001B25A0);
/* 3. issue 3-wire command that RF set to power down.*/
PHY_SetRFReg(Adapter, RF_PATH_A, 0, bRFRegOffsetMask, 0);
if (pHalData->rf_type == RF_2T2R)
PHY_SetRFReg(Adapter, RF_PATH_B, 0,
bRFRegOffsetMask, 0);
/* 4. Force PFM , disable SPS18_LDO_Marco_Block */
rtl8723au_write8(Adapter, REG_SPS0_CTRL, sps0);
break;
default:
break;
}
}
static void CardDisableRTL8723U(struct rtw_adapter *Adapter)
{
u8 u1bTmp;
DBG_8723A("CardDisableRTL8723U\n");
/* USB-MF Card Disable Flow */
/* 1. Run LPS WL RFOFF flow */
HalPwrSeqCmdParsing23a(Adapter, PWR_CUT_ALL_MSK, PWR_FAB_ALL_MSK,
PWR_INTF_USB_MSK, rtl8723AU_enter_lps_flow);
/* 2. 0x1F[7:0] = 0 turn off RF */
rtl8723au_write8(Adapter, REG_RF_CTRL, 0x00);
/* ==== Reset digital sequence ====== */
if ((rtl8723au_read8(Adapter, REG_MCUFWDL) & BIT(7)) &&
Adapter->bFWReady) /* 8051 RAM code */
rtl8723a_FirmwareSelfReset(Adapter);
/* Reset MCU. Suggested by Filen. 2011.01.26. by tynli. */
u1bTmp = rtl8723au_read8(Adapter, REG_SYS_FUNC_EN+1);
rtl8723au_write8(Adapter, REG_SYS_FUNC_EN+1, u1bTmp & ~BIT(2));
/* g. MCUFWDL 0x80[1:0]= 0 reset MCU ready status */
rtl8723au_write8(Adapter, REG_MCUFWDL, 0x00);
/* ==== Reset digital sequence end ====== */
/* Card disable power action flow */
HalPwrSeqCmdParsing23a(Adapter, PWR_CUT_ALL_MSK, PWR_FAB_ALL_MSK,
PWR_INTF_USB_MSK,
rtl8723AU_card_disable_flow);
/* Reset MCU IO Wrapper, added by Roger, 2011.08.30. */
u1bTmp = rtl8723au_read8(Adapter, REG_RSV_CTRL + 1);
rtl8723au_write8(Adapter, REG_RSV_CTRL+1, u1bTmp & ~BIT(0));
u1bTmp = rtl8723au_read8(Adapter, REG_RSV_CTRL + 1);
rtl8723au_write8(Adapter, REG_RSV_CTRL+1, u1bTmp | BIT(0));
/* 7. RSV_CTRL 0x1C[7:0] = 0x0E lock ISO/CLK/Power control register */
rtl8723au_write8(Adapter, REG_RSV_CTRL, 0x0e);
}
int rtl8723au_hal_deinit(struct rtw_adapter *padapter)
{
DBG_8723A("==> %s\n", __func__);
#ifdef CONFIG_8723AU_BT_COEXIST
BT_HaltProcess(padapter);
#endif
/* 2011/02/18 To Fix RU LNA power leakage problem. We need to
execute below below in Adapter init and halt sequence.
According to EEchou's opinion, we can enable the ability for all */
/* IC. Accord to johnny's opinion, only RU need the support. */
CardDisableRTL8723U(padapter);
padapter->hw_init_completed = false;
return _SUCCESS;
}
int rtl8723au_inirp_init(struct rtw_adapter *Adapter)
{
u8 i;
struct recv_buf *precvbuf;
int status;
struct recv_priv *precvpriv = &Adapter->recvpriv;
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
status = _SUCCESS;
RT_TRACE(_module_hci_hal_init_c_, _drv_info_, ("===> usb_inirp_init\n"));
/* issue Rx irp to receive data */
precvbuf = (struct recv_buf *)precvpriv->precv_buf;
for (i = 0; i < NR_RECVBUFF; i++) {
if (rtl8723au_read_port(Adapter, 0, precvbuf) == _FAIL) {
RT_TRACE(_module_hci_hal_init_c_, _drv_err_,
("usb_rx_init: usb_read_port error\n"));
status = _FAIL;
goto exit;
}
precvbuf++;
}
if (rtl8723au_read_interrupt(Adapter) == _FAIL) {
RT_TRACE(_module_hci_hal_init_c_, _drv_err_,
("%s: usb_read_interrupt error\n", __func__));
status = _FAIL;
}
pHalData->IntrMask[0] = rtl8723au_read32(Adapter, REG_USB_HIMR);
MSG_8723A("pHalData->IntrMask = 0x%04x\n", pHalData->IntrMask[0]);
pHalData->IntrMask[0] |= UHIMR_C2HCMD|UHIMR_CPWM;
rtl8723au_write32(Adapter, REG_USB_HIMR, pHalData->IntrMask[0]);
exit:
RT_TRACE(_module_hci_hal_init_c_, _drv_info_,
("<=== usb_inirp_init\n"));
return status;
}
int rtl8723au_inirp_deinit(struct rtw_adapter *Adapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
RT_TRACE(_module_hci_hal_init_c_, _drv_info_,
("\n ===> usb_rx_deinit\n"));
rtl8723au_read_port_cancel(Adapter);
pHalData->IntrMask[0] = rtl8723au_read32(Adapter, REG_USB_HIMR);
MSG_8723A("%s pHalData->IntrMask = 0x%04x\n", __func__,
pHalData->IntrMask[0]);
pHalData->IntrMask[0] = 0x0;
rtl8723au_write32(Adapter, REG_USB_HIMR, pHalData->IntrMask[0]);
RT_TRACE(_module_hci_hal_init_c_, _drv_info_,
("\n <=== usb_rx_deinit\n"));
return _SUCCESS;
}
static void _ReadBoardType(struct rtw_adapter *Adapter, u8 *PROMContent,
bool AutoloadFail)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
u8 boardType = BOARD_USB_DONGLE;
if (AutoloadFail) {
if (IS_8723_SERIES(pHalData->VersionID))
pHalData->rf_type = RF_1T1R;
else
pHalData->rf_type = RF_2T2R;
pHalData->BoardType = boardType;
return;
}
boardType = PROMContent[EEPROM_NORMAL_BoardType];
boardType &= BOARD_TYPE_NORMAL_MASK;/* bit[7:5] */
boardType >>= 5;
pHalData->BoardType = boardType;
MSG_8723A("_ReadBoardType(%x)\n", pHalData->BoardType);
if (boardType == BOARD_USB_High_PA)
pHalData->ExternalPA = 1;
}
static void Hal_EfuseParseMACAddr_8723AU(struct rtw_adapter *padapter,
u8 *hwinfo, bool AutoLoadFail)
{
u16 i;
u8 sMacAddr[ETH_ALEN] = {0x00, 0xE0, 0x4C, 0x87, 0x23, 0x00};
struct eeprom_priv *pEEPROM = GET_EEPROM_EFUSE_PRIV(padapter);
if (AutoLoadFail) {
for (i = 0; i < 6; i++)
pEEPROM->mac_addr[i] = sMacAddr[i];
} else {
/* Read Permanent MAC address */
memcpy(pEEPROM->mac_addr, &hwinfo[EEPROM_MAC_ADDR_8723AU],
ETH_ALEN);
}
RT_TRACE(_module_hci_hal_init_c_, _drv_notice_,
("Hal_EfuseParseMACAddr_8723AU: Permanent Address =%02x:%02x:"
"%02x:%02x:%02x:%02x\n",
pEEPROM->mac_addr[0], pEEPROM->mac_addr[1],
pEEPROM->mac_addr[2], pEEPROM->mac_addr[3],
pEEPROM->mac_addr[4], pEEPROM->mac_addr[5]));
}
static void readAdapterInfo(struct rtw_adapter *padapter)
{
struct eeprom_priv *pEEPROM = GET_EEPROM_EFUSE_PRIV(padapter);
/* struct hal_data_8723a * pHalData = GET_HAL_DATA(padapter); */
u8 hwinfo[HWSET_MAX_SIZE];
Hal_InitPGData(padapter, hwinfo);
Hal_EfuseParseIDCode(padapter, hwinfo);
Hal_EfuseParseEEPROMVer(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
Hal_EfuseParseMACAddr_8723AU(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
Hal_EfuseParsetxpowerinfo_8723A(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
_ReadBoardType(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseBTCoexistInfo_8723A(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
rtl8723a_EfuseParseChnlPlan(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
Hal_EfuseParseThermalMeter_8723A(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
/* _ReadRFSetting(Adapter, PROMContent, pEEPROM->bautoload_fail_flag); */
/* _ReadPSSetting(Adapter, PROMContent, pEEPROM->bautoload_fail_flag); */
Hal_EfuseParseAntennaDiversity(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
Hal_EfuseParseEEPROMVer(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseCustomerID(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
Hal_EfuseParseRateIndicationOption(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
Hal_EfuseParseXtal_8723A(padapter, hwinfo,
pEEPROM->bautoload_fail_flag);
/* hal_CustomizedBehavior_8723U(Adapter); */
/* Adapter->bDongle = (PROMContent[EEPROM_EASY_REPLACEMENT] == 1)? 0: 1; */
DBG_8723A("%s(): REPLACEMENT = %x\n", __func__, padapter->bDongle);
}
static void _ReadPROMContent(struct rtw_adapter *Adapter)
{
struct eeprom_priv *pEEPROM = GET_EEPROM_EFUSE_PRIV(Adapter);
u8 eeValue;
eeValue = rtl8723au_read8(Adapter, REG_9346CR);
/* To check system boot selection. */
pEEPROM->EepromOrEfuse = (eeValue & BOOT_FROM_EEPROM) ? true : false;
pEEPROM->bautoload_fail_flag = (eeValue & EEPROM_EN) ? false : true;
DBG_8723A("Boot from %s, Autoload %s !\n",
(pEEPROM->EepromOrEfuse ? "EEPROM" : "EFUSE"),
(pEEPROM->bautoload_fail_flag ? "Fail" : "OK"));
readAdapterInfo(Adapter);
}
static void _ReadRFType(struct rtw_adapter *Adapter)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
pHalData->rf_chip = RF_6052;
}
/* */
/* Description: */
/* We should set Efuse cell selection to WiFi cell in default. */
/* */
/* Assumption: */
/* PASSIVE_LEVEL */
/* */
/* Added by Roger, 2010.11.23. */
/* */
static void hal_EfuseCellSel(struct rtw_adapter *Adapter)
{
u32 value32;
value32 = rtl8723au_read32(Adapter, EFUSE_TEST);
value32 = (value32 & ~EFUSE_SEL_MASK) | EFUSE_SEL(EFUSE_WIFI_SEL_0);
rtl8723au_write32(Adapter, EFUSE_TEST, value32);
}
void rtl8723a_read_adapter_info(struct rtw_adapter *Adapter)
{
unsigned long start = jiffies;
/* Read EEPROM size before call any EEPROM function */
Adapter->EepromAddressSize = GetEEPROMSize8723A(Adapter);
MSG_8723A("====> _ReadAdapterInfo8723AU\n");
hal_EfuseCellSel(Adapter);
_ReadRFType(Adapter);/* rf_chip -> _InitRFType() */
_ReadPROMContent(Adapter);
/* MSG_8723A("%s()(done), rf_chip = 0x%x, rf_type = 0x%x\n",
__func__, pHalData->rf_chip, pHalData->rf_type); */
MSG_8723A("<==== _ReadAdapterInfo8723AU in %d ms\n",
jiffies_to_msecs(jiffies - start));
}
/* */
/* Description: */
/* Query setting of specified variable. */
/* */
int GetHalDefVar8192CUsb(struct rtw_adapter *Adapter,
enum hal_def_variable eVariable, void *pValue)
{
struct hal_data_8723a *pHalData = GET_HAL_DATA(Adapter);
int bResult = _SUCCESS;
switch (eVariable) {
case HAL_DEF_UNDERCORATEDSMOOTHEDPWDB:
*((int *)pValue) = pHalData->dmpriv.UndecoratedSmoothedPWDB;
break;
case HAL_DEF_IS_SUPPORT_ANT_DIV:
break;
case HAL_DEF_CURRENT_ANTENNA:
break;
case HAL_DEF_DRVINFO_SZ:
*((u32 *)pValue) = DRVINFO_SZ;
break;
case HAL_DEF_MAX_RECVBUF_SZ:
*((u32 *)pValue) = MAX_RECVBUF_SZ;
break;
case HAL_DEF_RX_PACKET_OFFSET:
*((u32 *)pValue) = RXDESC_SIZE + DRVINFO_SZ;
break;
case HAL_DEF_DBG_DUMP_RXPKT:
*((u8 *)pValue) = pHalData->bDumpRxPkt;
break;
case HAL_DEF_DBG_DM_FUNC:
*((u32 *)pValue) = pHalData->odmpriv.SupportAbility;
break;
case HW_VAR_MAX_RX_AMPDU_FACTOR:
*((u32 *)pValue) = IEEE80211_HT_MAX_AMPDU_64K;
break;
case HW_DEF_ODM_DBG_FLAG:
{
struct dm_odm_t *pDM_Odm = &pHalData->odmpriv;
printk("pDM_Odm->DebugComponents = 0x%llx\n",
pDM_Odm->DebugComponents);
}
break;
default:
/* RT_TRACE(COMP_INIT, DBG_WARNING, ("GetHalDefVar8192CUsb(): "
"Unkown variable: %d!\n", eVariable)); */
bResult = _FAIL;
break;
}
return bResult;
}
void rtl8723a_update_ramask(struct rtw_adapter *padapter,
u32 mac_id, u8 rssi_level)
{
struct sta_info *psta;
struct FW_Sta_Info *fw_sta;
struct hal_data_8723a *pHalData = GET_HAL_DATA(padapter);
struct dm_priv *pdmpriv = &pHalData->dmpriv;
struct mlme_ext_priv *pmlmeext = &padapter->mlmeextpriv;
struct mlme_ext_info *pmlmeinfo = &pmlmeext->mlmext_info;
struct wlan_bssid_ex *cur_network = &pmlmeinfo->network;
u8 init_rate, networkType, raid;
u32 mask, rate_bitmap;
u8 shortGIrate = false;
int supportRateNum;
if (mac_id >= NUM_STA) /* CAM_SIZE */
return;
psta = pmlmeinfo->FW_sta_info[mac_id].psta;
if (psta == NULL)
return;
switch (mac_id) {
case 0:/* for infra mode */
supportRateNum =
rtw_get_rateset_len23a(cur_network->SupportedRates);
networkType = judge_network_type23a(padapter,
cur_network->SupportedRates,
supportRateNum) & 0xf;
/* pmlmeext->cur_wireless_mode = networkType; */
raid = networktype_to_raid23a(networkType);
mask = update_supported_rate23a(cur_network->SupportedRates,
supportRateNum);
mask |= (pmlmeinfo->HT_enable) ?
update_MSC_rate23a(&pmlmeinfo->ht_cap) : 0;
if (support_short_GI23a(padapter, &pmlmeinfo->ht_cap))
shortGIrate = true;
break;
case 1:/* for broadcast/multicast */
fw_sta = &pmlmeinfo->FW_sta_info[mac_id];
supportRateNum = rtw_get_rateset_len23a(fw_sta->SupportedRates);
if (pmlmeext->cur_wireless_mode & WIRELESS_11B)
networkType = WIRELESS_11B;
else
networkType = WIRELESS_11G;
raid = networktype_to_raid23a(networkType);
mask = update_basic_rate23a(cur_network->SupportedRates,
supportRateNum);
break;
default: /* for each sta in IBSS */
fw_sta = &pmlmeinfo->FW_sta_info[mac_id];
supportRateNum = rtw_get_rateset_len23a(fw_sta->SupportedRates);
networkType = judge_network_type23a(padapter,
fw_sta->SupportedRates,
supportRateNum) & 0xf;
/* pmlmeext->cur_wireless_mode = networkType; */
raid = networktype_to_raid23a(networkType);
mask = update_supported_rate23a(cur_network->SupportedRates,
supportRateNum);
/* todo: support HT in IBSS */
break;
}
/* mask &= 0x0fffffff; */
rate_bitmap = ODM_Get_Rate_Bitmap23a(pHalData, mac_id, mask,
rssi_level);
DBG_8723A("%s => mac_id:%d, networkType:0x%02x, "
"mask:0x%08x\n\t ==> rssi_level:%d, rate_bitmap:0x%08x\n",
__func__, mac_id, networkType, mask, rssi_level, rate_bitmap);
mask &= rate_bitmap;
mask |= ((raid << 28) & 0xf0000000);
init_rate = get_highest_rate_idx23a(mask) & 0x3f;
if (pHalData->fw_ractrl == true) {
u8 arg = 0;
arg = mac_id & 0x1f;/* MACID */
arg |= BIT(7);
if (shortGIrate == true)
arg |= BIT(5);
DBG_8723A("update raid entry, mask = 0x%x, arg = 0x%x\n",
mask, arg);
rtl8723a_set_raid_cmd(padapter, mask, arg);
} else {
if (shortGIrate == true)
init_rate |= BIT(6);
rtl8723au_write8(padapter, (REG_INIDATA_RATE_SEL + mac_id),
init_rate);
}
/* set ra_id */
psta->raid = raid;
psta->init_rate = init_rate;
/* set correct initial date rate for each mac_id */
pdmpriv->INIDATA_RATE[mac_id] = init_rate;
}
| gpl-2.0 |
theophile/amazon_fire_kffowi_bonus_modules | drivers/misc/mediatek/masp/asf/core/alg_aes_export.c | 128 | 4536 | #include "sec_osal_light.h"
/**************************************************************************
* TYPEDEF
**************************************************************************/
typedef unsigned int uint32;
typedef unsigned char uchar;
/**************************************************************************
* AES FUNCTION
**************************************************************************/
#include "sec_aes.h"
/* legacy function used for W1128/32 MP */
#include "aes_legacy.h"
/* standard operation aes function used for W1150 MP */
#include "aes_so.h"
/**************************************************************************
* DEFINITIONS
**************************************************************************/
#define MOD "AES_EXPORT"
/**************************************************************************
* MACRO
**************************************************************************/
#define SMSG printk
/**************************************************************************
* GLOBAL VARIABLE
**************************************************************************/
/* using W1128/32 mP solution by default */
AES_VER g_ver = AES_VER_LEGACY;
/**************************************************************************
* LIBRARY EXPORT FUNCTION - ENCRYPTION
**************************************************************************/
int lib_aes_enc(uchar* input_buf, uint32 input_len, uchar* output_buf, uint32 output_len)
{
switch (g_ver)
{
case AES_VER_LEGACY:
if(0 != aes_legacy_enc(input_buf,input_len,output_buf,output_len))
{
goto _err;
}
break;
case AES_VER_SO:
if(0 != aes_so_enc(input_buf,input_len,output_buf,output_len))
{
goto _err;
}
break;
default:
SMSG("[%s] Invalid Ver\n",MOD);
goto _err;
}
return 0;
_err:
return -1;
}
/**************************************************************************
* LIBRARY EXPORT FUNCTION - DECRYPTION
**************************************************************************/
int lib_aes_dec(uchar* input_buf, uint32 input_len, uchar* output_buf, uint32 output_len)
{
switch (g_ver)
{
case AES_VER_LEGACY:
if(0 != aes_legacy_dec(input_buf,input_len,output_buf,output_len))
{
goto _err;
}
break;
case AES_VER_SO:
if(0 != aes_so_dec(input_buf,input_len,output_buf,output_len))
{
goto _err;
}
break;
default:
SMSG("[%s] Invalid Ver\n",MOD);
goto _err;
}
return 0;
_err:
return -1;
}
/**************************************************************************
* LIBRARY EXPORT FUNCTION - KEY INITIALIZATION
**************************************************************************/
int lib_aes_init_key(uchar* key_buf, uint32 key_len, AES_VER ver)
{
switch (ver)
{
case AES_VER_LEGACY:
g_ver = AES_VER_LEGACY;
SMSG("\n[%s] Legacy\n",MOD);
if(0 != aes_legacy_init_key(key_buf,key_len))
{
goto _err;
}
break;
case AES_VER_SO:
g_ver = AES_VER_SO;
SMSG("\n[%s] SO\n",MOD);
if(0 != aes_so_init_key(key_buf,key_len))
{
goto _err;
}
break;
default:
SMSG("\n[%s] Invalid Ver\n",MOD);
goto _err;
}
return 0;
_err:
return -1;
}
int lib_aes_init_vector(AES_VER ver)
{
switch (ver)
{
case AES_VER_LEGACY:
g_ver = AES_VER_LEGACY;
SMSG("[%s] Legacy(V)\n",MOD);
if(0 != aes_legacy_init_vector())
{
goto _err;
}
break;
case AES_VER_SO:
g_ver = AES_VER_SO;
SMSG("[%s] SO(V)\n",MOD);
if(0 != aes_so_init_vector())
{
goto _err;
}
break;
default:
SMSG("[%s] Invalid Ver(V)\n",MOD);
goto _err;
}
return 0;
_err:
return -1;
}
| gpl-2.0 |
cholokei/android_kernel_samsung_dalikt | drivers/media/tdmb/fc8050/fc8050_spi.c | 384 | 8083 | /*****************************************************************************
Copyright(c) 2009 FCI Inc. All Rights Reserved
File name : fc8050_spi.c
Description : fc8050 host interface
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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
History :
----------------------------------------------------------------------
2009/08/29 jason initial
*******************************************************************************/
#include <linux/input.h>
#include <linux/spi/spi.h>
#include "fci_types.h"
#include "fc8050_regs.h"
#include "fci_oal.h"
#include "fc8050_spi.h"
#include "tdmb.h"
#define DRIVER_NAME "fc8050_spi"
#define HPIC_READ 0x01 /* read command */
#define HPIC_WRITE 0x02 /* write command */
#define HPIC_AINC 0x04 /* address increment */
#define HPIC_BMODE 0x00 /* byte mode */
#define HPIC_WMODE 0x10 /* word mode */
#define HPIC_LMODE 0x20 /* long mode */
#define HPIC_ENDIAN 0x00 /* little endian */
#define HPIC_CLEAR 0x80 /* currently not used */
#define CHIPID 0
#if (CHIPID == 0)
#define SPI_CMD_WRITE 0x0
#define SPI_CMD_READ 0x1
#define SPI_CMD_BURST_WRITE 0x2
#define SPI_CMD_BURST_READ 0x3
#else
#define SPI_CMD_WRITE 0x4
#define SPI_CMD_READ 0x5
#define SPI_CMD_BURST_WRITE 0x6
#define SPI_CMD_BURST_READ 0x7
#endif
struct spi_device *fc8050_spi;
static u8 tx_data[32] __cacheline_aligned;
static DEFINE_MUTEX(lock);
int fc8050_spi_write_then_read(
struct spi_device *spi
, u8 *txbuf
, u16 tx_length
, u8 *rxbuf
, u16 rx_length)
{
s32 res;
struct spi_message message;
struct spi_transfer x;
spi_message_init(&message);
memset(&x, 0, sizeof x);
spi_message_add_tail(&x, &message);
x.tx_buf = txbuf;
x.rx_buf = txbuf;
x.len = tx_length + rx_length;
res = spi_sync(spi, &message);
memcpy(rxbuf, x.rx_buf + tx_length, rx_length);
return res;
}
int fc8050_spi_write_then_burstread(
struct spi_device *spi
, u8 *txbuf
, u16 tx_length
, u8 *rxbuf
, u16 rx_length)
{
s32 res;
struct spi_message message;
struct spi_transfer x;
spi_message_init(&message);
memset(&x, 0, sizeof x);
spi_message_add_tail(&x, &message);
x.tx_buf = txbuf;
x.rx_buf = rxbuf;
x.len = tx_length + rx_length;
res = spi_sync(spi, &message);
return res;
}
static int spi_bulkread(HANDLE hDevice, u8 addr, u8 *data, u16 length)
{
s32 ret;
tx_data[0] = SPI_CMD_BURST_READ;
tx_data[1] = addr;
fc8050_spi = tdmb_get_spi_handle();
ret = fc8050_spi_write_then_read(
fc8050_spi, &tx_data[0], 2, &data[0], length);
if (ret) {
print_log(0, "fc8050_spi_bulkread fail : %d\n", ret);
return BBM_NOK;
}
return BBM_OK;
}
static int spi_bulkwrite(HANDLE hDevice, u8 addr, u8 *data, u16 length)
{
s32 ret;
s32 i;
tx_data[0] = SPI_CMD_BURST_WRITE;
tx_data[1] = addr;
for (i = 0; i < length; i++)
tx_data[2+i] = data[i];
fc8050_spi = tdmb_get_spi_handle();
ret = fc8050_spi_write_then_read(
fc8050_spi, &tx_data[0], length+2, NULL, 0);
if (ret) {
print_log(0, "fc8050_spi_bulkwrite fail : %d\n", ret);
return BBM_NOK;
}
return BBM_OK;
}
static int spi_dataread(HANDLE hDevice, u8 addr, u8 *data, u16 length)
{
s32 ret = 0;
tx_data[0] = SPI_CMD_BURST_READ;
tx_data[1] = addr;
fc8050_spi = tdmb_get_spi_handle();
ret = fc8050_spi_write_then_burstread(
fc8050_spi, &tx_data[0], 2, &data[0], length);
if (ret) {
print_log(0, "fc8050_spi_dataread fail : %d\n", ret);
return BBM_NOK;
}
return BBM_OK;
}
int fc8050_spi_init(HANDLE hDevice, u16 param1, u16 param2)
{
return BBM_OK;
}
int fc8050_spi_byteread(HANDLE hDevice, u16 addr, u8 *data)
{
int res;
u8 command = HPIC_READ | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkread(hDevice, BBM_DATA_REG, data, 1);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_wordread(HANDLE hDevice, u16 addr, u16 *data)
{
int res;
u8 command = HPIC_READ | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
if (BBM_SCI_DATA <= addr && BBM_SCI_SYNCRX >= addr)
command = HPIC_READ | HPIC_WMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkread(hDevice, BBM_DATA_REG, (u8 *)data, 2);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_longread(HANDLE hDevice, u16 addr, u32 *data)
{
int res;
u8 command = HPIC_READ | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkread(hDevice, BBM_DATA_REG, (u8 *)data, 4);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_bulkread(HANDLE hDevice, u16 addr, u8 *data, u16 length)
{
int res;
u8 command = HPIC_READ | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkread(hDevice, BBM_DATA_REG, data, length);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_bytewrite(HANDLE hDevice, u16 addr, u8 data)
{
int res;
u8 command = HPIC_WRITE | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkwrite(hDevice, BBM_DATA_REG, (u8 *)&data, 1);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_wordwrite(HANDLE hDevice, u16 addr, u16 data)
{
int res;
u8 command = HPIC_WRITE | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
if (BBM_SCI_DATA <= addr && BBM_SCI_SYNCRX >= addr)
command = HPIC_WRITE | HPIC_WMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkwrite(hDevice, BBM_DATA_REG, (u8 *)&data, 2);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_longwrite(HANDLE hDevice, u16 addr, u32 data)
{
int res;
u8 command = HPIC_WRITE | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkwrite(hDevice, BBM_DATA_REG, (u8 *)&data, 4);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_bulkwrite(HANDLE hDevice, u16 addr, u8 *data, u16 length)
{
int res;
u8 command = HPIC_WRITE | HPIC_AINC | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_bulkwrite(hDevice, BBM_DATA_REG, data, length);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_dataread(HANDLE hDevice, u16 addr, u8 *data, u16 length)
{
int res;
u8 command = HPIC_READ | HPIC_BMODE | HPIC_ENDIAN;
mutex_lock(&lock);
res = spi_bulkwrite(hDevice, BBM_COMMAND_REG, &command, 1);
res |= spi_bulkwrite(hDevice, BBM_ADDRESS_REG, (u8 *)&addr, 2);
res |= spi_dataread(hDevice, BBM_DATA_REG, data, length);
mutex_unlock(&lock);
return res;
}
int fc8050_spi_deinit(HANDLE hDevice)
{
print_log(NULL, "fc8050_spi_deinit\n");
return BBM_OK;
}
| gpl-2.0 |
akiradeveloper/linux | sound/core/jack.c | 1152 | 6736 | /*
* Jack abstraction layer
*
* Copyright 2008 Wolfson Microelectronics
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <sound/jack.h>
#include <sound/core.h>
static int jack_switch_types[SND_JACK_SWITCH_TYPES] = {
SW_HEADPHONE_INSERT,
SW_MICROPHONE_INSERT,
SW_LINEOUT_INSERT,
SW_JACK_PHYSICAL_INSERT,
SW_VIDEOOUT_INSERT,
SW_LINEIN_INSERT,
};
static int snd_jack_dev_disconnect(struct snd_device *device)
{
struct snd_jack *jack = device->device_data;
if (!jack->input_dev)
return 0;
/* If the input device is registered with the input subsystem
* then we need to use a different deallocator. */
if (jack->registered)
input_unregister_device(jack->input_dev);
else
input_free_device(jack->input_dev);
jack->input_dev = NULL;
return 0;
}
static int snd_jack_dev_free(struct snd_device *device)
{
struct snd_jack *jack = device->device_data;
if (jack->private_free)
jack->private_free(jack);
snd_jack_dev_disconnect(device);
kfree(jack->id);
kfree(jack);
return 0;
}
static int snd_jack_dev_register(struct snd_device *device)
{
struct snd_jack *jack = device->device_data;
struct snd_card *card = device->card;
int err, i;
snprintf(jack->name, sizeof(jack->name), "%s %s",
card->shortname, jack->id);
jack->input_dev->name = jack->name;
/* Default to the sound card device. */
if (!jack->input_dev->dev.parent)
jack->input_dev->dev.parent = snd_card_get_device_link(card);
/* Add capabilities for any keys that are enabled */
for (i = 0; i < ARRAY_SIZE(jack->key); i++) {
int testbit = SND_JACK_BTN_0 >> i;
if (!(jack->type & testbit))
continue;
if (!jack->key[i])
jack->key[i] = BTN_0 + i;
input_set_capability(jack->input_dev, EV_KEY, jack->key[i]);
}
err = input_register_device(jack->input_dev);
if (err == 0)
jack->registered = 1;
return err;
}
/**
* snd_jack_new - Create a new jack
* @card: the card instance
* @id: an identifying string for this jack
* @type: a bitmask of enum snd_jack_type values that can be detected by
* this jack
* @jjack: Used to provide the allocated jack object to the caller.
*
* Creates a new jack object.
*
* Return: Zero if successful, or a negative error code on failure.
* On success @jjack will be initialised.
*/
int snd_jack_new(struct snd_card *card, const char *id, int type,
struct snd_jack **jjack)
{
struct snd_jack *jack;
int err;
int i;
static struct snd_device_ops ops = {
.dev_free = snd_jack_dev_free,
.dev_register = snd_jack_dev_register,
.dev_disconnect = snd_jack_dev_disconnect,
};
jack = kzalloc(sizeof(struct snd_jack), GFP_KERNEL);
if (jack == NULL)
return -ENOMEM;
jack->id = kstrdup(id, GFP_KERNEL);
jack->input_dev = input_allocate_device();
if (jack->input_dev == NULL) {
err = -ENOMEM;
goto fail_input;
}
jack->input_dev->phys = "ALSA";
jack->type = type;
for (i = 0; i < SND_JACK_SWITCH_TYPES; i++)
if (type & (1 << i))
input_set_capability(jack->input_dev, EV_SW,
jack_switch_types[i]);
err = snd_device_new(card, SNDRV_DEV_JACK, jack, &ops);
if (err < 0)
goto fail_input;
*jjack = jack;
return 0;
fail_input:
input_free_device(jack->input_dev);
kfree(jack->id);
kfree(jack);
return err;
}
EXPORT_SYMBOL(snd_jack_new);
/**
* snd_jack_set_parent - Set the parent device for a jack
*
* @jack: The jack to configure
* @parent: The device to set as parent for the jack.
*
* Set the parent for the jack devices in the device tree. This
* function is only valid prior to registration of the jack. If no
* parent is configured then the parent device will be the sound card.
*/
void snd_jack_set_parent(struct snd_jack *jack, struct device *parent)
{
WARN_ON(jack->registered);
jack->input_dev->dev.parent = parent;
}
EXPORT_SYMBOL(snd_jack_set_parent);
/**
* snd_jack_set_key - Set a key mapping on a jack
*
* @jack: The jack to configure
* @type: Jack report type for this key
* @keytype: Input layer key type to be reported
*
* Map a SND_JACK_BTN_ button type to an input layer key, allowing
* reporting of keys on accessories via the jack abstraction. If no
* mapping is provided but keys are enabled in the jack type then
* BTN_n numeric buttons will be reported.
*
* If jacks are not reporting via the input API this call will have no
* effect.
*
* Note that this is intended to be use by simple devices with small
* numbers of keys that can be reported. It is also possible to
* access the input device directly - devices with complex input
* capabilities on accessories should consider doing this rather than
* using this abstraction.
*
* This function may only be called prior to registration of the jack.
*
* Return: Zero if successful, or a negative error code on failure.
*/
int snd_jack_set_key(struct snd_jack *jack, enum snd_jack_types type,
int keytype)
{
int key = fls(SND_JACK_BTN_0) - fls(type);
WARN_ON(jack->registered);
if (!keytype || key >= ARRAY_SIZE(jack->key))
return -EINVAL;
jack->type |= type;
jack->key[key] = keytype;
return 0;
}
EXPORT_SYMBOL(snd_jack_set_key);
/**
* snd_jack_report - Report the current status of a jack
*
* @jack: The jack to report status for
* @status: The current status of the jack
*/
void snd_jack_report(struct snd_jack *jack, int status)
{
int i;
if (!jack)
return;
for (i = 0; i < ARRAY_SIZE(jack->key); i++) {
int testbit = SND_JACK_BTN_0 >> i;
if (jack->type & testbit)
input_report_key(jack->input_dev, jack->key[i],
status & testbit);
}
for (i = 0; i < ARRAY_SIZE(jack_switch_types); i++) {
int testbit = 1 << i;
if (jack->type & testbit)
input_report_switch(jack->input_dev,
jack_switch_types[i],
status & testbit);
}
input_sync(jack->input_dev);
}
EXPORT_SYMBOL(snd_jack_report);
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_DESCRIPTION("Jack detection support for ALSA");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ch33kybutt/D3v1l-kernel | net/ipv4/tcp_yeah.c | 1152 | 7050 | /*
*
* YeAH TCP
*
* For further details look at:
* http://wil.cs.caltech.edu/pfldnet2007/paper/YeAH_TCP.pdf
*
*/
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/inet_diag.h>
#include <net/tcp.h>
#include "tcp_vegas.h"
#define TCP_YEAH_ALPHA 80 //lin number of packets queued at the bottleneck
#define TCP_YEAH_GAMMA 1 //lin fraction of queue to be removed per rtt
#define TCP_YEAH_DELTA 3 //log minimum fraction of cwnd to be removed on loss
#define TCP_YEAH_EPSILON 1 //log maximum fraction to be removed on early decongestion
#define TCP_YEAH_PHY 8 //lin maximum delta from base
#define TCP_YEAH_RHO 16 //lin minumum number of consecutive rtt to consider competition on loss
#define TCP_YEAH_ZETA 50 //lin minimum number of state switchs to reset reno_count
#define TCP_SCALABLE_AI_CNT 100U
/* YeAH variables */
struct yeah {
struct vegas vegas; /* must be first */
/* YeAH */
u32 lastQ;
u32 doing_reno_now;
u32 reno_count;
u32 fast_count;
u32 pkts_acked;
};
static void tcp_yeah_init(struct sock *sk)
{
struct tcp_sock *tp = tcp_sk(sk);
struct yeah *yeah = inet_csk_ca(sk);
tcp_vegas_init(sk);
yeah->doing_reno_now = 0;
yeah->lastQ = 0;
yeah->reno_count = 2;
/* Ensure the MD arithmetic works. This is somewhat pedantic,
* since I don't think we will see a cwnd this large. :) */
tp->snd_cwnd_clamp = min_t(u32, tp->snd_cwnd_clamp, 0xffffffff/128);
}
static void tcp_yeah_pkts_acked(struct sock *sk, u32 pkts_acked, s32 rtt_us)
{
const struct inet_connection_sock *icsk = inet_csk(sk);
struct yeah *yeah = inet_csk_ca(sk);
if (icsk->icsk_ca_state == TCP_CA_Open)
yeah->pkts_acked = pkts_acked;
tcp_vegas_pkts_acked(sk, pkts_acked, rtt_us);
}
static void tcp_yeah_cong_avoid(struct sock *sk, u32 ack, u32 in_flight)
{
struct tcp_sock *tp = tcp_sk(sk);
struct yeah *yeah = inet_csk_ca(sk);
if (!tcp_is_cwnd_limited(sk, in_flight))
return;
if (tp->snd_cwnd <= tp->snd_ssthresh)
tcp_slow_start(tp);
else if (!yeah->doing_reno_now) {
/* Scalable */
tp->snd_cwnd_cnt += yeah->pkts_acked;
if (tp->snd_cwnd_cnt > min(tp->snd_cwnd, TCP_SCALABLE_AI_CNT)){
if (tp->snd_cwnd < tp->snd_cwnd_clamp)
tp->snd_cwnd++;
tp->snd_cwnd_cnt = 0;
}
yeah->pkts_acked = 1;
} else {
/* Reno */
tcp_cong_avoid_ai(tp, tp->snd_cwnd);
}
/* The key players are v_vegas.beg_snd_una and v_beg_snd_nxt.
*
* These are so named because they represent the approximate values
* of snd_una and snd_nxt at the beginning of the current RTT. More
* precisely, they represent the amount of data sent during the RTT.
* At the end of the RTT, when we receive an ACK for v_beg_snd_nxt,
* we will calculate that (v_beg_snd_nxt - v_vegas.beg_snd_una) outstanding
* bytes of data have been ACKed during the course of the RTT, giving
* an "actual" rate of:
*
* (v_beg_snd_nxt - v_vegas.beg_snd_una) / (rtt duration)
*
* Unfortunately, v_vegas.beg_snd_una is not exactly equal to snd_una,
* because delayed ACKs can cover more than one segment, so they
* don't line up yeahly with the boundaries of RTTs.
*
* Another unfortunate fact of life is that delayed ACKs delay the
* advance of the left edge of our send window, so that the number
* of bytes we send in an RTT is often less than our cwnd will allow.
* So we keep track of our cwnd separately, in v_beg_snd_cwnd.
*/
if (after(ack, yeah->vegas.beg_snd_nxt)) {
/* We do the Vegas calculations only if we got enough RTT
* samples that we can be reasonably sure that we got
* at least one RTT sample that wasn't from a delayed ACK.
* If we only had 2 samples total,
* then that means we're getting only 1 ACK per RTT, which
* means they're almost certainly delayed ACKs.
* If we have 3 samples, we should be OK.
*/
if (yeah->vegas.cntRTT > 2) {
u32 rtt, queue;
u64 bw;
/* We have enough RTT samples, so, using the Vegas
* algorithm, we determine if we should increase or
* decrease cwnd, and by how much.
*/
/* Pluck out the RTT we are using for the Vegas
* calculations. This is the min RTT seen during the
* last RTT. Taking the min filters out the effects
* of delayed ACKs, at the cost of noticing congestion
* a bit later.
*/
rtt = yeah->vegas.minRTT;
/* Compute excess number of packets above bandwidth
* Avoid doing full 64 bit divide.
*/
bw = tp->snd_cwnd;
bw *= rtt - yeah->vegas.baseRTT;
do_div(bw, rtt);
queue = bw;
if (queue > TCP_YEAH_ALPHA ||
rtt - yeah->vegas.baseRTT > (yeah->vegas.baseRTT / TCP_YEAH_PHY)) {
if (queue > TCP_YEAH_ALPHA &&
tp->snd_cwnd > yeah->reno_count) {
u32 reduction = min(queue / TCP_YEAH_GAMMA ,
tp->snd_cwnd >> TCP_YEAH_EPSILON);
tp->snd_cwnd -= reduction;
tp->snd_cwnd = max(tp->snd_cwnd,
yeah->reno_count);
tp->snd_ssthresh = tp->snd_cwnd;
}
if (yeah->reno_count <= 2)
yeah->reno_count = max(tp->snd_cwnd>>1, 2U);
else
yeah->reno_count++;
yeah->doing_reno_now = min(yeah->doing_reno_now + 1,
0xffffffU);
} else {
yeah->fast_count++;
if (yeah->fast_count > TCP_YEAH_ZETA) {
yeah->reno_count = 2;
yeah->fast_count = 0;
}
yeah->doing_reno_now = 0;
}
yeah->lastQ = queue;
}
/* Save the extent of the current window so we can use this
* at the end of the next RTT.
*/
yeah->vegas.beg_snd_una = yeah->vegas.beg_snd_nxt;
yeah->vegas.beg_snd_nxt = tp->snd_nxt;
yeah->vegas.beg_snd_cwnd = tp->snd_cwnd;
/* Wipe the slate clean for the next RTT. */
yeah->vegas.cntRTT = 0;
yeah->vegas.minRTT = 0x7fffffff;
}
}
static u32 tcp_yeah_ssthresh(struct sock *sk) {
const struct tcp_sock *tp = tcp_sk(sk);
struct yeah *yeah = inet_csk_ca(sk);
u32 reduction;
if (yeah->doing_reno_now < TCP_YEAH_RHO) {
reduction = yeah->lastQ;
reduction = min( reduction, max(tp->snd_cwnd>>1, 2U) );
reduction = max( reduction, tp->snd_cwnd >> TCP_YEAH_DELTA);
} else
reduction = max(tp->snd_cwnd>>1, 2U);
yeah->fast_count = 0;
yeah->reno_count = max(yeah->reno_count>>1, 2U);
return tp->snd_cwnd - reduction;
}
static struct tcp_congestion_ops tcp_yeah = {
.flags = TCP_CONG_RTT_STAMP,
.init = tcp_yeah_init,
.ssthresh = tcp_yeah_ssthresh,
.cong_avoid = tcp_yeah_cong_avoid,
.min_cwnd = tcp_reno_min_cwnd,
.set_state = tcp_vegas_state,
.cwnd_event = tcp_vegas_cwnd_event,
.get_info = tcp_vegas_get_info,
.pkts_acked = tcp_yeah_pkts_acked,
.owner = THIS_MODULE,
.name = "yeah",
};
static int __init tcp_yeah_register(void)
{
BUG_ON(sizeof(struct yeah) > ICSK_CA_PRIV_SIZE);
tcp_register_congestion_control(&tcp_yeah);
return 0;
}
static void __exit tcp_yeah_unregister(void)
{
tcp_unregister_congestion_control(&tcp_yeah);
}
module_init(tcp_yeah_register);
module_exit(tcp_yeah_unregister);
MODULE_AUTHOR("Angelo P. Castellani");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("YeAH TCP");
| gpl-2.0 |
TeamTwisted/hells-Core-N6 | drivers/media/platform/s5p-jpeg/jpeg-core.c | 2176 | 40189 | /* linux/drivers/media/platform/s5p-jpeg/jpeg-core.c
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* Author: Andrzej Pietrasiewicz <andrzej.p@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/clk.h>
#include <linux/err.h>
#include <linux/gfp.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <media/v4l2-mem2mem.h>
#include <media/v4l2-ioctl.h>
#include <media/videobuf2-core.h>
#include <media/videobuf2-dma-contig.h>
#include "jpeg-core.h"
#include "jpeg-hw.h"
static struct s5p_jpeg_fmt formats_enc[] = {
{
.name = "JPEG JFIF",
.fourcc = V4L2_PIX_FMT_JPEG,
.colplanes = 1,
.types = MEM2MEM_CAPTURE,
},
{
.name = "YUV 4:2:2 packed, YCbYCr",
.fourcc = V4L2_PIX_FMT_YUYV,
.depth = 16,
.colplanes = 1,
.types = MEM2MEM_OUTPUT,
},
{
.name = "RGB565",
.fourcc = V4L2_PIX_FMT_RGB565,
.depth = 16,
.colplanes = 1,
.types = MEM2MEM_OUTPUT,
},
};
#define NUM_FORMATS_ENC ARRAY_SIZE(formats_enc)
static struct s5p_jpeg_fmt formats_dec[] = {
{
.name = "YUV 4:2:0 planar, YCbCr",
.fourcc = V4L2_PIX_FMT_YUV420,
.depth = 12,
.colplanes = 3,
.h_align = 4,
.v_align = 4,
.types = MEM2MEM_CAPTURE,
},
{
.name = "YUV 4:2:2 packed, YCbYCr",
.fourcc = V4L2_PIX_FMT_YUYV,
.depth = 16,
.colplanes = 1,
.h_align = 4,
.v_align = 3,
.types = MEM2MEM_CAPTURE,
},
{
.name = "JPEG JFIF",
.fourcc = V4L2_PIX_FMT_JPEG,
.colplanes = 1,
.types = MEM2MEM_OUTPUT,
},
};
#define NUM_FORMATS_DEC ARRAY_SIZE(formats_dec)
static const unsigned char qtbl_luminance[4][64] = {
{/* level 1 - high quality */
8, 6, 6, 8, 12, 14, 16, 17,
6, 6, 6, 8, 10, 13, 12, 15,
6, 6, 7, 8, 13, 14, 18, 24,
8, 8, 8, 14, 13, 19, 24, 35,
12, 10, 13, 13, 20, 26, 34, 39,
14, 13, 14, 19, 26, 34, 39, 39,
16, 12, 18, 24, 34, 39, 39, 39,
17, 15, 24, 35, 39, 39, 39, 39
},
{/* level 2 */
12, 8, 8, 12, 17, 21, 24, 23,
8, 9, 9, 11, 15, 19, 18, 23,
8, 9, 10, 12, 19, 20, 27, 36,
12, 11, 12, 21, 20, 28, 36, 53,
17, 15, 19, 20, 30, 39, 51, 59,
21, 19, 20, 28, 39, 51, 59, 59,
24, 18, 27, 36, 51, 59, 59, 59,
23, 23, 36, 53, 59, 59, 59, 59
},
{/* level 3 */
16, 11, 11, 16, 23, 27, 31, 30,
11, 12, 12, 15, 20, 23, 23, 30,
11, 12, 13, 16, 23, 26, 35, 47,
16, 15, 16, 23, 26, 37, 47, 64,
23, 20, 23, 26, 39, 51, 64, 64,
27, 23, 26, 37, 51, 64, 64, 64,
31, 23, 35, 47, 64, 64, 64, 64,
30, 30, 47, 64, 64, 64, 64, 64
},
{/*level 4 - low quality */
20, 16, 25, 39, 50, 46, 62, 68,
16, 18, 23, 38, 38, 53, 65, 68,
25, 23, 31, 38, 53, 65, 68, 68,
39, 38, 38, 53, 65, 68, 68, 68,
50, 38, 53, 65, 68, 68, 68, 68,
46, 53, 65, 68, 68, 68, 68, 68,
62, 65, 68, 68, 68, 68, 68, 68,
68, 68, 68, 68, 68, 68, 68, 68
}
};
static const unsigned char qtbl_chrominance[4][64] = {
{/* level 1 - high quality */
9, 8, 9, 11, 14, 17, 19, 24,
8, 10, 9, 11, 14, 13, 17, 22,
9, 9, 13, 14, 13, 15, 23, 26,
11, 11, 14, 14, 15, 20, 26, 33,
14, 14, 13, 15, 20, 24, 33, 39,
17, 13, 15, 20, 24, 32, 39, 39,
19, 17, 23, 26, 33, 39, 39, 39,
24, 22, 26, 33, 39, 39, 39, 39
},
{/* level 2 */
13, 11, 13, 16, 20, 20, 29, 37,
11, 14, 14, 14, 16, 20, 26, 32,
13, 14, 15, 17, 20, 23, 35, 40,
16, 14, 17, 21, 23, 30, 40, 50,
20, 16, 20, 23, 30, 37, 50, 59,
20, 20, 23, 30, 37, 48, 59, 59,
29, 26, 35, 40, 50, 59, 59, 59,
37, 32, 40, 50, 59, 59, 59, 59
},
{/* level 3 */
17, 15, 17, 21, 20, 26, 38, 48,
15, 19, 18, 17, 20, 26, 35, 43,
17, 18, 20, 22, 26, 30, 46, 53,
21, 17, 22, 28, 30, 39, 53, 64,
20, 20, 26, 30, 39, 48, 64, 64,
26, 26, 30, 39, 48, 63, 64, 64,
38, 35, 46, 53, 64, 64, 64, 64,
48, 43, 53, 64, 64, 64, 64, 64
},
{/*level 4 - low quality */
21, 25, 32, 38, 54, 68, 68, 68,
25, 28, 24, 38, 54, 68, 68, 68,
32, 24, 32, 43, 66, 68, 68, 68,
38, 38, 43, 53, 68, 68, 68, 68,
54, 54, 66, 68, 68, 68, 68, 68,
68, 68, 68, 68, 68, 68, 68, 68,
68, 68, 68, 68, 68, 68, 68, 68,
68, 68, 68, 68, 68, 68, 68, 68
}
};
static const unsigned char hdctbl0[16] = {
0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0
};
static const unsigned char hdctblg0[12] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xa, 0xb
};
static const unsigned char hactbl0[16] = {
0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d
};
static const unsigned char hactblg0[162] = {
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa
};
static inline struct s5p_jpeg_ctx *ctrl_to_ctx(struct v4l2_ctrl *c)
{
return container_of(c->handler, struct s5p_jpeg_ctx, ctrl_handler);
}
static inline struct s5p_jpeg_ctx *fh_to_ctx(struct v4l2_fh *fh)
{
return container_of(fh, struct s5p_jpeg_ctx, fh);
}
static inline void jpeg_set_qtbl(void __iomem *regs, const unsigned char *qtbl,
unsigned long tab, int len)
{
int i;
for (i = 0; i < len; i++)
writel((unsigned int)qtbl[i], regs + tab + (i * 0x04));
}
static inline void jpeg_set_qtbl_lum(void __iomem *regs, int quality)
{
/* this driver fills quantisation table 0 with data for luma */
jpeg_set_qtbl(regs, qtbl_luminance[quality], S5P_JPG_QTBL_CONTENT(0),
ARRAY_SIZE(qtbl_luminance[quality]));
}
static inline void jpeg_set_qtbl_chr(void __iomem *regs, int quality)
{
/* this driver fills quantisation table 1 with data for chroma */
jpeg_set_qtbl(regs, qtbl_chrominance[quality], S5P_JPG_QTBL_CONTENT(1),
ARRAY_SIZE(qtbl_chrominance[quality]));
}
static inline void jpeg_set_htbl(void __iomem *regs, const unsigned char *htbl,
unsigned long tab, int len)
{
int i;
for (i = 0; i < len; i++)
writel((unsigned int)htbl[i], regs + tab + (i * 0x04));
}
static inline void jpeg_set_hdctbl(void __iomem *regs)
{
/* this driver fills table 0 for this component */
jpeg_set_htbl(regs, hdctbl0, S5P_JPG_HDCTBL(0), ARRAY_SIZE(hdctbl0));
}
static inline void jpeg_set_hdctblg(void __iomem *regs)
{
/* this driver fills table 0 for this component */
jpeg_set_htbl(regs, hdctblg0, S5P_JPG_HDCTBLG(0), ARRAY_SIZE(hdctblg0));
}
static inline void jpeg_set_hactbl(void __iomem *regs)
{
/* this driver fills table 0 for this component */
jpeg_set_htbl(regs, hactbl0, S5P_JPG_HACTBL(0), ARRAY_SIZE(hactbl0));
}
static inline void jpeg_set_hactblg(void __iomem *regs)
{
/* this driver fills table 0 for this component */
jpeg_set_htbl(regs, hactblg0, S5P_JPG_HACTBLG(0), ARRAY_SIZE(hactblg0));
}
/*
* ============================================================================
* Device file operations
* ============================================================================
*/
static int queue_init(void *priv, struct vb2_queue *src_vq,
struct vb2_queue *dst_vq);
static struct s5p_jpeg_fmt *s5p_jpeg_find_format(unsigned int mode,
__u32 pixelformat);
static int s5p_jpeg_controls_create(struct s5p_jpeg_ctx *ctx);
static int s5p_jpeg_open(struct file *file)
{
struct s5p_jpeg *jpeg = video_drvdata(file);
struct video_device *vfd = video_devdata(file);
struct s5p_jpeg_ctx *ctx;
struct s5p_jpeg_fmt *out_fmt;
int ret = 0;
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
if (mutex_lock_interruptible(&jpeg->lock)) {
ret = -ERESTARTSYS;
goto free;
}
v4l2_fh_init(&ctx->fh, vfd);
/* Use separate control handler per file handle */
ctx->fh.ctrl_handler = &ctx->ctrl_handler;
file->private_data = &ctx->fh;
v4l2_fh_add(&ctx->fh);
ctx->jpeg = jpeg;
if (vfd == jpeg->vfd_encoder) {
ctx->mode = S5P_JPEG_ENCODE;
out_fmt = s5p_jpeg_find_format(ctx->mode, V4L2_PIX_FMT_RGB565);
} else {
ctx->mode = S5P_JPEG_DECODE;
out_fmt = s5p_jpeg_find_format(ctx->mode, V4L2_PIX_FMT_JPEG);
}
ret = s5p_jpeg_controls_create(ctx);
if (ret < 0)
goto error;
ctx->m2m_ctx = v4l2_m2m_ctx_init(jpeg->m2m_dev, ctx, queue_init);
if (IS_ERR(ctx->m2m_ctx)) {
ret = PTR_ERR(ctx->m2m_ctx);
goto error;
}
ctx->out_q.fmt = out_fmt;
ctx->cap_q.fmt = s5p_jpeg_find_format(ctx->mode, V4L2_PIX_FMT_YUYV);
mutex_unlock(&jpeg->lock);
return 0;
error:
v4l2_fh_del(&ctx->fh);
v4l2_fh_exit(&ctx->fh);
mutex_unlock(&jpeg->lock);
free:
kfree(ctx);
return ret;
}
static int s5p_jpeg_release(struct file *file)
{
struct s5p_jpeg *jpeg = video_drvdata(file);
struct s5p_jpeg_ctx *ctx = fh_to_ctx(file->private_data);
mutex_lock(&jpeg->lock);
v4l2_m2m_ctx_release(ctx->m2m_ctx);
mutex_unlock(&jpeg->lock);
v4l2_ctrl_handler_free(&ctx->ctrl_handler);
v4l2_fh_del(&ctx->fh);
v4l2_fh_exit(&ctx->fh);
kfree(ctx);
return 0;
}
static unsigned int s5p_jpeg_poll(struct file *file,
struct poll_table_struct *wait)
{
struct s5p_jpeg *jpeg = video_drvdata(file);
struct s5p_jpeg_ctx *ctx = fh_to_ctx(file->private_data);
unsigned int res;
mutex_lock(&jpeg->lock);
res = v4l2_m2m_poll(file, ctx->m2m_ctx, wait);
mutex_unlock(&jpeg->lock);
return res;
}
static int s5p_jpeg_mmap(struct file *file, struct vm_area_struct *vma)
{
struct s5p_jpeg *jpeg = video_drvdata(file);
struct s5p_jpeg_ctx *ctx = fh_to_ctx(file->private_data);
int ret;
if (mutex_lock_interruptible(&jpeg->lock))
return -ERESTARTSYS;
ret = v4l2_m2m_mmap(file, ctx->m2m_ctx, vma);
mutex_unlock(&jpeg->lock);
return ret;
}
static const struct v4l2_file_operations s5p_jpeg_fops = {
.owner = THIS_MODULE,
.open = s5p_jpeg_open,
.release = s5p_jpeg_release,
.poll = s5p_jpeg_poll,
.unlocked_ioctl = video_ioctl2,
.mmap = s5p_jpeg_mmap,
};
/*
* ============================================================================
* video ioctl operations
* ============================================================================
*/
static int get_byte(struct s5p_jpeg_buffer *buf)
{
if (buf->curr >= buf->size)
return -1;
return ((unsigned char *)buf->data)[buf->curr++];
}
static int get_word_be(struct s5p_jpeg_buffer *buf, unsigned int *word)
{
unsigned int temp;
int byte;
byte = get_byte(buf);
if (byte == -1)
return -1;
temp = byte << 8;
byte = get_byte(buf);
if (byte == -1)
return -1;
*word = (unsigned int)byte | temp;
return 0;
}
static void skip(struct s5p_jpeg_buffer *buf, long len)
{
if (len <= 0)
return;
while (len--)
get_byte(buf);
}
static bool s5p_jpeg_parse_hdr(struct s5p_jpeg_q_data *result,
unsigned long buffer, unsigned long size)
{
int c, components, notfound;
unsigned int height, width, word;
long length;
struct s5p_jpeg_buffer jpeg_buffer;
jpeg_buffer.size = size;
jpeg_buffer.data = buffer;
jpeg_buffer.curr = 0;
notfound = 1;
while (notfound) {
c = get_byte(&jpeg_buffer);
if (c == -1)
break;
if (c != 0xff)
continue;
do
c = get_byte(&jpeg_buffer);
while (c == 0xff);
if (c == -1)
break;
if (c == 0)
continue;
length = 0;
switch (c) {
/* SOF0: baseline JPEG */
case SOF0:
if (get_word_be(&jpeg_buffer, &word))
break;
if (get_byte(&jpeg_buffer) == -1)
break;
if (get_word_be(&jpeg_buffer, &height))
break;
if (get_word_be(&jpeg_buffer, &width))
break;
components = get_byte(&jpeg_buffer);
if (components == -1)
break;
notfound = 0;
skip(&jpeg_buffer, components * 3);
break;
/* skip payload-less markers */
case RST ... RST + 7:
case SOI:
case EOI:
case TEM:
break;
/* skip uninteresting payload markers */
default:
if (get_word_be(&jpeg_buffer, &word))
break;
length = (long)word - 2;
skip(&jpeg_buffer, length);
break;
}
}
result->w = width;
result->h = height;
result->size = components;
return !notfound;
}
static int s5p_jpeg_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
if (ctx->mode == S5P_JPEG_ENCODE) {
strlcpy(cap->driver, S5P_JPEG_M2M_NAME " encoder",
sizeof(cap->driver));
strlcpy(cap->card, S5P_JPEG_M2M_NAME " encoder",
sizeof(cap->card));
} else {
strlcpy(cap->driver, S5P_JPEG_M2M_NAME " decoder",
sizeof(cap->driver));
strlcpy(cap->card, S5P_JPEG_M2M_NAME " decoder",
sizeof(cap->card));
}
cap->bus_info[0] = 0;
/*
* This is only a mem-to-mem video device. The capture and output
* device capability flags are left only for backward compatibility
* and are scheduled for removal.
*/
cap->capabilities = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_M2M |
V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_OUTPUT;
return 0;
}
static int enum_fmt(struct s5p_jpeg_fmt *formats, int n,
struct v4l2_fmtdesc *f, u32 type)
{
int i, num = 0;
for (i = 0; i < n; ++i) {
if (formats[i].types & type) {
/* index-th format of type type found ? */
if (num == f->index)
break;
/* Correct type but haven't reached our index yet,
* just increment per-type index */
++num;
}
}
/* Format not found */
if (i >= n)
return -EINVAL;
strlcpy(f->description, formats[i].name, sizeof(f->description));
f->pixelformat = formats[i].fourcc;
return 0;
}
static int s5p_jpeg_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
if (ctx->mode == S5P_JPEG_ENCODE)
return enum_fmt(formats_enc, NUM_FORMATS_ENC, f,
MEM2MEM_CAPTURE);
return enum_fmt(formats_dec, NUM_FORMATS_DEC, f, MEM2MEM_CAPTURE);
}
static int s5p_jpeg_enum_fmt_vid_out(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
if (ctx->mode == S5P_JPEG_ENCODE)
return enum_fmt(formats_enc, NUM_FORMATS_ENC, f,
MEM2MEM_OUTPUT);
return enum_fmt(formats_dec, NUM_FORMATS_DEC, f, MEM2MEM_OUTPUT);
}
static struct s5p_jpeg_q_data *get_q_data(struct s5p_jpeg_ctx *ctx,
enum v4l2_buf_type type)
{
if (type == V4L2_BUF_TYPE_VIDEO_OUTPUT)
return &ctx->out_q;
if (type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
return &ctx->cap_q;
return NULL;
}
static int s5p_jpeg_g_fmt(struct file *file, void *priv, struct v4l2_format *f)
{
struct vb2_queue *vq;
struct s5p_jpeg_q_data *q_data = NULL;
struct v4l2_pix_format *pix = &f->fmt.pix;
struct s5p_jpeg_ctx *ct = fh_to_ctx(priv);
vq = v4l2_m2m_get_vq(ct->m2m_ctx, f->type);
if (!vq)
return -EINVAL;
if (f->type == V4L2_BUF_TYPE_VIDEO_CAPTURE &&
ct->mode == S5P_JPEG_DECODE && !ct->hdr_parsed)
return -EINVAL;
q_data = get_q_data(ct, f->type);
BUG_ON(q_data == NULL);
pix->width = q_data->w;
pix->height = q_data->h;
pix->field = V4L2_FIELD_NONE;
pix->pixelformat = q_data->fmt->fourcc;
pix->bytesperline = 0;
if (q_data->fmt->fourcc != V4L2_PIX_FMT_JPEG) {
u32 bpl = q_data->w;
if (q_data->fmt->colplanes == 1)
bpl = (bpl * q_data->fmt->depth) >> 3;
pix->bytesperline = bpl;
}
pix->sizeimage = q_data->size;
return 0;
}
static struct s5p_jpeg_fmt *s5p_jpeg_find_format(unsigned int mode,
u32 pixelformat)
{
unsigned int k;
struct s5p_jpeg_fmt *formats;
int n;
if (mode == S5P_JPEG_ENCODE) {
formats = formats_enc;
n = NUM_FORMATS_ENC;
} else {
formats = formats_dec;
n = NUM_FORMATS_DEC;
}
for (k = 0; k < n; k++) {
struct s5p_jpeg_fmt *fmt = &formats[k];
if (fmt->fourcc == pixelformat)
return fmt;
}
return NULL;
}
static void jpeg_bound_align_image(u32 *w, unsigned int wmin, unsigned int wmax,
unsigned int walign,
u32 *h, unsigned int hmin, unsigned int hmax,
unsigned int halign)
{
int width, height, w_step, h_step;
width = *w;
height = *h;
w_step = 1 << walign;
h_step = 1 << halign;
v4l_bound_align_image(w, wmin, wmax, walign, h, hmin, hmax, halign, 0);
if (*w < width && (*w + w_step) < wmax)
*w += w_step;
if (*h < height && (*h + h_step) < hmax)
*h += h_step;
}
static int vidioc_try_fmt(struct v4l2_format *f, struct s5p_jpeg_fmt *fmt,
struct s5p_jpeg_ctx *ctx, int q_type)
{
struct v4l2_pix_format *pix = &f->fmt.pix;
if (pix->field == V4L2_FIELD_ANY)
pix->field = V4L2_FIELD_NONE;
else if (pix->field != V4L2_FIELD_NONE)
return -EINVAL;
/* V4L2 specification suggests the driver corrects the format struct
* if any of the dimensions is unsupported */
if (q_type == MEM2MEM_OUTPUT)
jpeg_bound_align_image(&pix->width, S5P_JPEG_MIN_WIDTH,
S5P_JPEG_MAX_WIDTH, 0,
&pix->height, S5P_JPEG_MIN_HEIGHT,
S5P_JPEG_MAX_HEIGHT, 0);
else
jpeg_bound_align_image(&pix->width, S5P_JPEG_MIN_WIDTH,
S5P_JPEG_MAX_WIDTH, fmt->h_align,
&pix->height, S5P_JPEG_MIN_HEIGHT,
S5P_JPEG_MAX_HEIGHT, fmt->v_align);
if (fmt->fourcc == V4L2_PIX_FMT_JPEG) {
if (pix->sizeimage <= 0)
pix->sizeimage = PAGE_SIZE;
pix->bytesperline = 0;
} else {
u32 bpl = pix->bytesperline;
if (fmt->colplanes > 1 && bpl < pix->width)
bpl = pix->width; /* planar */
if (fmt->colplanes == 1 && /* packed */
(bpl << 3) * fmt->depth < pix->width)
bpl = (pix->width * fmt->depth) >> 3;
pix->bytesperline = bpl;
pix->sizeimage = (pix->width * pix->height * fmt->depth) >> 3;
}
return 0;
}
static int s5p_jpeg_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
struct s5p_jpeg_fmt *fmt;
fmt = s5p_jpeg_find_format(ctx->mode, f->fmt.pix.pixelformat);
if (!fmt || !(fmt->types & MEM2MEM_CAPTURE)) {
v4l2_err(&ctx->jpeg->v4l2_dev,
"Fourcc format (0x%08x) invalid.\n",
f->fmt.pix.pixelformat);
return -EINVAL;
}
return vidioc_try_fmt(f, fmt, ctx, MEM2MEM_CAPTURE);
}
static int s5p_jpeg_try_fmt_vid_out(struct file *file, void *priv,
struct v4l2_format *f)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
struct s5p_jpeg_fmt *fmt;
fmt = s5p_jpeg_find_format(ctx->mode, f->fmt.pix.pixelformat);
if (!fmt || !(fmt->types & MEM2MEM_OUTPUT)) {
v4l2_err(&ctx->jpeg->v4l2_dev,
"Fourcc format (0x%08x) invalid.\n",
f->fmt.pix.pixelformat);
return -EINVAL;
}
return vidioc_try_fmt(f, fmt, ctx, MEM2MEM_OUTPUT);
}
static int s5p_jpeg_s_fmt(struct s5p_jpeg_ctx *ct, struct v4l2_format *f)
{
struct vb2_queue *vq;
struct s5p_jpeg_q_data *q_data = NULL;
struct v4l2_pix_format *pix = &f->fmt.pix;
vq = v4l2_m2m_get_vq(ct->m2m_ctx, f->type);
if (!vq)
return -EINVAL;
q_data = get_q_data(ct, f->type);
BUG_ON(q_data == NULL);
if (vb2_is_busy(vq)) {
v4l2_err(&ct->jpeg->v4l2_dev, "%s queue busy\n", __func__);
return -EBUSY;
}
q_data->fmt = s5p_jpeg_find_format(ct->mode, pix->pixelformat);
q_data->w = pix->width;
q_data->h = pix->height;
if (q_data->fmt->fourcc != V4L2_PIX_FMT_JPEG)
q_data->size = q_data->w * q_data->h * q_data->fmt->depth >> 3;
else
q_data->size = pix->sizeimage;
return 0;
}
static int s5p_jpeg_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
int ret;
ret = s5p_jpeg_try_fmt_vid_cap(file, priv, f);
if (ret)
return ret;
return s5p_jpeg_s_fmt(fh_to_ctx(priv), f);
}
static int s5p_jpeg_s_fmt_vid_out(struct file *file, void *priv,
struct v4l2_format *f)
{
int ret;
ret = s5p_jpeg_try_fmt_vid_out(file, priv, f);
if (ret)
return ret;
return s5p_jpeg_s_fmt(fh_to_ctx(priv), f);
}
static int s5p_jpeg_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *reqbufs)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
return v4l2_m2m_reqbufs(file, ctx->m2m_ctx, reqbufs);
}
static int s5p_jpeg_querybuf(struct file *file, void *priv,
struct v4l2_buffer *buf)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
return v4l2_m2m_querybuf(file, ctx->m2m_ctx, buf);
}
static int s5p_jpeg_qbuf(struct file *file, void *priv, struct v4l2_buffer *buf)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
return v4l2_m2m_qbuf(file, ctx->m2m_ctx, buf);
}
static int s5p_jpeg_dqbuf(struct file *file, void *priv,
struct v4l2_buffer *buf)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
return v4l2_m2m_dqbuf(file, ctx->m2m_ctx, buf);
}
static int s5p_jpeg_streamon(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
return v4l2_m2m_streamon(file, ctx->m2m_ctx, type);
}
static int s5p_jpeg_streamoff(struct file *file, void *priv,
enum v4l2_buf_type type)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
return v4l2_m2m_streamoff(file, ctx->m2m_ctx, type);
}
static int s5p_jpeg_g_selection(struct file *file, void *priv,
struct v4l2_selection *s)
{
struct s5p_jpeg_ctx *ctx = fh_to_ctx(priv);
if (s->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
/* For JPEG blob active == default == bounds */
switch (s->target) {
case V4L2_SEL_TGT_CROP:
case V4L2_SEL_TGT_CROP_BOUNDS:
case V4L2_SEL_TGT_CROP_DEFAULT:
case V4L2_SEL_TGT_COMPOSE:
case V4L2_SEL_TGT_COMPOSE_DEFAULT:
s->r.width = ctx->out_q.w;
s->r.height = ctx->out_q.h;
break;
case V4L2_SEL_TGT_COMPOSE_BOUNDS:
case V4L2_SEL_TGT_COMPOSE_PADDED:
s->r.width = ctx->cap_q.w;
s->r.height = ctx->cap_q.h;
break;
default:
return -EINVAL;
}
s->r.left = 0;
s->r.top = 0;
return 0;
}
/*
* V4L2 controls
*/
static int s5p_jpeg_g_volatile_ctrl(struct v4l2_ctrl *ctrl)
{
struct s5p_jpeg_ctx *ctx = ctrl_to_ctx(ctrl);
struct s5p_jpeg *jpeg = ctx->jpeg;
unsigned long flags;
switch (ctrl->id) {
case V4L2_CID_JPEG_CHROMA_SUBSAMPLING:
spin_lock_irqsave(&jpeg->slock, flags);
WARN_ON(ctx->subsampling > S5P_SUBSAMPLING_MODE_GRAY);
if (ctx->subsampling > 2)
ctrl->val = V4L2_JPEG_CHROMA_SUBSAMPLING_GRAY;
else
ctrl->val = ctx->subsampling;
spin_unlock_irqrestore(&jpeg->slock, flags);
break;
}
return 0;
}
static int s5p_jpeg_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct s5p_jpeg_ctx *ctx = ctrl_to_ctx(ctrl);
unsigned long flags;
spin_lock_irqsave(&ctx->jpeg->slock, flags);
switch (ctrl->id) {
case V4L2_CID_JPEG_COMPRESSION_QUALITY:
ctx->compr_quality = S5P_JPEG_COMPR_QUAL_WORST - ctrl->val;
break;
case V4L2_CID_JPEG_RESTART_INTERVAL:
ctx->restart_interval = ctrl->val;
break;
case V4L2_CID_JPEG_CHROMA_SUBSAMPLING:
ctx->subsampling = ctrl->val;
break;
}
spin_unlock_irqrestore(&ctx->jpeg->slock, flags);
return 0;
}
static const struct v4l2_ctrl_ops s5p_jpeg_ctrl_ops = {
.g_volatile_ctrl = s5p_jpeg_g_volatile_ctrl,
.s_ctrl = s5p_jpeg_s_ctrl,
};
static int s5p_jpeg_controls_create(struct s5p_jpeg_ctx *ctx)
{
unsigned int mask = ~0x27; /* 444, 422, 420, GRAY */
struct v4l2_ctrl *ctrl;
v4l2_ctrl_handler_init(&ctx->ctrl_handler, 3);
if (ctx->mode == S5P_JPEG_ENCODE) {
v4l2_ctrl_new_std(&ctx->ctrl_handler, &s5p_jpeg_ctrl_ops,
V4L2_CID_JPEG_COMPRESSION_QUALITY,
0, 3, 1, 3);
v4l2_ctrl_new_std(&ctx->ctrl_handler, &s5p_jpeg_ctrl_ops,
V4L2_CID_JPEG_RESTART_INTERVAL,
0, 3, 0xffff, 0);
mask = ~0x06; /* 422, 420 */
}
ctrl = v4l2_ctrl_new_std_menu(&ctx->ctrl_handler, &s5p_jpeg_ctrl_ops,
V4L2_CID_JPEG_CHROMA_SUBSAMPLING,
V4L2_JPEG_CHROMA_SUBSAMPLING_GRAY, mask,
V4L2_JPEG_CHROMA_SUBSAMPLING_422);
if (ctx->ctrl_handler.error)
return ctx->ctrl_handler.error;
if (ctx->mode == S5P_JPEG_DECODE)
ctrl->flags |= V4L2_CTRL_FLAG_VOLATILE |
V4L2_CTRL_FLAG_READ_ONLY;
return 0;
}
static const struct v4l2_ioctl_ops s5p_jpeg_ioctl_ops = {
.vidioc_querycap = s5p_jpeg_querycap,
.vidioc_enum_fmt_vid_cap = s5p_jpeg_enum_fmt_vid_cap,
.vidioc_enum_fmt_vid_out = s5p_jpeg_enum_fmt_vid_out,
.vidioc_g_fmt_vid_cap = s5p_jpeg_g_fmt,
.vidioc_g_fmt_vid_out = s5p_jpeg_g_fmt,
.vidioc_try_fmt_vid_cap = s5p_jpeg_try_fmt_vid_cap,
.vidioc_try_fmt_vid_out = s5p_jpeg_try_fmt_vid_out,
.vidioc_s_fmt_vid_cap = s5p_jpeg_s_fmt_vid_cap,
.vidioc_s_fmt_vid_out = s5p_jpeg_s_fmt_vid_out,
.vidioc_reqbufs = s5p_jpeg_reqbufs,
.vidioc_querybuf = s5p_jpeg_querybuf,
.vidioc_qbuf = s5p_jpeg_qbuf,
.vidioc_dqbuf = s5p_jpeg_dqbuf,
.vidioc_streamon = s5p_jpeg_streamon,
.vidioc_streamoff = s5p_jpeg_streamoff,
.vidioc_g_selection = s5p_jpeg_g_selection,
};
/*
* ============================================================================
* mem2mem callbacks
* ============================================================================
*/
static void s5p_jpeg_device_run(void *priv)
{
struct s5p_jpeg_ctx *ctx = priv;
struct s5p_jpeg *jpeg = ctx->jpeg;
struct vb2_buffer *src_buf, *dst_buf;
unsigned long src_addr, dst_addr;
src_buf = v4l2_m2m_next_src_buf(ctx->m2m_ctx);
dst_buf = v4l2_m2m_next_dst_buf(ctx->m2m_ctx);
src_addr = vb2_dma_contig_plane_dma_addr(src_buf, 0);
dst_addr = vb2_dma_contig_plane_dma_addr(dst_buf, 0);
jpeg_reset(jpeg->regs);
jpeg_poweron(jpeg->regs);
jpeg_proc_mode(jpeg->regs, ctx->mode);
if (ctx->mode == S5P_JPEG_ENCODE) {
if (ctx->out_q.fmt->fourcc == V4L2_PIX_FMT_RGB565)
jpeg_input_raw_mode(jpeg->regs, S5P_JPEG_RAW_IN_565);
else
jpeg_input_raw_mode(jpeg->regs, S5P_JPEG_RAW_IN_422);
jpeg_subsampling_mode(jpeg->regs, ctx->subsampling);
jpeg_dri(jpeg->regs, ctx->restart_interval);
jpeg_x(jpeg->regs, ctx->out_q.w);
jpeg_y(jpeg->regs, ctx->out_q.h);
jpeg_imgadr(jpeg->regs, src_addr);
jpeg_jpgadr(jpeg->regs, dst_addr);
/* ultimately comes from sizeimage from userspace */
jpeg_enc_stream_int(jpeg->regs, ctx->cap_q.size);
/* JPEG RGB to YCbCr conversion matrix */
jpeg_coef(jpeg->regs, 1, 1, S5P_JPEG_COEF11);
jpeg_coef(jpeg->regs, 1, 2, S5P_JPEG_COEF12);
jpeg_coef(jpeg->regs, 1, 3, S5P_JPEG_COEF13);
jpeg_coef(jpeg->regs, 2, 1, S5P_JPEG_COEF21);
jpeg_coef(jpeg->regs, 2, 2, S5P_JPEG_COEF22);
jpeg_coef(jpeg->regs, 2, 3, S5P_JPEG_COEF23);
jpeg_coef(jpeg->regs, 3, 1, S5P_JPEG_COEF31);
jpeg_coef(jpeg->regs, 3, 2, S5P_JPEG_COEF32);
jpeg_coef(jpeg->regs, 3, 3, S5P_JPEG_COEF33);
/*
* JPEG IP allows storing 4 quantization tables
* We fill table 0 for luma and table 1 for chroma
*/
jpeg_set_qtbl_lum(jpeg->regs, ctx->compr_quality);
jpeg_set_qtbl_chr(jpeg->regs, ctx->compr_quality);
/* use table 0 for Y */
jpeg_qtbl(jpeg->regs, 1, 0);
/* use table 1 for Cb and Cr*/
jpeg_qtbl(jpeg->regs, 2, 1);
jpeg_qtbl(jpeg->regs, 3, 1);
/* Y, Cb, Cr use Huffman table 0 */
jpeg_htbl_ac(jpeg->regs, 1);
jpeg_htbl_dc(jpeg->regs, 1);
jpeg_htbl_ac(jpeg->regs, 2);
jpeg_htbl_dc(jpeg->regs, 2);
jpeg_htbl_ac(jpeg->regs, 3);
jpeg_htbl_dc(jpeg->regs, 3);
} else { /* S5P_JPEG_DECODE */
jpeg_rst_int_enable(jpeg->regs, true);
jpeg_data_num_int_enable(jpeg->regs, true);
jpeg_final_mcu_num_int_enable(jpeg->regs, true);
if (ctx->cap_q.fmt->fourcc == V4L2_PIX_FMT_YUYV)
jpeg_outform_raw(jpeg->regs, S5P_JPEG_RAW_OUT_422);
else
jpeg_outform_raw(jpeg->regs, S5P_JPEG_RAW_OUT_420);
jpeg_jpgadr(jpeg->regs, src_addr);
jpeg_imgadr(jpeg->regs, dst_addr);
}
jpeg_start(jpeg->regs);
}
static int s5p_jpeg_job_ready(void *priv)
{
struct s5p_jpeg_ctx *ctx = priv;
if (ctx->mode == S5P_JPEG_DECODE)
return ctx->hdr_parsed;
return 1;
}
static void s5p_jpeg_job_abort(void *priv)
{
}
static struct v4l2_m2m_ops s5p_jpeg_m2m_ops = {
.device_run = s5p_jpeg_device_run,
.job_ready = s5p_jpeg_job_ready,
.job_abort = s5p_jpeg_job_abort,
};
/*
* ============================================================================
* Queue operations
* ============================================================================
*/
static int s5p_jpeg_queue_setup(struct vb2_queue *vq,
const struct v4l2_format *fmt,
unsigned int *nbuffers, unsigned int *nplanes,
unsigned int sizes[], void *alloc_ctxs[])
{
struct s5p_jpeg_ctx *ctx = vb2_get_drv_priv(vq);
struct s5p_jpeg_q_data *q_data = NULL;
unsigned int size, count = *nbuffers;
q_data = get_q_data(ctx, vq->type);
BUG_ON(q_data == NULL);
size = q_data->size;
/*
* header is parsed during decoding and parsed information stored
* in the context so we do not allow another buffer to overwrite it
*/
if (ctx->mode == S5P_JPEG_DECODE)
count = 1;
*nbuffers = count;
*nplanes = 1;
sizes[0] = size;
alloc_ctxs[0] = ctx->jpeg->alloc_ctx;
return 0;
}
static int s5p_jpeg_buf_prepare(struct vb2_buffer *vb)
{
struct s5p_jpeg_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
struct s5p_jpeg_q_data *q_data = NULL;
q_data = get_q_data(ctx, vb->vb2_queue->type);
BUG_ON(q_data == NULL);
if (vb2_plane_size(vb, 0) < q_data->size) {
pr_err("%s data will not fit into plane (%lu < %lu)\n",
__func__, vb2_plane_size(vb, 0),
(long)q_data->size);
return -EINVAL;
}
vb2_set_plane_payload(vb, 0, q_data->size);
return 0;
}
static void s5p_jpeg_buf_queue(struct vb2_buffer *vb)
{
struct s5p_jpeg_ctx *ctx = vb2_get_drv_priv(vb->vb2_queue);
if (ctx->mode == S5P_JPEG_DECODE &&
vb->vb2_queue->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) {
struct s5p_jpeg_q_data tmp, *q_data;
ctx->hdr_parsed = s5p_jpeg_parse_hdr(&tmp,
(unsigned long)vb2_plane_vaddr(vb, 0),
min((unsigned long)ctx->out_q.size,
vb2_get_plane_payload(vb, 0)));
if (!ctx->hdr_parsed) {
vb2_buffer_done(vb, VB2_BUF_STATE_ERROR);
return;
}
q_data = &ctx->out_q;
q_data->w = tmp.w;
q_data->h = tmp.h;
q_data = &ctx->cap_q;
q_data->w = tmp.w;
q_data->h = tmp.h;
jpeg_bound_align_image(&q_data->w, S5P_JPEG_MIN_WIDTH,
S5P_JPEG_MAX_WIDTH, q_data->fmt->h_align,
&q_data->h, S5P_JPEG_MIN_HEIGHT,
S5P_JPEG_MAX_HEIGHT, q_data->fmt->v_align
);
q_data->size = q_data->w * q_data->h * q_data->fmt->depth >> 3;
}
if (ctx->m2m_ctx)
v4l2_m2m_buf_queue(ctx->m2m_ctx, vb);
}
static void s5p_jpeg_wait_prepare(struct vb2_queue *vq)
{
struct s5p_jpeg_ctx *ctx = vb2_get_drv_priv(vq);
mutex_unlock(&ctx->jpeg->lock);
}
static void s5p_jpeg_wait_finish(struct vb2_queue *vq)
{
struct s5p_jpeg_ctx *ctx = vb2_get_drv_priv(vq);
mutex_lock(&ctx->jpeg->lock);
}
static int s5p_jpeg_start_streaming(struct vb2_queue *q, unsigned int count)
{
struct s5p_jpeg_ctx *ctx = vb2_get_drv_priv(q);
int ret;
ret = pm_runtime_get_sync(ctx->jpeg->dev);
return ret > 0 ? 0 : ret;
}
static int s5p_jpeg_stop_streaming(struct vb2_queue *q)
{
struct s5p_jpeg_ctx *ctx = vb2_get_drv_priv(q);
pm_runtime_put(ctx->jpeg->dev);
return 0;
}
static struct vb2_ops s5p_jpeg_qops = {
.queue_setup = s5p_jpeg_queue_setup,
.buf_prepare = s5p_jpeg_buf_prepare,
.buf_queue = s5p_jpeg_buf_queue,
.wait_prepare = s5p_jpeg_wait_prepare,
.wait_finish = s5p_jpeg_wait_finish,
.start_streaming = s5p_jpeg_start_streaming,
.stop_streaming = s5p_jpeg_stop_streaming,
};
static int queue_init(void *priv, struct vb2_queue *src_vq,
struct vb2_queue *dst_vq)
{
struct s5p_jpeg_ctx *ctx = priv;
int ret;
src_vq->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
src_vq->io_modes = VB2_MMAP | VB2_USERPTR;
src_vq->drv_priv = ctx;
src_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
src_vq->ops = &s5p_jpeg_qops;
src_vq->mem_ops = &vb2_dma_contig_memops;
src_vq->timestamp_type = V4L2_BUF_FLAG_TIMESTAMP_COPY;
ret = vb2_queue_init(src_vq);
if (ret)
return ret;
dst_vq->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
dst_vq->io_modes = VB2_MMAP | VB2_USERPTR;
dst_vq->drv_priv = ctx;
dst_vq->buf_struct_size = sizeof(struct v4l2_m2m_buffer);
dst_vq->ops = &s5p_jpeg_qops;
dst_vq->mem_ops = &vb2_dma_contig_memops;
dst_vq->timestamp_type = V4L2_BUF_FLAG_TIMESTAMP_COPY;
return vb2_queue_init(dst_vq);
}
/*
* ============================================================================
* ISR
* ============================================================================
*/
static irqreturn_t s5p_jpeg_irq(int irq, void *dev_id)
{
struct s5p_jpeg *jpeg = dev_id;
struct s5p_jpeg_ctx *curr_ctx;
struct vb2_buffer *src_buf, *dst_buf;
unsigned long payload_size = 0;
enum vb2_buffer_state state = VB2_BUF_STATE_DONE;
bool enc_jpeg_too_large = false;
bool timer_elapsed = false;
bool op_completed = false;
spin_lock(&jpeg->slock);
curr_ctx = v4l2_m2m_get_curr_priv(jpeg->m2m_dev);
src_buf = v4l2_m2m_src_buf_remove(curr_ctx->m2m_ctx);
dst_buf = v4l2_m2m_dst_buf_remove(curr_ctx->m2m_ctx);
if (curr_ctx->mode == S5P_JPEG_ENCODE)
enc_jpeg_too_large = jpeg_enc_stream_stat(jpeg->regs);
timer_elapsed = jpeg_timer_stat(jpeg->regs);
op_completed = jpeg_result_stat_ok(jpeg->regs);
if (curr_ctx->mode == S5P_JPEG_DECODE)
op_completed = op_completed && jpeg_stream_stat_ok(jpeg->regs);
if (enc_jpeg_too_large) {
state = VB2_BUF_STATE_ERROR;
jpeg_clear_enc_stream_stat(jpeg->regs);
} else if (timer_elapsed) {
state = VB2_BUF_STATE_ERROR;
jpeg_clear_timer_stat(jpeg->regs);
} else if (!op_completed) {
state = VB2_BUF_STATE_ERROR;
} else {
payload_size = jpeg_compressed_size(jpeg->regs);
}
dst_buf->v4l2_buf.timecode = src_buf->v4l2_buf.timecode;
dst_buf->v4l2_buf.timestamp = src_buf->v4l2_buf.timestamp;
v4l2_m2m_buf_done(src_buf, state);
if (curr_ctx->mode == S5P_JPEG_ENCODE)
vb2_set_plane_payload(dst_buf, 0, payload_size);
v4l2_m2m_buf_done(dst_buf, state);
v4l2_m2m_job_finish(jpeg->m2m_dev, curr_ctx->m2m_ctx);
curr_ctx->subsampling = jpeg_get_subsampling_mode(jpeg->regs);
spin_unlock(&jpeg->slock);
jpeg_clear_int(jpeg->regs);
return IRQ_HANDLED;
}
/*
* ============================================================================
* Driver basic infrastructure
* ============================================================================
*/
static int s5p_jpeg_probe(struct platform_device *pdev)
{
struct s5p_jpeg *jpeg;
struct resource *res;
int ret;
/* JPEG IP abstraction struct */
jpeg = devm_kzalloc(&pdev->dev, sizeof(struct s5p_jpeg), GFP_KERNEL);
if (!jpeg)
return -ENOMEM;
mutex_init(&jpeg->lock);
spin_lock_init(&jpeg->slock);
jpeg->dev = &pdev->dev;
/* memory-mapped registers */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
jpeg->regs = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(jpeg->regs))
return PTR_ERR(jpeg->regs);
/* interrupt service routine registration */
jpeg->irq = ret = platform_get_irq(pdev, 0);
if (ret < 0) {
dev_err(&pdev->dev, "cannot find IRQ\n");
return ret;
}
ret = devm_request_irq(&pdev->dev, jpeg->irq, s5p_jpeg_irq, 0,
dev_name(&pdev->dev), jpeg);
if (ret) {
dev_err(&pdev->dev, "cannot claim IRQ %d\n", jpeg->irq);
return ret;
}
/* clocks */
jpeg->clk = clk_get(&pdev->dev, "jpeg");
if (IS_ERR(jpeg->clk)) {
dev_err(&pdev->dev, "cannot get clock\n");
ret = PTR_ERR(jpeg->clk);
return ret;
}
dev_dbg(&pdev->dev, "clock source %p\n", jpeg->clk);
clk_prepare_enable(jpeg->clk);
/* v4l2 device */
ret = v4l2_device_register(&pdev->dev, &jpeg->v4l2_dev);
if (ret) {
dev_err(&pdev->dev, "Failed to register v4l2 device\n");
goto clk_get_rollback;
}
/* mem2mem device */
jpeg->m2m_dev = v4l2_m2m_init(&s5p_jpeg_m2m_ops);
if (IS_ERR(jpeg->m2m_dev)) {
v4l2_err(&jpeg->v4l2_dev, "Failed to init mem2mem device\n");
ret = PTR_ERR(jpeg->m2m_dev);
goto device_register_rollback;
}
jpeg->alloc_ctx = vb2_dma_contig_init_ctx(&pdev->dev);
if (IS_ERR(jpeg->alloc_ctx)) {
v4l2_err(&jpeg->v4l2_dev, "Failed to init memory allocator\n");
ret = PTR_ERR(jpeg->alloc_ctx);
goto m2m_init_rollback;
}
/* JPEG encoder /dev/videoX node */
jpeg->vfd_encoder = video_device_alloc();
if (!jpeg->vfd_encoder) {
v4l2_err(&jpeg->v4l2_dev, "Failed to allocate video device\n");
ret = -ENOMEM;
goto vb2_allocator_rollback;
}
strlcpy(jpeg->vfd_encoder->name, S5P_JPEG_M2M_NAME,
sizeof(jpeg->vfd_encoder->name));
jpeg->vfd_encoder->fops = &s5p_jpeg_fops;
jpeg->vfd_encoder->ioctl_ops = &s5p_jpeg_ioctl_ops;
jpeg->vfd_encoder->minor = -1;
jpeg->vfd_encoder->release = video_device_release;
jpeg->vfd_encoder->lock = &jpeg->lock;
jpeg->vfd_encoder->v4l2_dev = &jpeg->v4l2_dev;
jpeg->vfd_encoder->vfl_dir = VFL_DIR_M2M;
ret = video_register_device(jpeg->vfd_encoder, VFL_TYPE_GRABBER, -1);
if (ret) {
v4l2_err(&jpeg->v4l2_dev, "Failed to register video device\n");
goto enc_vdev_alloc_rollback;
}
video_set_drvdata(jpeg->vfd_encoder, jpeg);
v4l2_info(&jpeg->v4l2_dev,
"encoder device registered as /dev/video%d\n",
jpeg->vfd_encoder->num);
/* JPEG decoder /dev/videoX node */
jpeg->vfd_decoder = video_device_alloc();
if (!jpeg->vfd_decoder) {
v4l2_err(&jpeg->v4l2_dev, "Failed to allocate video device\n");
ret = -ENOMEM;
goto enc_vdev_register_rollback;
}
strlcpy(jpeg->vfd_decoder->name, S5P_JPEG_M2M_NAME,
sizeof(jpeg->vfd_decoder->name));
jpeg->vfd_decoder->fops = &s5p_jpeg_fops;
jpeg->vfd_decoder->ioctl_ops = &s5p_jpeg_ioctl_ops;
jpeg->vfd_decoder->minor = -1;
jpeg->vfd_decoder->release = video_device_release;
jpeg->vfd_decoder->lock = &jpeg->lock;
jpeg->vfd_decoder->v4l2_dev = &jpeg->v4l2_dev;
ret = video_register_device(jpeg->vfd_decoder, VFL_TYPE_GRABBER, -1);
if (ret) {
v4l2_err(&jpeg->v4l2_dev, "Failed to register video device\n");
goto dec_vdev_alloc_rollback;
}
video_set_drvdata(jpeg->vfd_decoder, jpeg);
v4l2_info(&jpeg->v4l2_dev,
"decoder device registered as /dev/video%d\n",
jpeg->vfd_decoder->num);
/* final statements & power management */
platform_set_drvdata(pdev, jpeg);
pm_runtime_enable(&pdev->dev);
v4l2_info(&jpeg->v4l2_dev, "Samsung S5P JPEG codec\n");
return 0;
dec_vdev_alloc_rollback:
video_device_release(jpeg->vfd_decoder);
enc_vdev_register_rollback:
video_unregister_device(jpeg->vfd_encoder);
enc_vdev_alloc_rollback:
video_device_release(jpeg->vfd_encoder);
vb2_allocator_rollback:
vb2_dma_contig_cleanup_ctx(jpeg->alloc_ctx);
m2m_init_rollback:
v4l2_m2m_release(jpeg->m2m_dev);
device_register_rollback:
v4l2_device_unregister(&jpeg->v4l2_dev);
clk_get_rollback:
clk_disable_unprepare(jpeg->clk);
clk_put(jpeg->clk);
return ret;
}
static int s5p_jpeg_remove(struct platform_device *pdev)
{
struct s5p_jpeg *jpeg = platform_get_drvdata(pdev);
pm_runtime_disable(jpeg->dev);
video_unregister_device(jpeg->vfd_decoder);
video_device_release(jpeg->vfd_decoder);
video_unregister_device(jpeg->vfd_encoder);
video_device_release(jpeg->vfd_encoder);
vb2_dma_contig_cleanup_ctx(jpeg->alloc_ctx);
v4l2_m2m_release(jpeg->m2m_dev);
v4l2_device_unregister(&jpeg->v4l2_dev);
clk_disable_unprepare(jpeg->clk);
clk_put(jpeg->clk);
return 0;
}
static int s5p_jpeg_runtime_suspend(struct device *dev)
{
return 0;
}
static int s5p_jpeg_runtime_resume(struct device *dev)
{
struct s5p_jpeg *jpeg = dev_get_drvdata(dev);
/*
* JPEG IP allows storing two Huffman tables for each component
* We fill table 0 for each component
*/
jpeg_set_hdctbl(jpeg->regs);
jpeg_set_hdctblg(jpeg->regs);
jpeg_set_hactbl(jpeg->regs);
jpeg_set_hactblg(jpeg->regs);
return 0;
}
static const struct dev_pm_ops s5p_jpeg_pm_ops = {
.runtime_suspend = s5p_jpeg_runtime_suspend,
.runtime_resume = s5p_jpeg_runtime_resume,
};
static struct platform_driver s5p_jpeg_driver = {
.probe = s5p_jpeg_probe,
.remove = s5p_jpeg_remove,
.driver = {
.owner = THIS_MODULE,
.name = S5P_JPEG_M2M_NAME,
.pm = &s5p_jpeg_pm_ops,
},
};
module_platform_driver(s5p_jpeg_driver);
MODULE_AUTHOR("Andrzej Pietrasiewicz <andrzej.p@samsung.com>");
MODULE_DESCRIPTION("Samsung JPEG codec driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
makerbot/linux-Birdwing | arch/arm/mach-imx/clk-imx21.c | 2688 | 9211 | /*
* Copyright 2004-2007 Freescale Semiconductor, Inc. All Rights Reserved.
* Copyright 2008 Juergen Beisert, kernel@pengutronix.de
* Copyright 2008 Martin Fuzzey, mfuzzey@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <linux/clk.h>
#include <linux/clkdev.h>
#include <linux/clk-provider.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/err.h>
#include "clk.h"
#include "common.h"
#include "hardware.h"
#define IO_ADDR_CCM(off) (MX21_IO_ADDRESS(MX21_CCM_BASE_ADDR + (off)))
/* Register offsets */
#define CCM_CSCR IO_ADDR_CCM(0x0)
#define CCM_MPCTL0 IO_ADDR_CCM(0x4)
#define CCM_MPCTL1 IO_ADDR_CCM(0x8)
#define CCM_SPCTL0 IO_ADDR_CCM(0xc)
#define CCM_SPCTL1 IO_ADDR_CCM(0x10)
#define CCM_OSC26MCTL IO_ADDR_CCM(0x14)
#define CCM_PCDR0 IO_ADDR_CCM(0x18)
#define CCM_PCDR1 IO_ADDR_CCM(0x1c)
#define CCM_PCCR0 IO_ADDR_CCM(0x20)
#define CCM_PCCR1 IO_ADDR_CCM(0x24)
#define CCM_CCSR IO_ADDR_CCM(0x28)
#define CCM_PMCTL IO_ADDR_CCM(0x2c)
#define CCM_PMCOUNT IO_ADDR_CCM(0x30)
#define CCM_WKGDCTL IO_ADDR_CCM(0x34)
static const char *mpll_sel_clks[] = { "fpm", "ckih", };
static const char *spll_sel_clks[] = { "fpm", "ckih", };
enum imx21_clks {
ckil, ckih, fpm, mpll_sel, spll_sel, mpll, spll, fclk, hclk, ipg, per1,
per2, per3, per4, uart1_ipg_gate, uart2_ipg_gate, uart3_ipg_gate,
uart4_ipg_gate, gpt1_ipg_gate, gpt2_ipg_gate, gpt3_ipg_gate,
pwm_ipg_gate, sdhc1_ipg_gate, sdhc2_ipg_gate, lcdc_ipg_gate,
lcdc_hclk_gate, cspi3_ipg_gate, cspi2_ipg_gate, cspi1_ipg_gate,
per4_gate, csi_hclk_gate, usb_div, usb_gate, usb_hclk_gate, ssi1_gate,
ssi2_gate, nfc_div, nfc_gate, dma_gate, dma_hclk_gate, brom_gate,
emma_gate, emma_hclk_gate, slcdc_gate, slcdc_hclk_gate, wdog_gate,
gpio_gate, i2c_gate, kpp_gate, owire_gate, rtc_gate, clk_max
};
static struct clk *clk[clk_max];
/*
* must be called very early to get information about the
* available clock rate when the timer framework starts
*/
int __init mx21_clocks_init(unsigned long lref, unsigned long href)
{
int i;
clk[ckil] = imx_clk_fixed("ckil", lref);
clk[ckih] = imx_clk_fixed("ckih", href);
clk[fpm] = imx_clk_fixed_factor("fpm", "ckil", 512, 1);
clk[mpll_sel] = imx_clk_mux("mpll_sel", CCM_CSCR, 16, 1, mpll_sel_clks,
ARRAY_SIZE(mpll_sel_clks));
clk[spll_sel] = imx_clk_mux("spll_sel", CCM_CSCR, 17, 1, spll_sel_clks,
ARRAY_SIZE(spll_sel_clks));
clk[mpll] = imx_clk_pllv1("mpll", "mpll_sel", CCM_MPCTL0);
clk[spll] = imx_clk_pllv1("spll", "spll_sel", CCM_SPCTL0);
clk[fclk] = imx_clk_divider("fclk", "mpll", CCM_CSCR, 29, 3);
clk[hclk] = imx_clk_divider("hclk", "fclk", CCM_CSCR, 10, 4);
clk[ipg] = imx_clk_divider("ipg", "hclk", CCM_CSCR, 9, 1);
clk[per1] = imx_clk_divider("per1", "mpll", CCM_PCDR1, 0, 6);
clk[per2] = imx_clk_divider("per2", "mpll", CCM_PCDR1, 8, 6);
clk[per3] = imx_clk_divider("per3", "mpll", CCM_PCDR1, 16, 6);
clk[per4] = imx_clk_divider("per4", "mpll", CCM_PCDR1, 24, 6);
clk[uart1_ipg_gate] = imx_clk_gate("uart1_ipg_gate", "ipg", CCM_PCCR0, 0);
clk[uart2_ipg_gate] = imx_clk_gate("uart2_ipg_gate", "ipg", CCM_PCCR0, 1);
clk[uart3_ipg_gate] = imx_clk_gate("uart3_ipg_gate", "ipg", CCM_PCCR0, 2);
clk[uart4_ipg_gate] = imx_clk_gate("uart4_ipg_gate", "ipg", CCM_PCCR0, 3);
clk[gpt1_ipg_gate] = imx_clk_gate("gpt1_ipg_gate", "ipg", CCM_PCCR1, 25);
clk[gpt2_ipg_gate] = imx_clk_gate("gpt2_ipg_gate", "ipg", CCM_PCCR1, 26);
clk[gpt3_ipg_gate] = imx_clk_gate("gpt3_ipg_gate", "ipg", CCM_PCCR1, 27);
clk[pwm_ipg_gate] = imx_clk_gate("pwm_ipg_gate", "ipg", CCM_PCCR1, 28);
clk[sdhc1_ipg_gate] = imx_clk_gate("sdhc1_ipg_gate", "ipg", CCM_PCCR0, 9);
clk[sdhc2_ipg_gate] = imx_clk_gate("sdhc2_ipg_gate", "ipg", CCM_PCCR0, 10);
clk[lcdc_ipg_gate] = imx_clk_gate("lcdc_ipg_gate", "ipg", CCM_PCCR0, 18);
clk[lcdc_hclk_gate] = imx_clk_gate("lcdc_hclk_gate", "hclk", CCM_PCCR0, 26);
clk[cspi3_ipg_gate] = imx_clk_gate("cspi3_ipg_gate", "ipg", CCM_PCCR1, 23);
clk[cspi2_ipg_gate] = imx_clk_gate("cspi2_ipg_gate", "ipg", CCM_PCCR0, 5);
clk[cspi1_ipg_gate] = imx_clk_gate("cspi1_ipg_gate", "ipg", CCM_PCCR0, 4);
clk[per4_gate] = imx_clk_gate("per4_gate", "per4", CCM_PCCR0, 22);
clk[csi_hclk_gate] = imx_clk_gate("csi_hclk_gate", "hclk", CCM_PCCR0, 31);
clk[usb_div] = imx_clk_divider("usb_div", "spll", CCM_CSCR, 26, 3);
clk[usb_gate] = imx_clk_gate("usb_gate", "usb_div", CCM_PCCR0, 14);
clk[usb_hclk_gate] = imx_clk_gate("usb_hclk_gate", "hclk", CCM_PCCR0, 24);
clk[ssi1_gate] = imx_clk_gate("ssi1_gate", "ipg", CCM_PCCR0, 6);
clk[ssi2_gate] = imx_clk_gate("ssi2_gate", "ipg", CCM_PCCR0, 7);
clk[nfc_div] = imx_clk_divider("nfc_div", "ipg", CCM_PCDR0, 12, 4);
clk[nfc_gate] = imx_clk_gate("nfc_gate", "nfc_div", CCM_PCCR0, 19);
clk[dma_gate] = imx_clk_gate("dma_gate", "ipg", CCM_PCCR0, 13);
clk[dma_hclk_gate] = imx_clk_gate("dma_hclk_gate", "hclk", CCM_PCCR0, 30);
clk[brom_gate] = imx_clk_gate("brom_gate", "hclk", CCM_PCCR0, 28);
clk[emma_gate] = imx_clk_gate("emma_gate", "ipg", CCM_PCCR0, 15);
clk[emma_hclk_gate] = imx_clk_gate("emma_hclk_gate", "hclk", CCM_PCCR0, 27);
clk[slcdc_gate] = imx_clk_gate("slcdc_gate", "ipg", CCM_PCCR0, 25);
clk[slcdc_hclk_gate] = imx_clk_gate("slcdc_hclk_gate", "hclk", CCM_PCCR0, 21);
clk[wdog_gate] = imx_clk_gate("wdog_gate", "ipg", CCM_PCCR1, 24);
clk[gpio_gate] = imx_clk_gate("gpio_gate", "ipg", CCM_PCCR0, 11);
clk[i2c_gate] = imx_clk_gate("i2c_gate", "ipg", CCM_PCCR0, 12);
clk[kpp_gate] = imx_clk_gate("kpp_gate", "ipg", CCM_PCCR1, 30);
clk[owire_gate] = imx_clk_gate("owire_gate", "ipg", CCM_PCCR1, 31);
clk[rtc_gate] = imx_clk_gate("rtc_gate", "ipg", CCM_PCCR1, 29);
for (i = 0; i < ARRAY_SIZE(clk); i++)
if (IS_ERR(clk[i]))
pr_err("i.MX21 clk %d: register failed with %ld\n",
i, PTR_ERR(clk[i]));
clk_register_clkdev(clk[per1], "per1", NULL);
clk_register_clkdev(clk[per2], "per2", NULL);
clk_register_clkdev(clk[per3], "per3", NULL);
clk_register_clkdev(clk[per4], "per4", NULL);
clk_register_clkdev(clk[per1], "per", "imx21-uart.0");
clk_register_clkdev(clk[uart1_ipg_gate], "ipg", "imx21-uart.0");
clk_register_clkdev(clk[per1], "per", "imx21-uart.1");
clk_register_clkdev(clk[uart2_ipg_gate], "ipg", "imx21-uart.1");
clk_register_clkdev(clk[per1], "per", "imx21-uart.2");
clk_register_clkdev(clk[uart3_ipg_gate], "ipg", "imx21-uart.2");
clk_register_clkdev(clk[per1], "per", "imx21-uart.3");
clk_register_clkdev(clk[uart4_ipg_gate], "ipg", "imx21-uart.3");
clk_register_clkdev(clk[gpt1_ipg_gate], "ipg", "imx-gpt.0");
clk_register_clkdev(clk[per1], "per", "imx-gpt.0");
clk_register_clkdev(clk[gpt2_ipg_gate], "ipg", "imx-gpt.1");
clk_register_clkdev(clk[per1], "per", "imx-gpt.1");
clk_register_clkdev(clk[gpt3_ipg_gate], "ipg", "imx-gpt.2");
clk_register_clkdev(clk[per1], "per", "imx-gpt.2");
clk_register_clkdev(clk[pwm_ipg_gate], "pwm", "mxc_pwm.0");
clk_register_clkdev(clk[per2], "per", "imx21-cspi.0");
clk_register_clkdev(clk[cspi1_ipg_gate], "ipg", "imx21-cspi.0");
clk_register_clkdev(clk[per2], "per", "imx21-cspi.1");
clk_register_clkdev(clk[cspi2_ipg_gate], "ipg", "imx21-cspi.1");
clk_register_clkdev(clk[per2], "per", "imx21-cspi.2");
clk_register_clkdev(clk[cspi3_ipg_gate], "ipg", "imx21-cspi.2");
clk_register_clkdev(clk[per3], "per", "imx21-fb.0");
clk_register_clkdev(clk[lcdc_ipg_gate], "ipg", "imx21-fb.0");
clk_register_clkdev(clk[lcdc_hclk_gate], "ahb", "imx21-fb.0");
clk_register_clkdev(clk[usb_gate], "per", "imx21-hcd.0");
clk_register_clkdev(clk[usb_hclk_gate], "ahb", "imx21-hcd.0");
clk_register_clkdev(clk[nfc_gate], NULL, "imx21-nand.0");
clk_register_clkdev(clk[dma_hclk_gate], "ahb", "imx21-dma");
clk_register_clkdev(clk[dma_gate], "ipg", "imx21-dma");
clk_register_clkdev(clk[wdog_gate], NULL, "imx2-wdt.0");
clk_register_clkdev(clk[i2c_gate], NULL, "imx21-i2c.0");
clk_register_clkdev(clk[kpp_gate], NULL, "mxc-keypad");
clk_register_clkdev(clk[owire_gate], NULL, "mxc_w1.0");
clk_register_clkdev(clk[brom_gate], "brom", NULL);
clk_register_clkdev(clk[emma_gate], "emma", NULL);
clk_register_clkdev(clk[slcdc_gate], "slcdc", NULL);
clk_register_clkdev(clk[gpio_gate], "gpio", NULL);
clk_register_clkdev(clk[rtc_gate], "rtc", NULL);
clk_register_clkdev(clk[csi_hclk_gate], "csi", NULL);
clk_register_clkdev(clk[ssi1_gate], "ssi1", NULL);
clk_register_clkdev(clk[ssi2_gate], "ssi2", NULL);
clk_register_clkdev(clk[sdhc1_ipg_gate], "sdhc1", NULL);
clk_register_clkdev(clk[sdhc2_ipg_gate], "sdhc2", NULL);
mxc_timer_init(MX21_IO_ADDRESS(MX21_GPT1_BASE_ADDR), MX21_INT_GPT1);
return 0;
}
| gpl-2.0 |
ShinyROM/android_kernel_asus_grouper | fs/ecryptfs/kthread.c | 4480 | 5730 | /**
* eCryptfs: Linux filesystem encryption layer
*
* Copyright (C) 2008 International Business Machines Corp.
* Author(s): Michael A. Halcrow <mahalcro@us.ibm.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/slab.h>
#include <linux/wait.h>
#include <linux/mount.h>
#include "ecryptfs_kernel.h"
struct kmem_cache *ecryptfs_open_req_cache;
static struct ecryptfs_kthread_ctl {
#define ECRYPTFS_KTHREAD_ZOMBIE 0x00000001
u32 flags;
struct mutex mux;
struct list_head req_list;
wait_queue_head_t wait;
} ecryptfs_kthread_ctl;
static struct task_struct *ecryptfs_kthread;
/**
* ecryptfs_threadfn
* @ignored: ignored
*
* The eCryptfs kernel thread that has the responsibility of getting
* the lower file with RW permissions.
*
* Returns zero on success; non-zero otherwise
*/
static int ecryptfs_threadfn(void *ignored)
{
set_freezable();
while (1) {
struct ecryptfs_open_req *req;
wait_event_freezable(
ecryptfs_kthread_ctl.wait,
(!list_empty(&ecryptfs_kthread_ctl.req_list)
|| kthread_should_stop()));
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
mutex_unlock(&ecryptfs_kthread_ctl.mux);
goto out;
}
while (!list_empty(&ecryptfs_kthread_ctl.req_list)) {
req = list_first_entry(&ecryptfs_kthread_ctl.req_list,
struct ecryptfs_open_req,
kthread_ctl_list);
mutex_lock(&req->mux);
list_del(&req->kthread_ctl_list);
if (!(req->flags & ECRYPTFS_REQ_ZOMBIE)) {
dget(req->lower_dentry);
mntget(req->lower_mnt);
(*req->lower_file) = dentry_open(
req->lower_dentry, req->lower_mnt,
(O_RDWR | O_LARGEFILE), current_cred());
req->flags |= ECRYPTFS_REQ_PROCESSED;
}
wake_up(&req->wait);
mutex_unlock(&req->mux);
}
mutex_unlock(&ecryptfs_kthread_ctl.mux);
}
out:
return 0;
}
int __init ecryptfs_init_kthread(void)
{
int rc = 0;
mutex_init(&ecryptfs_kthread_ctl.mux);
init_waitqueue_head(&ecryptfs_kthread_ctl.wait);
INIT_LIST_HEAD(&ecryptfs_kthread_ctl.req_list);
ecryptfs_kthread = kthread_run(&ecryptfs_threadfn, NULL,
"ecryptfs-kthread");
if (IS_ERR(ecryptfs_kthread)) {
rc = PTR_ERR(ecryptfs_kthread);
printk(KERN_ERR "%s: Failed to create kernel thread; rc = [%d]"
"\n", __func__, rc);
}
return rc;
}
void ecryptfs_destroy_kthread(void)
{
struct ecryptfs_open_req *req;
mutex_lock(&ecryptfs_kthread_ctl.mux);
ecryptfs_kthread_ctl.flags |= ECRYPTFS_KTHREAD_ZOMBIE;
list_for_each_entry(req, &ecryptfs_kthread_ctl.req_list,
kthread_ctl_list) {
mutex_lock(&req->mux);
req->flags |= ECRYPTFS_REQ_ZOMBIE;
wake_up(&req->wait);
mutex_unlock(&req->mux);
}
mutex_unlock(&ecryptfs_kthread_ctl.mux);
kthread_stop(ecryptfs_kthread);
wake_up(&ecryptfs_kthread_ctl.wait);
}
/**
* ecryptfs_privileged_open
* @lower_file: Result of dentry_open by root on lower dentry
* @lower_dentry: Lower dentry for file to open
* @lower_mnt: Lower vfsmount for file to open
*
* This function gets a r/w file opened againt the lower dentry.
*
* Returns zero on success; non-zero otherwise
*/
int ecryptfs_privileged_open(struct file **lower_file,
struct dentry *lower_dentry,
struct vfsmount *lower_mnt,
const struct cred *cred)
{
struct ecryptfs_open_req *req;
int flags = O_LARGEFILE;
int rc = 0;
/* Corresponding dput() and mntput() are done when the
* lower file is fput() when all eCryptfs files for the inode are
* released. */
dget(lower_dentry);
mntget(lower_mnt);
flags |= IS_RDONLY(lower_dentry->d_inode) ? O_RDONLY : O_RDWR;
(*lower_file) = dentry_open(lower_dentry, lower_mnt, flags, cred);
if (!IS_ERR(*lower_file))
goto out;
if (flags & O_RDONLY) {
rc = PTR_ERR((*lower_file));
goto out;
}
req = kmem_cache_alloc(ecryptfs_open_req_cache, GFP_KERNEL);
if (!req) {
rc = -ENOMEM;
goto out;
}
mutex_init(&req->mux);
req->lower_file = lower_file;
req->lower_dentry = lower_dentry;
req->lower_mnt = lower_mnt;
init_waitqueue_head(&req->wait);
req->flags = 0;
mutex_lock(&ecryptfs_kthread_ctl.mux);
if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) {
rc = -EIO;
mutex_unlock(&ecryptfs_kthread_ctl.mux);
printk(KERN_ERR "%s: We are in the middle of shutting down; "
"aborting privileged request to open lower file\n",
__func__);
goto out_free;
}
list_add_tail(&req->kthread_ctl_list, &ecryptfs_kthread_ctl.req_list);
mutex_unlock(&ecryptfs_kthread_ctl.mux);
wake_up(&ecryptfs_kthread_ctl.wait);
wait_event(req->wait, (req->flags != 0));
mutex_lock(&req->mux);
BUG_ON(req->flags == 0);
if (req->flags & ECRYPTFS_REQ_DROPPED
|| req->flags & ECRYPTFS_REQ_ZOMBIE) {
rc = -EIO;
printk(KERN_WARNING "%s: Privileged open request dropped\n",
__func__);
goto out_unlock;
}
if (IS_ERR(*req->lower_file))
rc = PTR_ERR(*req->lower_file);
out_unlock:
mutex_unlock(&req->mux);
out_free:
kmem_cache_free(ecryptfs_open_req_cache, req);
out:
return rc;
}
| gpl-2.0 |
PureNexusProject/android_kernel_google_molly | arch/arm/mach-omap1/devices.c | 4736 | 7988 | /*
* linux/arch/arm/mach-omap1/devices.c
*
* OMAP1 platform device setup/initialization
*
* 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/dma-mapping.h>
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <asm/mach/map.h>
#include <plat/tc.h>
#include <plat/board.h>
#include <plat/mux.h>
#include <plat/mmc.h>
#include <plat/omap7xx.h>
#include <mach/camera.h>
#include <mach/hardware.h>
#include "common.h"
#include "clock.h"
/*-------------------------------------------------------------------------*/
#if defined(CONFIG_RTC_DRV_OMAP) || defined(CONFIG_RTC_DRV_OMAP_MODULE)
#define OMAP_RTC_BASE 0xfffb4800
static struct resource rtc_resources[] = {
{
.start = OMAP_RTC_BASE,
.end = OMAP_RTC_BASE + 0x5f,
.flags = IORESOURCE_MEM,
},
{
.start = INT_RTC_TIMER,
.flags = IORESOURCE_IRQ,
},
{
.start = INT_RTC_ALARM,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device omap_rtc_device = {
.name = "omap_rtc",
.id = -1,
.num_resources = ARRAY_SIZE(rtc_resources),
.resource = rtc_resources,
};
static void omap_init_rtc(void)
{
(void) platform_device_register(&omap_rtc_device);
}
#else
static inline void omap_init_rtc(void) {}
#endif
static inline void omap_init_mbox(void) { }
/*-------------------------------------------------------------------------*/
#if defined(CONFIG_MMC_OMAP) || defined(CONFIG_MMC_OMAP_MODULE)
static inline void omap1_mmc_mux(struct omap_mmc_platform_data *mmc_controller,
int controller_nr)
{
if (controller_nr == 0) {
if (cpu_is_omap7xx()) {
omap_cfg_reg(MMC_7XX_CMD);
omap_cfg_reg(MMC_7XX_CLK);
omap_cfg_reg(MMC_7XX_DAT0);
} else {
omap_cfg_reg(MMC_CMD);
omap_cfg_reg(MMC_CLK);
omap_cfg_reg(MMC_DAT0);
}
if (cpu_is_omap1710()) {
omap_cfg_reg(M15_1710_MMC_CLKI);
omap_cfg_reg(P19_1710_MMC_CMDDIR);
omap_cfg_reg(P20_1710_MMC_DATDIR0);
}
if (mmc_controller->slots[0].wires == 4 && !cpu_is_omap7xx()) {
omap_cfg_reg(MMC_DAT1);
/* NOTE: DAT2 can be on W10 (here) or M15 */
if (!mmc_controller->slots[0].nomux)
omap_cfg_reg(MMC_DAT2);
omap_cfg_reg(MMC_DAT3);
}
}
/* Block 2 is on newer chips, and has many pinout options */
if (cpu_is_omap16xx() && controller_nr == 1) {
if (!mmc_controller->slots[1].nomux) {
omap_cfg_reg(Y8_1610_MMC2_CMD);
omap_cfg_reg(Y10_1610_MMC2_CLK);
omap_cfg_reg(R18_1610_MMC2_CLKIN);
omap_cfg_reg(W8_1610_MMC2_DAT0);
if (mmc_controller->slots[1].wires == 4) {
omap_cfg_reg(V8_1610_MMC2_DAT1);
omap_cfg_reg(W15_1610_MMC2_DAT2);
omap_cfg_reg(R10_1610_MMC2_DAT3);
}
/* These are needed for the level shifter */
omap_cfg_reg(V9_1610_MMC2_CMDDIR);
omap_cfg_reg(V5_1610_MMC2_DATDIR0);
omap_cfg_reg(W19_1610_MMC2_DATDIR1);
}
/* Feedback clock must be set on OMAP-1710 MMC2 */
if (cpu_is_omap1710())
omap_writel(omap_readl(MOD_CONF_CTRL_1) | (1 << 24),
MOD_CONF_CTRL_1);
}
}
void __init omap1_init_mmc(struct omap_mmc_platform_data **mmc_data,
int nr_controllers)
{
int i;
for (i = 0; i < nr_controllers; i++) {
unsigned long base, size;
unsigned int irq = 0;
if (!mmc_data[i])
continue;
omap1_mmc_mux(mmc_data[i], i);
switch (i) {
case 0:
base = OMAP1_MMC1_BASE;
irq = INT_MMC;
break;
case 1:
if (!cpu_is_omap16xx())
return;
base = OMAP1_MMC2_BASE;
irq = INT_1610_MMC2;
break;
default:
continue;
}
size = OMAP1_MMC_SIZE;
omap_mmc_add("mmci-omap", i, base, size, irq, mmc_data[i]);
};
}
#endif
/*-------------------------------------------------------------------------*/
/* OMAP7xx SPI support */
#if defined(CONFIG_SPI_OMAP_100K) || defined(CONFIG_SPI_OMAP_100K_MODULE)
struct platform_device omap_spi1 = {
.name = "omap1_spi100k",
.id = 1,
};
struct platform_device omap_spi2 = {
.name = "omap1_spi100k",
.id = 2,
};
static void omap_init_spi100k(void)
{
omap_spi1.dev.platform_data = ioremap(OMAP7XX_SPI1_BASE, 0x7ff);
if (omap_spi1.dev.platform_data)
platform_device_register(&omap_spi1);
omap_spi2.dev.platform_data = ioremap(OMAP7XX_SPI2_BASE, 0x7ff);
if (omap_spi2.dev.platform_data)
platform_device_register(&omap_spi2);
}
#else
static inline void omap_init_spi100k(void)
{
}
#endif
#define OMAP1_CAMERA_BASE 0xfffb6800
#define OMAP1_CAMERA_IOSIZE 0x1c
static struct resource omap1_camera_resources[] = {
[0] = {
.start = OMAP1_CAMERA_BASE,
.end = OMAP1_CAMERA_BASE + OMAP1_CAMERA_IOSIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = INT_CAMERA,
.flags = IORESOURCE_IRQ,
},
};
static u64 omap1_camera_dma_mask = DMA_BIT_MASK(32);
static struct platform_device omap1_camera_device = {
.name = "omap1-camera",
.id = 0, /* This is used to put cameras on this interface */
.dev = {
.dma_mask = &omap1_camera_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
.num_resources = ARRAY_SIZE(omap1_camera_resources),
.resource = omap1_camera_resources,
};
void __init omap1_camera_init(void *info)
{
struct platform_device *dev = &omap1_camera_device;
int ret;
dev->dev.platform_data = info;
ret = platform_device_register(dev);
if (ret)
dev_err(&dev->dev, "unable to register device: %d\n", ret);
}
/*-------------------------------------------------------------------------*/
static inline void omap_init_sti(void) {}
#if defined(CONFIG_SND_SOC) || defined(CONFIG_SND_SOC_MODULE)
static struct platform_device omap_pcm = {
.name = "omap-pcm-audio",
.id = -1,
};
static void omap_init_audio(void)
{
platform_device_register(&omap_pcm);
}
#else
static inline void omap_init_audio(void) {}
#endif
/*-------------------------------------------------------------------------*/
/*
* This gets called after board-specific INIT_MACHINE, and initializes most
* on-chip peripherals accessible on this board (except for few like USB):
*
* (a) Does any "standard config" pin muxing needed. Board-specific
* code will have muxed GPIO pins and done "nonstandard" setup;
* that code could live in the boot loader.
* (b) Populating board-specific platform_data with the data drivers
* rely on to handle wiring variations.
* (c) Creating platform devices as meaningful on this board and
* with this kernel configuration.
*
* Claiming GPIOs, and setting their direction and initial values, is the
* responsibility of the device drivers. So is responding to probe().
*
* Board-specific knowledge like creating devices or pin setup is to be
* kept out of drivers as much as possible. In particular, pin setup
* may be handled by the boot loader, and drivers should expect it will
* normally have been done by the time they're probed.
*/
static int __init omap1_init_devices(void)
{
if (!cpu_class_is_omap1())
return -ENODEV;
omap_sram_init();
omap1_clk_late_init();
/* please keep these calls, and their implementations above,
* in alphabetical order so they're easier to sort through.
*/
omap_init_mbox();
omap_init_rtc();
omap_init_spi100k();
omap_init_sti();
omap_init_audio();
return 0;
}
arch_initcall(omap1_init_devices);
#if defined(CONFIG_OMAP_WATCHDOG) || defined(CONFIG_OMAP_WATCHDOG_MODULE)
static struct resource wdt_resources[] = {
{
.start = 0xfffeb000,
.end = 0xfffeb07F,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device omap_wdt_device = {
.name = "omap_wdt",
.id = -1,
.num_resources = ARRAY_SIZE(wdt_resources),
.resource = wdt_resources,
};
static int __init omap_init_wdt(void)
{
if (!cpu_is_omap16xx())
return -ENODEV;
return platform_device_register(&omap_wdt_device);
}
subsys_initcall(omap_init_wdt);
#endif
| gpl-2.0 |
aopp/android_kernel_lge_hammerhead | arch/arm/mach-omap2/board-flash.c | 4736 | 6212 | /*
* board-flash.c
* Modified from mach-omap2/board-3430sdp-flash.c
*
* Copyright (C) 2009 Nokia Corporation
* Copyright (C) 2009 Texas Instruments
*
* Vimal Singh <vimalsingh@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/mtd/physmap.h>
#include <linux/io.h>
#include <plat/irqs.h>
#include <plat/gpmc.h>
#include <plat/nand.h>
#include <plat/onenand.h>
#include <plat/tc.h>
#include "board-flash.h"
#define REG_FPGA_REV 0x10
#define REG_FPGA_DIP_SWITCH_INPUT2 0x60
#define MAX_SUPPORTED_GPMC_CONFIG 3
#define DEBUG_BASE 0x08000000 /* debug board */
/* various memory sizes */
#define FLASH_SIZE_SDPV1 SZ_64M /* NOR flash (64 Meg aligned) */
#define FLASH_SIZE_SDPV2 SZ_128M /* NOR flash (256 Meg aligned) */
static struct physmap_flash_data board_nor_data = {
.width = 2,
};
static struct resource board_nor_resource = {
.flags = IORESOURCE_MEM,
};
static struct platform_device board_nor_device = {
.name = "physmap-flash",
.id = 0,
.dev = {
.platform_data = &board_nor_data,
},
.num_resources = 1,
.resource = &board_nor_resource,
};
static void
__init board_nor_init(struct mtd_partition *nor_parts, u8 nr_parts, u8 cs)
{
int err;
board_nor_data.parts = nor_parts;
board_nor_data.nr_parts = nr_parts;
/* Configure start address and size of NOR device */
if (omap_rev() >= OMAP3430_REV_ES1_0) {
err = gpmc_cs_request(cs, FLASH_SIZE_SDPV2 - 1,
(unsigned long *)&board_nor_resource.start);
board_nor_resource.end = board_nor_resource.start
+ FLASH_SIZE_SDPV2 - 1;
} else {
err = gpmc_cs_request(cs, FLASH_SIZE_SDPV1 - 1,
(unsigned long *)&board_nor_resource.start);
board_nor_resource.end = board_nor_resource.start
+ FLASH_SIZE_SDPV1 - 1;
}
if (err < 0) {
pr_err("NOR: Can't request GPMC CS\n");
return;
}
if (platform_device_register(&board_nor_device) < 0)
pr_err("Unable to register NOR device\n");
}
#if defined(CONFIG_MTD_ONENAND_OMAP2) || \
defined(CONFIG_MTD_ONENAND_OMAP2_MODULE)
static struct omap_onenand_platform_data board_onenand_data = {
.dma_channel = -1, /* disable DMA in OMAP OneNAND driver */
};
static void
__init board_onenand_init(struct mtd_partition *onenand_parts,
u8 nr_parts, u8 cs)
{
board_onenand_data.cs = cs;
board_onenand_data.parts = onenand_parts;
board_onenand_data.nr_parts = nr_parts;
gpmc_onenand_init(&board_onenand_data);
}
#else
static void
__init board_onenand_init(struct mtd_partition *nor_parts, u8 nr_parts, u8 cs)
{
}
#endif /* CONFIG_MTD_ONENAND_OMAP2 || CONFIG_MTD_ONENAND_OMAP2_MODULE */
#if defined(CONFIG_MTD_NAND_OMAP2) || \
defined(CONFIG_MTD_NAND_OMAP2_MODULE)
/* Note that all values in this struct are in nanoseconds */
static struct gpmc_timings nand_timings = {
.sync_clk = 0,
.cs_on = 0,
.cs_rd_off = 36,
.cs_wr_off = 36,
.adv_on = 6,
.adv_rd_off = 24,
.adv_wr_off = 36,
.we_off = 30,
.oe_off = 48,
.access = 54,
.rd_cycle = 72,
.wr_cycle = 72,
.wr_access = 30,
.wr_data_mux_bus = 0,
};
static struct omap_nand_platform_data board_nand_data = {
.gpmc_t = &nand_timings,
};
void
__init board_nand_init(struct mtd_partition *nand_parts,
u8 nr_parts, u8 cs, int nand_type)
{
board_nand_data.cs = cs;
board_nand_data.parts = nand_parts;
board_nand_data.nr_parts = nr_parts;
board_nand_data.devsize = nand_type;
board_nand_data.ecc_opt = OMAP_ECC_HAMMING_CODE_DEFAULT;
board_nand_data.gpmc_irq = OMAP_GPMC_IRQ_BASE + cs;
gpmc_nand_init(&board_nand_data);
}
#endif /* CONFIG_MTD_NAND_OMAP2 || CONFIG_MTD_NAND_OMAP2_MODULE */
/**
* get_gpmc0_type - Reads the FPGA DIP_SWITCH_INPUT_REGISTER2 to get
* the various cs values.
*/
static u8 get_gpmc0_type(void)
{
u8 cs = 0;
void __iomem *fpga_map_addr;
fpga_map_addr = ioremap(DEBUG_BASE, 4096);
if (!fpga_map_addr)
return -ENOMEM;
if (!(__raw_readw(fpga_map_addr + REG_FPGA_REV)))
/* we dont have an DEBUG FPGA??? */
/* Depend on #defines!! default to strata boot return param */
goto unmap;
/* S8-DIP-OFF = 1, S8-DIP-ON = 0 */
cs = __raw_readw(fpga_map_addr + REG_FPGA_DIP_SWITCH_INPUT2) & 0xf;
/* ES2.0 SDP's onwards 4 dip switches are provided for CS */
if (omap_rev() >= OMAP3430_REV_ES1_0)
/* change (S8-1:4=DS-2:0) to (S8-4:1=DS-2:0) */
cs = ((cs & 8) >> 3) | ((cs & 4) >> 1) |
((cs & 2) << 1) | ((cs & 1) << 3);
else
/* change (S8-1:3=DS-2:0) to (S8-3:1=DS-2:0) */
cs = ((cs & 4) >> 2) | (cs & 2) | ((cs & 1) << 2);
unmap:
iounmap(fpga_map_addr);
return cs;
}
/**
* board_flash_init - Identify devices connected to GPMC and register.
*
* @return - void.
*/
void __init board_flash_init(struct flash_partitions partition_info[],
char chip_sel_board[][GPMC_CS_NUM], int nand_type)
{
u8 cs = 0;
u8 norcs = GPMC_CS_NUM + 1;
u8 nandcs = GPMC_CS_NUM + 1;
u8 onenandcs = GPMC_CS_NUM + 1;
u8 idx;
unsigned char *config_sel = NULL;
/* REVISIT: Is this return correct idx for 2430 SDP?
* for which cs configuration matches for 2430 SDP?
*/
idx = get_gpmc0_type();
if (idx >= MAX_SUPPORTED_GPMC_CONFIG) {
pr_err("%s: Invalid chip select: %d\n", __func__, cs);
return;
}
config_sel = (unsigned char *)(chip_sel_board[idx]);
while (cs < GPMC_CS_NUM) {
switch (config_sel[cs]) {
case PDC_NOR:
if (norcs > GPMC_CS_NUM)
norcs = cs;
break;
case PDC_NAND:
if (nandcs > GPMC_CS_NUM)
nandcs = cs;
break;
case PDC_ONENAND:
if (onenandcs > GPMC_CS_NUM)
onenandcs = cs;
break;
};
cs++;
}
if (norcs > GPMC_CS_NUM)
pr_err("NOR: Unable to find configuration in GPMC\n");
else
board_nor_init(partition_info[0].parts,
partition_info[0].nr_parts, norcs);
if (onenandcs > GPMC_CS_NUM)
pr_err("OneNAND: Unable to find configuration in GPMC\n");
else
board_onenand_init(partition_info[1].parts,
partition_info[1].nr_parts, onenandcs);
if (nandcs > GPMC_CS_NUM)
pr_err("NAND: Unable to find configuration in GPMC\n");
else
board_nand_init(partition_info[2].parts,
partition_info[2].nr_parts, nandcs, nand_type);
}
| gpl-2.0 |
gem5/linux-arm-gem5 | arch/microblaze/lib/memcpy.c | 4736 | 4968 | /*
* Copyright (C) 2008-2009 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2008-2009 PetaLogix
* Copyright (C) 2007 John Williams
*
* Reasonably optimised generic C-code for memcpy on Microblaze
* This is generic C code to do efficient, alignment-aware memcpy.
*
* It is based on demo code originally Copyright 2001 by Intel Corp, taken from
* http://www.embedded.com/showArticle.jhtml?articleID=19205567
*
* Attempts were made, unsuccessfully, to contact the original
* author of this code (Michael Morrow, Intel). Below is the original
* copyright notice.
*
* This software has been developed by Intel Corporation.
* Intel specifically disclaims all warranties, express or
* implied, and all liability, including consequential and
* other indirect damages, for the use of this program, including
* liability for infringement of any proprietary rights,
* and including the warranties of merchantability and fitness
* for a particular purpose. Intel does not assume any
* responsibility for and errors which may appear in this program
* not any responsibility to update it.
*/
#include <linux/export.h>
#include <linux/types.h>
#include <linux/stddef.h>
#include <linux/compiler.h>
#include <linux/string.h>
#ifdef __HAVE_ARCH_MEMCPY
#ifndef CONFIG_OPT_LIB_FUNCTION
void *memcpy(void *v_dst, const void *v_src, __kernel_size_t c)
{
const char *src = v_src;
char *dst = v_dst;
/* Simple, byte oriented memcpy. */
while (c--)
*dst++ = *src++;
return v_dst;
}
#else /* CONFIG_OPT_LIB_FUNCTION */
void *memcpy(void *v_dst, const void *v_src, __kernel_size_t c)
{
const char *src = v_src;
char *dst = v_dst;
/* The following code tries to optimize the copy by using unsigned
* alignment. This will work fine if both source and destination are
* aligned on the same boundary. However, if they are aligned on
* different boundaries shifts will be necessary. This might result in
* bad performance on MicroBlaze systems without a barrel shifter.
*/
const uint32_t *i_src;
uint32_t *i_dst;
if (likely(c >= 4)) {
unsigned value, buf_hold;
/* Align the destination to a word boundary. */
/* This is done in an endian independent manner. */
switch ((unsigned long)dst & 3) {
case 1:
*dst++ = *src++;
--c;
case 2:
*dst++ = *src++;
--c;
case 3:
*dst++ = *src++;
--c;
}
i_dst = (void *)dst;
/* Choose a copy scheme based on the source */
/* alignment relative to destination. */
switch ((unsigned long)src & 3) {
case 0x0: /* Both byte offsets are aligned */
i_src = (const void *)src;
for (; c >= 4; c -= 4)
*i_dst++ = *i_src++;
src = (const void *)i_src;
break;
case 0x1: /* Unaligned - Off by 1 */
/* Word align the source */
i_src = (const void *) ((unsigned)src & ~3);
#ifndef __MICROBLAZEEL__
/* Load the holding buffer */
buf_hold = *i_src++ << 8;
for (; c >= 4; c -= 4) {
value = *i_src++;
*i_dst++ = buf_hold | value >> 24;
buf_hold = value << 8;
}
#else
/* Load the holding buffer */
buf_hold = (*i_src++ & 0xFFFFFF00) >> 8;
for (; c >= 4; c -= 4) {
value = *i_src++;
*i_dst++ = buf_hold | ((value & 0xFF) << 24);
buf_hold = (value & 0xFFFFFF00) >> 8;
}
#endif
/* Realign the source */
src = (const void *)i_src;
src -= 3;
break;
case 0x2: /* Unaligned - Off by 2 */
/* Word align the source */
i_src = (const void *) ((unsigned)src & ~3);
#ifndef __MICROBLAZEEL__
/* Load the holding buffer */
buf_hold = *i_src++ << 16;
for (; c >= 4; c -= 4) {
value = *i_src++;
*i_dst++ = buf_hold | value >> 16;
buf_hold = value << 16;
}
#else
/* Load the holding buffer */
buf_hold = (*i_src++ & 0xFFFF0000) >> 16;
for (; c >= 4; c -= 4) {
value = *i_src++;
*i_dst++ = buf_hold | ((value & 0xFFFF) << 16);
buf_hold = (value & 0xFFFF0000) >> 16;
}
#endif
/* Realign the source */
src = (const void *)i_src;
src -= 2;
break;
case 0x3: /* Unaligned - Off by 3 */
/* Word align the source */
i_src = (const void *) ((unsigned)src & ~3);
#ifndef __MICROBLAZEEL__
/* Load the holding buffer */
buf_hold = *i_src++ << 24;
for (; c >= 4; c -= 4) {
value = *i_src++;
*i_dst++ = buf_hold | value >> 8;
buf_hold = value << 24;
}
#else
/* Load the holding buffer */
buf_hold = (*i_src++ & 0xFF000000) >> 24;
for (; c >= 4; c -= 4) {
value = *i_src++;
*i_dst++ = buf_hold | ((value & 0xFFFFFF) << 8);
buf_hold = (value & 0xFF000000) >> 24;
}
#endif
/* Realign the source */
src = (const void *)i_src;
src -= 1;
break;
}
dst = (void *)i_dst;
}
/* Finish off any remaining bytes */
/* simple fast copy, ... unless a cache boundary is crossed */
switch (c) {
case 3:
*dst++ = *src++;
case 2:
*dst++ = *src++;
case 1:
*dst++ = *src++;
}
return v_dst;
}
#endif /* CONFIG_OPT_LIB_FUNCTION */
EXPORT_SYMBOL(memcpy);
#endif /* __HAVE_ARCH_MEMCPY */
| gpl-2.0 |
CAF-victara/kernel_msm | arch/arm/mach-omap2/i2c.c | 4992 | 2922 | /*
* Helper module for board specific I2C bus registration
*
* Copyright (C) 2009 Nokia Corporation.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <plat/cpu.h>
#include <plat/i2c.h>
#include "common.h"
#include <plat/omap_hwmod.h>
#include "mux.h"
/* In register I2C_CON, Bit 15 is the I2C enable bit */
#define I2C_EN BIT(15)
#define OMAP2_I2C_CON_OFFSET 0x24
#define OMAP4_I2C_CON_OFFSET 0xA4
/* Maximum microseconds to wait for OMAP module to softreset */
#define MAX_MODULE_SOFTRESET_WAIT 10000
void __init omap2_i2c_mux_pins(int bus_id)
{
char mux_name[sizeof("i2c2_scl.i2c2_scl")];
/* First I2C bus is not muxable */
if (bus_id == 1)
return;
sprintf(mux_name, "i2c%i_scl.i2c%i_scl", bus_id, bus_id);
omap_mux_init_signal(mux_name, OMAP_PIN_INPUT);
sprintf(mux_name, "i2c%i_sda.i2c%i_sda", bus_id, bus_id);
omap_mux_init_signal(mux_name, OMAP_PIN_INPUT);
}
/**
* omap_i2c_reset - reset the omap i2c module.
* @oh: struct omap_hwmod *
*
* The i2c moudle in omap2, omap3 had a special sequence to reset. The
* sequence is:
* - Disable the I2C.
* - Write to SOFTRESET bit.
* - Enable the I2C.
* - Poll on the RESETDONE bit.
* The sequence is implemented in below function. This is called for 2420,
* 2430 and omap3.
*/
int omap_i2c_reset(struct omap_hwmod *oh)
{
u32 v;
u16 i2c_con;
int c = 0;
if (oh->class->rev == OMAP_I2C_IP_VERSION_2) {
i2c_con = OMAP4_I2C_CON_OFFSET;
} else if (oh->class->rev == OMAP_I2C_IP_VERSION_1) {
i2c_con = OMAP2_I2C_CON_OFFSET;
} else {
WARN(1, "Cannot reset I2C block %s: unsupported revision\n",
oh->name);
return -EINVAL;
}
/* Disable I2C */
v = omap_hwmod_read(oh, i2c_con);
v &= ~I2C_EN;
omap_hwmod_write(v, oh, i2c_con);
/* Write to the SOFTRESET bit */
omap_hwmod_softreset(oh);
/* Enable I2C */
v = omap_hwmod_read(oh, i2c_con);
v |= I2C_EN;
omap_hwmod_write(v, oh, i2c_con);
/* Poll on RESETDONE bit */
omap_test_timeout((omap_hwmod_read(oh,
oh->class->sysc->syss_offs)
& SYSS_RESETDONE_MASK),
MAX_MODULE_SOFTRESET_WAIT, c);
if (c == MAX_MODULE_SOFTRESET_WAIT)
pr_warning("%s: %s: softreset failed (waited %d usec)\n",
__func__, oh->name, MAX_MODULE_SOFTRESET_WAIT);
else
pr_debug("%s: %s: softreset in %d usec\n", __func__,
oh->name, c);
return 0;
}
| gpl-2.0 |
rwaterspf1/android_kernel_lge_hammerheadcaf | drivers/tty/serial/altera_jtaguart.c | 5248 | 13645 | /*
* altera_jtaguart.c -- Altera JTAG UART driver
*
* Based on mcf.c -- Freescale ColdFire UART driver
*
* (C) Copyright 2003-2007, Greg Ungerer <gerg@snapgear.com>
* (C) Copyright 2008, Thomas Chou <thomas@wytron.com.tw>
* (C) Copyright 2010, Tobias Klauser <tklauser@distanz.ch>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/console.h>
#include <linux/of.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial.h>
#include <linux/serial_core.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/altera_jtaguart.h>
#define DRV_NAME "altera_jtaguart"
/*
* Altera JTAG UART register definitions according to the Altera JTAG UART
* datasheet: http://www.altera.com/literature/hb/nios2/n2cpu_nii51009.pdf
*/
#define ALTERA_JTAGUART_SIZE 8
#define ALTERA_JTAGUART_DATA_REG 0
#define ALTERA_JTAGUART_DATA_DATA_MSK 0x000000FF
#define ALTERA_JTAGUART_DATA_RVALID_MSK 0x00008000
#define ALTERA_JTAGUART_DATA_RAVAIL_MSK 0xFFFF0000
#define ALTERA_JTAGUART_DATA_RAVAIL_OFF 16
#define ALTERA_JTAGUART_CONTROL_REG 4
#define ALTERA_JTAGUART_CONTROL_RE_MSK 0x00000001
#define ALTERA_JTAGUART_CONTROL_WE_MSK 0x00000002
#define ALTERA_JTAGUART_CONTROL_RI_MSK 0x00000100
#define ALTERA_JTAGUART_CONTROL_RI_OFF 8
#define ALTERA_JTAGUART_CONTROL_WI_MSK 0x00000200
#define ALTERA_JTAGUART_CONTROL_AC_MSK 0x00000400
#define ALTERA_JTAGUART_CONTROL_WSPACE_MSK 0xFFFF0000
#define ALTERA_JTAGUART_CONTROL_WSPACE_OFF 16
/*
* Local per-uart structure.
*/
struct altera_jtaguart {
struct uart_port port;
unsigned int sigs; /* Local copy of line sigs */
unsigned long imr; /* Local IMR mirror */
};
static unsigned int altera_jtaguart_tx_empty(struct uart_port *port)
{
return (readl(port->membase + ALTERA_JTAGUART_CONTROL_REG) &
ALTERA_JTAGUART_CONTROL_WSPACE_MSK) ? TIOCSER_TEMT : 0;
}
static unsigned int altera_jtaguart_get_mctrl(struct uart_port *port)
{
return TIOCM_CAR | TIOCM_DSR | TIOCM_CTS;
}
static void altera_jtaguart_set_mctrl(struct uart_port *port, unsigned int sigs)
{
}
static void altera_jtaguart_start_tx(struct uart_port *port)
{
struct altera_jtaguart *pp =
container_of(port, struct altera_jtaguart, port);
pp->imr |= ALTERA_JTAGUART_CONTROL_WE_MSK;
writel(pp->imr, port->membase + ALTERA_JTAGUART_CONTROL_REG);
}
static void altera_jtaguart_stop_tx(struct uart_port *port)
{
struct altera_jtaguart *pp =
container_of(port, struct altera_jtaguart, port);
pp->imr &= ~ALTERA_JTAGUART_CONTROL_WE_MSK;
writel(pp->imr, port->membase + ALTERA_JTAGUART_CONTROL_REG);
}
static void altera_jtaguart_stop_rx(struct uart_port *port)
{
struct altera_jtaguart *pp =
container_of(port, struct altera_jtaguart, port);
pp->imr &= ~ALTERA_JTAGUART_CONTROL_RE_MSK;
writel(pp->imr, port->membase + ALTERA_JTAGUART_CONTROL_REG);
}
static void altera_jtaguart_break_ctl(struct uart_port *port, int break_state)
{
}
static void altera_jtaguart_enable_ms(struct uart_port *port)
{
}
static void altera_jtaguart_set_termios(struct uart_port *port,
struct ktermios *termios,
struct ktermios *old)
{
/* Just copy the old termios settings back */
if (old)
tty_termios_copy_hw(termios, old);
}
static void altera_jtaguart_rx_chars(struct altera_jtaguart *pp)
{
struct uart_port *port = &pp->port;
unsigned char ch, flag;
unsigned long status;
while ((status = readl(port->membase + ALTERA_JTAGUART_DATA_REG)) &
ALTERA_JTAGUART_DATA_RVALID_MSK) {
ch = status & ALTERA_JTAGUART_DATA_DATA_MSK;
flag = TTY_NORMAL;
port->icount.rx++;
if (uart_handle_sysrq_char(port, ch))
continue;
uart_insert_char(port, 0, 0, ch, flag);
}
tty_flip_buffer_push(port->state->port.tty);
}
static void altera_jtaguart_tx_chars(struct altera_jtaguart *pp)
{
struct uart_port *port = &pp->port;
struct circ_buf *xmit = &port->state->xmit;
unsigned int pending, count;
if (port->x_char) {
/* Send special char - probably flow control */
writel(port->x_char, port->membase + ALTERA_JTAGUART_DATA_REG);
port->x_char = 0;
port->icount.tx++;
return;
}
pending = uart_circ_chars_pending(xmit);
if (pending > 0) {
count = (readl(port->membase + ALTERA_JTAGUART_CONTROL_REG) &
ALTERA_JTAGUART_CONTROL_WSPACE_MSK) >>
ALTERA_JTAGUART_CONTROL_WSPACE_OFF;
if (count > pending)
count = pending;
if (count > 0) {
pending -= count;
while (count--) {
writel(xmit->buf[xmit->tail],
port->membase + ALTERA_JTAGUART_DATA_REG);
xmit->tail = (xmit->tail + 1) & (UART_XMIT_SIZE - 1);
port->icount.tx++;
}
if (pending < WAKEUP_CHARS)
uart_write_wakeup(port);
}
}
if (pending == 0) {
pp->imr &= ~ALTERA_JTAGUART_CONTROL_WE_MSK;
writel(pp->imr, port->membase + ALTERA_JTAGUART_CONTROL_REG);
}
}
static irqreturn_t altera_jtaguart_interrupt(int irq, void *data)
{
struct uart_port *port = data;
struct altera_jtaguart *pp =
container_of(port, struct altera_jtaguart, port);
unsigned int isr;
isr = (readl(port->membase + ALTERA_JTAGUART_CONTROL_REG) >>
ALTERA_JTAGUART_CONTROL_RI_OFF) & pp->imr;
spin_lock(&port->lock);
if (isr & ALTERA_JTAGUART_CONTROL_RE_MSK)
altera_jtaguart_rx_chars(pp);
if (isr & ALTERA_JTAGUART_CONTROL_WE_MSK)
altera_jtaguart_tx_chars(pp);
spin_unlock(&port->lock);
return IRQ_RETVAL(isr);
}
static void altera_jtaguart_config_port(struct uart_port *port, int flags)
{
port->type = PORT_ALTERA_JTAGUART;
/* Clear mask, so no surprise interrupts. */
writel(0, port->membase + ALTERA_JTAGUART_CONTROL_REG);
}
static int altera_jtaguart_startup(struct uart_port *port)
{
struct altera_jtaguart *pp =
container_of(port, struct altera_jtaguart, port);
unsigned long flags;
int ret;
ret = request_irq(port->irq, altera_jtaguart_interrupt, 0,
DRV_NAME, port);
if (ret) {
pr_err(DRV_NAME ": unable to attach Altera JTAG UART %d "
"interrupt vector=%d\n", port->line, port->irq);
return ret;
}
spin_lock_irqsave(&port->lock, flags);
/* Enable RX interrupts now */
pp->imr = ALTERA_JTAGUART_CONTROL_RE_MSK;
writel(pp->imr, port->membase + ALTERA_JTAGUART_CONTROL_REG);
spin_unlock_irqrestore(&port->lock, flags);
return 0;
}
static void altera_jtaguart_shutdown(struct uart_port *port)
{
struct altera_jtaguart *pp =
container_of(port, struct altera_jtaguart, port);
unsigned long flags;
spin_lock_irqsave(&port->lock, flags);
/* Disable all interrupts now */
pp->imr = 0;
writel(pp->imr, port->membase + ALTERA_JTAGUART_CONTROL_REG);
spin_unlock_irqrestore(&port->lock, flags);
free_irq(port->irq, port);
}
static const char *altera_jtaguart_type(struct uart_port *port)
{
return (port->type == PORT_ALTERA_JTAGUART) ? "Altera JTAG UART" : NULL;
}
static int altera_jtaguart_request_port(struct uart_port *port)
{
/* UARTs always present */
return 0;
}
static void altera_jtaguart_release_port(struct uart_port *port)
{
/* Nothing to release... */
}
static int altera_jtaguart_verify_port(struct uart_port *port,
struct serial_struct *ser)
{
if (ser->type != PORT_UNKNOWN && ser->type != PORT_ALTERA_JTAGUART)
return -EINVAL;
return 0;
}
/*
* Define the basic serial functions we support.
*/
static struct uart_ops altera_jtaguart_ops = {
.tx_empty = altera_jtaguart_tx_empty,
.get_mctrl = altera_jtaguart_get_mctrl,
.set_mctrl = altera_jtaguart_set_mctrl,
.start_tx = altera_jtaguart_start_tx,
.stop_tx = altera_jtaguart_stop_tx,
.stop_rx = altera_jtaguart_stop_rx,
.enable_ms = altera_jtaguart_enable_ms,
.break_ctl = altera_jtaguart_break_ctl,
.startup = altera_jtaguart_startup,
.shutdown = altera_jtaguart_shutdown,
.set_termios = altera_jtaguart_set_termios,
.type = altera_jtaguart_type,
.request_port = altera_jtaguart_request_port,
.release_port = altera_jtaguart_release_port,
.config_port = altera_jtaguart_config_port,
.verify_port = altera_jtaguart_verify_port,
};
#define ALTERA_JTAGUART_MAXPORTS 1
static struct altera_jtaguart altera_jtaguart_ports[ALTERA_JTAGUART_MAXPORTS];
#if defined(CONFIG_SERIAL_ALTERA_JTAGUART_CONSOLE)
#if defined(CONFIG_SERIAL_ALTERA_JTAGUART_CONSOLE_BYPASS)
static void altera_jtaguart_console_putc(struct console *co, const char c)
{
struct uart_port *port = &(altera_jtaguart_ports + co->index)->port;
unsigned long status;
unsigned long flags;
spin_lock_irqsave(&port->lock, flags);
while (((status = readl(port->membase + ALTERA_JTAGUART_CONTROL_REG)) &
ALTERA_JTAGUART_CONTROL_WSPACE_MSK) == 0) {
if ((status & ALTERA_JTAGUART_CONTROL_AC_MSK) == 0) {
spin_unlock_irqrestore(&port->lock, flags);
return; /* no connection activity */
}
spin_unlock_irqrestore(&port->lock, flags);
cpu_relax();
spin_lock_irqsave(&port->lock, flags);
}
writel(c, port->membase + ALTERA_JTAGUART_DATA_REG);
spin_unlock_irqrestore(&port->lock, flags);
}
#else
static void altera_jtaguart_console_putc(struct console *co, const char c)
{
struct uart_port *port = &(altera_jtaguart_ports + co->index)->port;
unsigned long flags;
spin_lock_irqsave(&port->lock, flags);
while ((readl(port->membase + ALTERA_JTAGUART_CONTROL_REG) &
ALTERA_JTAGUART_CONTROL_WSPACE_MSK) == 0) {
spin_unlock_irqrestore(&port->lock, flags);
cpu_relax();
spin_lock_irqsave(&port->lock, flags);
}
writel(c, port->membase + ALTERA_JTAGUART_DATA_REG);
spin_unlock_irqrestore(&port->lock, flags);
}
#endif
static void altera_jtaguart_console_write(struct console *co, const char *s,
unsigned int count)
{
for (; count; count--, s++) {
altera_jtaguart_console_putc(co, *s);
if (*s == '\n')
altera_jtaguart_console_putc(co, '\r');
}
}
static int __init altera_jtaguart_console_setup(struct console *co,
char *options)
{
struct uart_port *port;
if (co->index < 0 || co->index >= ALTERA_JTAGUART_MAXPORTS)
return -EINVAL;
port = &altera_jtaguart_ports[co->index].port;
if (port->membase == NULL)
return -ENODEV;
return 0;
}
static struct uart_driver altera_jtaguart_driver;
static struct console altera_jtaguart_console = {
.name = "ttyJ",
.write = altera_jtaguart_console_write,
.device = uart_console_device,
.setup = altera_jtaguart_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &altera_jtaguart_driver,
};
static int __init altera_jtaguart_console_init(void)
{
register_console(&altera_jtaguart_console);
return 0;
}
console_initcall(altera_jtaguart_console_init);
#define ALTERA_JTAGUART_CONSOLE (&altera_jtaguart_console)
#else
#define ALTERA_JTAGUART_CONSOLE NULL
#endif /* CONFIG_ALTERA_JTAGUART_CONSOLE */
static struct uart_driver altera_jtaguart_driver = {
.owner = THIS_MODULE,
.driver_name = "altera_jtaguart",
.dev_name = "ttyJ",
.major = ALTERA_JTAGUART_MAJOR,
.minor = ALTERA_JTAGUART_MINOR,
.nr = ALTERA_JTAGUART_MAXPORTS,
.cons = ALTERA_JTAGUART_CONSOLE,
};
static int __devinit altera_jtaguart_probe(struct platform_device *pdev)
{
struct altera_jtaguart_platform_uart *platp = pdev->dev.platform_data;
struct uart_port *port;
struct resource *res_irq, *res_mem;
int i = pdev->id;
/* -1 emphasizes that the platform must have one port, no .N suffix */
if (i == -1)
i = 0;
if (i >= ALTERA_JTAGUART_MAXPORTS)
return -EINVAL;
port = &altera_jtaguart_ports[i].port;
res_mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res_mem)
port->mapbase = res_mem->start;
else if (platp)
port->mapbase = platp->mapbase;
else
return -ENODEV;
res_irq = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (res_irq)
port->irq = res_irq->start;
else if (platp)
port->irq = platp->irq;
else
return -ENODEV;
port->membase = ioremap(port->mapbase, ALTERA_JTAGUART_SIZE);
if (!port->membase)
return -ENOMEM;
port->line = i;
port->type = PORT_ALTERA_JTAGUART;
port->iotype = SERIAL_IO_MEM;
port->ops = &altera_jtaguart_ops;
port->flags = UPF_BOOT_AUTOCONF;
uart_add_one_port(&altera_jtaguart_driver, port);
return 0;
}
static int __devexit altera_jtaguart_remove(struct platform_device *pdev)
{
struct uart_port *port;
int i = pdev->id;
if (i == -1)
i = 0;
port = &altera_jtaguart_ports[i].port;
uart_remove_one_port(&altera_jtaguart_driver, port);
return 0;
}
#ifdef CONFIG_OF
static struct of_device_id altera_jtaguart_match[] = {
{ .compatible = "ALTR,juart-1.0", },
{},
};
MODULE_DEVICE_TABLE(of, altera_jtaguart_match);
#endif /* CONFIG_OF */
static struct platform_driver altera_jtaguart_platform_driver = {
.probe = altera_jtaguart_probe,
.remove = __devexit_p(altera_jtaguart_remove),
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(altera_jtaguart_match),
},
};
static int __init altera_jtaguart_init(void)
{
int rc;
rc = uart_register_driver(&altera_jtaguart_driver);
if (rc)
return rc;
rc = platform_driver_register(&altera_jtaguart_platform_driver);
if (rc) {
uart_unregister_driver(&altera_jtaguart_driver);
return rc;
}
return 0;
}
static void __exit altera_jtaguart_exit(void)
{
platform_driver_unregister(&altera_jtaguart_platform_driver);
uart_unregister_driver(&altera_jtaguart_driver);
}
module_init(altera_jtaguart_init);
module_exit(altera_jtaguart_exit);
MODULE_DESCRIPTION("Altera JTAG UART driver");
MODULE_AUTHOR("Thomas Chou <thomas@wytron.com.tw>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
RJDTWO/intoxicated-boeffla | net/ipv4/datagram.c | 6784 | 2074 | /*
* common UDP/RAW code
* Linux INET implementation
*
* Authors:
* Hideaki YOSHIFUJI <yoshfuji@linux-ipv6.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <net/ip.h>
#include <net/sock.h>
#include <net/route.h>
#include <net/tcp_states.h>
int ip4_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_in *usin = (struct sockaddr_in *) uaddr;
struct flowi4 *fl4;
struct rtable *rt;
__be32 saddr;
int oif;
int err;
if (addr_len < sizeof(*usin))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
sk_dst_reset(sk);
lock_sock(sk);
oif = sk->sk_bound_dev_if;
saddr = inet->inet_saddr;
if (ipv4_is_multicast(usin->sin_addr.s_addr)) {
if (!oif)
oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
}
fl4 = &inet->cork.fl.u.ip4;
rt = ip_route_connect(fl4, usin->sin_addr.s_addr, saddr,
RT_CONN_FLAGS(sk), oif,
sk->sk_protocol,
inet->inet_sport, usin->sin_port, sk, true);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
if (err == -ENETUNREACH)
IP_INC_STATS_BH(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
goto out;
}
if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) {
ip_rt_put(rt);
err = -EACCES;
goto out;
}
if (!inet->inet_saddr)
inet->inet_saddr = fl4->saddr; /* Update source address */
if (!inet->inet_rcv_saddr) {
inet->inet_rcv_saddr = fl4->saddr;
if (sk->sk_prot->rehash)
sk->sk_prot->rehash(sk);
}
inet->inet_daddr = fl4->daddr;
inet->inet_dport = usin->sin_port;
sk->sk_state = TCP_ESTABLISHED;
inet->inet_id = jiffies;
sk_dst_set(sk, &rt->dst);
err = 0;
out:
release_sock(sk);
return err;
}
EXPORT_SYMBOL(ip4_datagram_connect);
| gpl-2.0 |
ChaOSChriS/ChaOS-mako | arch/mn10300/unit-asb2305/pci-asb2305.c | 6784 | 7026 | /* ASB2305 PCI resource stuff
*
* Copyright (C) 2001 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
* - Derived from arch/i386/pci-i386.c
* - Copyright 1997--2000 Martin Mares <mj@suse.cz>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/errno.h>
#include "pci-asb2305.h"
/*
* We need to avoid collisions with `mirrored' VGA ports
* and other strange ISA hardware, so we always want the
* addresses to be allocated in the 0x000-0x0ff region
* modulo 0x400.
*
* Why? Because some silly external IO cards only decode
* the low 10 bits of the IO address. The 0x00-0xff region
* is reserved for motherboard devices that decode all 16
* bits, so it's ok to allocate at, say, 0x2800-0x28ff,
* but we want to try to avoid allocating at 0x2900-0x2bff
* which might have be mirrored at 0x0100-0x03ff..
*/
resource_size_t pcibios_align_resource(void *data, const struct resource *res,
resource_size_t size, resource_size_t align)
{
resource_size_t start = res->start;
#if 0
struct pci_dev *dev = data;
printk(KERN_DEBUG
"### PCIBIOS_ALIGN_RESOURCE(%s,,{%08lx-%08lx,%08lx},%lx)\n",
pci_name(dev),
res->start,
res->end,
res->flags,
size
);
#endif
if ((res->flags & IORESOURCE_IO) && (start & 0x300))
start = (start + 0x3ff) & ~0x3ff;
return start;
}
/*
* Handle resources of PCI devices. If the world were perfect, we could
* just allocate all the resource regions and do nothing more. It isn't.
* On the other hand, we cannot just re-allocate all devices, as it would
* require us to know lots of host bridge internals. So we attempt to
* keep as much of the original configuration as possible, but tweak it
* when it's found to be wrong.
*
* Known BIOS problems we have to work around:
* - I/O or memory regions not configured
* - regions configured, but not enabled in the command register
* - bogus I/O addresses above 64K used
* - expansion ROMs left enabled (this may sound harmless, but given
* the fact the PCI specs explicitly allow address decoders to be
* shared between expansion ROMs and other resource regions, it's
* at least dangerous)
*
* Our solution:
* (1) Allocate resources for all buses behind PCI-to-PCI bridges.
* This gives us fixed barriers on where we can allocate.
* (2) Allocate resources for all enabled devices. If there is
* a collision, just mark the resource as unallocated. Also
* disable expansion ROMs during this step.
* (3) Try to allocate resources for disabled devices. If the
* resources were assigned correctly, everything goes well,
* if they weren't, they won't disturb allocation of other
* resources.
* (4) Assign new addresses to resources which were either
* not configured at all or misconfigured. If explicitly
* requested by the user, configure expansion ROM address
* as well.
*/
static void __init pcibios_allocate_bus_resources(struct list_head *bus_list)
{
struct pci_bus *bus;
struct pci_dev *dev;
int idx;
struct resource *r;
/* Depth-First Search on bus tree */
list_for_each_entry(bus, bus_list, node) {
dev = bus->self;
if (dev) {
for (idx = PCI_BRIDGE_RESOURCES;
idx < PCI_NUM_RESOURCES;
idx++) {
r = &dev->resource[idx];
if (!r->flags)
continue;
if (!r->start ||
pci_claim_resource(dev, idx) < 0) {
printk(KERN_ERR "PCI:"
" Cannot allocate resource"
" region %d of bridge %s\n",
idx, pci_name(dev));
/* Something is wrong with the region.
* Invalidate the resource to prevent
* child resource allocations in this
* range. */
r->start = r->end = 0;
r->flags = 0;
}
}
}
pcibios_allocate_bus_resources(&bus->children);
}
}
static void __init pcibios_allocate_resources(int pass)
{
struct pci_dev *dev = NULL;
int idx, disabled;
u16 command;
struct resource *r;
for_each_pci_dev(dev) {
pci_read_config_word(dev, PCI_COMMAND, &command);
for (idx = 0; idx < 6; idx++) {
r = &dev->resource[idx];
if (r->parent) /* Already allocated */
continue;
if (!r->start) /* Address not assigned */
continue;
if (r->flags & IORESOURCE_IO)
disabled = !(command & PCI_COMMAND_IO);
else
disabled = !(command & PCI_COMMAND_MEMORY);
if (pass == disabled) {
DBG("PCI[%s]: Resource %08lx-%08lx"
" (f=%lx, d=%d, p=%d)\n",
pci_name(dev), r->start, r->end, r->flags,
disabled, pass);
if (pci_claim_resource(dev, idx) < 0) {
printk(KERN_ERR "PCI:"
" Cannot allocate resource"
" region %d of device %s\n",
idx, pci_name(dev));
/* We'll assign a new address later */
r->end -= r->start;
r->start = 0;
}
}
}
if (!pass) {
r = &dev->resource[PCI_ROM_RESOURCE];
if (r->flags & IORESOURCE_ROM_ENABLE) {
/* Turn the ROM off, leave the resource region,
* but keep it unregistered. */
u32 reg;
DBG("PCI: Switching off ROM of %s\n",
pci_name(dev));
r->flags &= ~IORESOURCE_ROM_ENABLE;
pci_read_config_dword(
dev, dev->rom_base_reg, ®);
pci_write_config_dword(
dev, dev->rom_base_reg,
reg & ~PCI_ROM_ADDRESS_ENABLE);
}
}
}
}
static int __init pcibios_assign_resources(void)
{
struct pci_dev *dev = NULL;
struct resource *r;
if (!(pci_probe & PCI_ASSIGN_ROMS)) {
/* Try to use BIOS settings for ROMs, otherwise let
pci_assign_unassigned_resources() allocate the new
addresses. */
for_each_pci_dev(dev) {
r = &dev->resource[PCI_ROM_RESOURCE];
if (!r->flags || !r->start)
continue;
if (pci_claim_resource(dev, PCI_ROM_RESOURCE) < 0) {
r->end -= r->start;
r->start = 0;
}
}
}
pci_assign_unassigned_resources();
return 0;
}
fs_initcall(pcibios_assign_resources);
void __init pcibios_resource_survey(void)
{
DBG("PCI: Allocating resources\n");
pcibios_allocate_bus_resources(&pci_root_buses);
pcibios_allocate_resources(0);
pcibios_allocate_resources(1);
}
int pci_mmap_page_range(struct pci_dev *dev, struct vm_area_struct *vma,
enum pci_mmap_state mmap_state, int write_combine)
{
unsigned long prot;
/* Leave vm_pgoff as-is, the PCI space address is the physical
* address on this platform.
*/
vma->vm_flags |= VM_LOCKED | VM_IO;
prot = pgprot_val(vma->vm_page_prot);
prot &= ~_PAGE_CACHE;
vma->vm_page_prot = __pgprot(prot);
/* Write-combine setting is ignored */
if (io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
vma->vm_end - vma->vm_start,
vma->vm_page_prot))
return -EAGAIN;
return 0;
}
| gpl-2.0 |
android-armv7a-belalang-tempur/android_SpeedKernel_3.4-1 | arch/sparc/prom/init_32.c | 7296 | 1768 | /*
* init.c: Initialize internal variables used by the PROM
* library functions.
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <asm/openprom.h>
#include <asm/oplib.h>
struct linux_romvec *romvec;
EXPORT_SYMBOL(romvec);
enum prom_major_version prom_vers;
unsigned int prom_rev, prom_prev;
/* The root node of the prom device tree. */
phandle prom_root_node;
EXPORT_SYMBOL(prom_root_node);
/* Pointer to the device tree operations structure. */
struct linux_nodeops *prom_nodeops;
/* You must call prom_init() before you attempt to use any of the
* routines in the prom library. It returns 0 on success, 1 on
* failure. It gets passed the pointer to the PROM vector.
*/
extern void prom_meminit(void);
extern void prom_ranges_init(void);
void __init prom_init(struct linux_romvec *rp)
{
romvec = rp;
switch(romvec->pv_romvers) {
case 0:
prom_vers = PROM_V0;
break;
case 2:
prom_vers = PROM_V2;
break;
case 3:
prom_vers = PROM_V3;
break;
default:
prom_printf("PROMLIB: Bad PROM version %d\n",
romvec->pv_romvers);
prom_halt();
break;
}
prom_rev = romvec->pv_plugin_revision;
prom_prev = romvec->pv_printrev;
prom_nodeops = romvec->pv_nodeops;
prom_root_node = prom_getsibling(0);
if ((prom_root_node == 0) || ((s32)prom_root_node == -1))
prom_halt();
if((((unsigned long) prom_nodeops) == 0) ||
(((unsigned long) prom_nodeops) == -1))
prom_halt();
prom_meminit();
prom_ranges_init();
printk("PROMLIB: Sun Boot Prom Version %d Revision %d\n",
romvec->pv_romvers, prom_rev);
/* Initialization successful. */
}
| gpl-2.0 |
F4uzan/skernel_u0 | arch/mips/cobalt/rtc.c | 9344 | 1720 | /*
* Registration of Cobalt RTC platform device.
*
* Copyright (C) 2007 Yoichi Yuasa <yuasa@linux-mips.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/mc146818rtc.h>
#include <linux/platform_device.h>
static struct resource cobalt_rtc_resource[] __initdata = {
{
.start = 0x70,
.end = 0x77,
.flags = IORESOURCE_IO,
},
{
.start = RTC_IRQ,
.end = RTC_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static __init int cobalt_rtc_add(void)
{
struct platform_device *pdev;
int retval;
pdev = platform_device_alloc("rtc_cmos", -1);
if (!pdev)
return -ENOMEM;
retval = platform_device_add_resources(pdev, cobalt_rtc_resource,
ARRAY_SIZE(cobalt_rtc_resource));
if (retval)
goto err_free_device;
retval = platform_device_add(pdev);
if (retval)
goto err_free_device;
return 0;
err_free_device:
platform_device_put(pdev);
return retval;
}
device_initcall(cobalt_rtc_add);
| gpl-2.0 |
AragaoAnderson/n5x_kernel_google_msm | arch/mips/math-emu/sp_frexp.c | 10368 | 1406 | /* IEEE754 floating point arithmetic
* single precision
*/
/*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* ########################################################################
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* ########################################################################
*/
#include "ieee754sp.h"
/* close to ieeep754sp_logb
*/
ieee754sp ieee754sp_frexp(ieee754sp x, int *eptr)
{
COMPXSP;
CLEARCX;
EXPLODEXSP;
switch (xc) {
case IEEE754_CLASS_SNAN:
case IEEE754_CLASS_QNAN:
case IEEE754_CLASS_INF:
case IEEE754_CLASS_ZERO:
*eptr = 0;
return x;
case IEEE754_CLASS_DNORM:
SPDNORMX;
break;
case IEEE754_CLASS_NORM:
break;
}
*eptr = xe + 1;
return buildsp(xs, -1 + SP_EBIAS, xm & ~SP_HIDDEN_BIT);
}
| gpl-2.0 |
BoostPop/kernel_lge_hammerhead | arch/mips/math-emu/sp_modf.c | 10368 | 2019 | /* IEEE754 floating point arithmetic
* single precision
*/
/*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* ########################################################################
*
* This program is free software; you can distribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as
* published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
*
* ########################################################################
*/
#include "ieee754sp.h"
/* modf function is always exact for a finite number
*/
ieee754sp ieee754sp_modf(ieee754sp x, ieee754sp *ip)
{
COMPXSP;
CLEARCX;
EXPLODEXSP;
switch (xc) {
case IEEE754_CLASS_SNAN:
case IEEE754_CLASS_QNAN:
case IEEE754_CLASS_INF:
case IEEE754_CLASS_ZERO:
*ip = x;
return x;
case IEEE754_CLASS_DNORM:
/* far to small */
*ip = ieee754sp_zero(xs);
return x;
case IEEE754_CLASS_NORM:
break;
}
if (xe < 0) {
*ip = ieee754sp_zero(xs);
return x;
}
if (xe >= SP_MBITS) {
*ip = x;
return ieee754sp_zero(xs);
}
/* generate ipart mantissa by clearing bottom bits
*/
*ip = buildsp(xs, xe + SP_EBIAS,
((xm >> (SP_MBITS - xe)) << (SP_MBITS - xe)) &
~SP_HIDDEN_BIT);
/* generate fpart mantissa by clearing top bits
* and normalizing (must be able to normalize)
*/
xm = (xm << (32 - (SP_MBITS - xe))) >> (32 - (SP_MBITS - xe));
if (xm == 0)
return ieee754sp_zero(xs);
while ((xm >> SP_MBITS) == 0) {
xm <<= 1;
xe--;
}
return buildsp(xs, xe + SP_EBIAS, xm & ~SP_HIDDEN_BIT);
}
| gpl-2.0 |
shakalaca/ASUS_ZenFone_ZE550ML_ZE551ML | linux/kernel/drivers/net/wireless/ath/ath5k/gpio.c | 10624 | 5546 | /*
* Copyright (c) 2004-2008 Reyk Floeter <reyk@openbsd.org>
* Copyright (c) 2006-2008 Nick Kossifidis <mickflemm@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/****************\
GPIO Functions
\****************/
#include "ath5k.h"
#include "reg.h"
#include "debug.h"
/**
* DOC: GPIO/LED functions
*
* Here we control the 6 bidirectional GPIO pins provided by the hw.
* We can set a GPIO pin to be an input or an output pin on GPIO control
* register and then read or set its status from GPIO data input/output
* registers.
*
* We also control the two LED pins provided by the hw, LED_0 is our
* "power" LED and LED_1 is our "network activity" LED but many scenarios
* are available from hw. Vendors might also provide LEDs connected to the
* GPIO pins, we handle them through the LED subsystem on led.c
*/
/**
* ath5k_hw_set_ledstate() - Set led state
* @ah: The &struct ath5k_hw
* @state: One of AR5K_LED_*
*
* Used to set the LED blinking state. This only
* works for the LED connected to the LED_0, LED_1 pins,
* not the GPIO based.
*/
void
ath5k_hw_set_ledstate(struct ath5k_hw *ah, unsigned int state)
{
u32 led;
/*5210 has different led mode handling*/
u32 led_5210;
/*Reset led status*/
if (ah->ah_version != AR5K_AR5210)
AR5K_REG_DISABLE_BITS(ah, AR5K_PCICFG,
AR5K_PCICFG_LEDMODE | AR5K_PCICFG_LED);
else
AR5K_REG_DISABLE_BITS(ah, AR5K_PCICFG, AR5K_PCICFG_LED);
/*
* Some blinking values, define at your wish
*/
switch (state) {
case AR5K_LED_SCAN:
case AR5K_LED_AUTH:
led = AR5K_PCICFG_LEDMODE_PROP | AR5K_PCICFG_LED_PEND;
led_5210 = AR5K_PCICFG_LED_PEND | AR5K_PCICFG_LED_BCTL;
break;
case AR5K_LED_INIT:
led = AR5K_PCICFG_LEDMODE_PROP | AR5K_PCICFG_LED_NONE;
led_5210 = AR5K_PCICFG_LED_PEND;
break;
case AR5K_LED_ASSOC:
case AR5K_LED_RUN:
led = AR5K_PCICFG_LEDMODE_PROP | AR5K_PCICFG_LED_ASSOC;
led_5210 = AR5K_PCICFG_LED_ASSOC;
break;
default:
led = AR5K_PCICFG_LEDMODE_PROM | AR5K_PCICFG_LED_NONE;
led_5210 = AR5K_PCICFG_LED_PEND;
break;
}
/*Write new status to the register*/
if (ah->ah_version != AR5K_AR5210)
AR5K_REG_ENABLE_BITS(ah, AR5K_PCICFG, led);
else
AR5K_REG_ENABLE_BITS(ah, AR5K_PCICFG, led_5210);
}
/**
* ath5k_hw_set_gpio_input() - Set GPIO inputs
* @ah: The &struct ath5k_hw
* @gpio: GPIO pin to set as input
*/
int
ath5k_hw_set_gpio_input(struct ath5k_hw *ah, u32 gpio)
{
if (gpio >= AR5K_NUM_GPIO)
return -EINVAL;
ath5k_hw_reg_write(ah,
(ath5k_hw_reg_read(ah, AR5K_GPIOCR) & ~AR5K_GPIOCR_OUT(gpio))
| AR5K_GPIOCR_IN(gpio), AR5K_GPIOCR);
return 0;
}
/**
* ath5k_hw_set_gpio_output() - Set GPIO outputs
* @ah: The &struct ath5k_hw
* @gpio: The GPIO pin to set as output
*/
int
ath5k_hw_set_gpio_output(struct ath5k_hw *ah, u32 gpio)
{
if (gpio >= AR5K_NUM_GPIO)
return -EINVAL;
ath5k_hw_reg_write(ah,
(ath5k_hw_reg_read(ah, AR5K_GPIOCR) & ~AR5K_GPIOCR_OUT(gpio))
| AR5K_GPIOCR_OUT(gpio), AR5K_GPIOCR);
return 0;
}
/**
* ath5k_hw_get_gpio() - Get GPIO state
* @ah: The &struct ath5k_hw
* @gpio: The GPIO pin to read
*/
u32
ath5k_hw_get_gpio(struct ath5k_hw *ah, u32 gpio)
{
if (gpio >= AR5K_NUM_GPIO)
return 0xffffffff;
/* GPIO input magic */
return ((ath5k_hw_reg_read(ah, AR5K_GPIODI) & AR5K_GPIODI_M) >> gpio) &
0x1;
}
/**
* ath5k_hw_set_gpio() - Set GPIO state
* @ah: The &struct ath5k_hw
* @gpio: The GPIO pin to set
* @val: Value to set (boolean)
*/
int
ath5k_hw_set_gpio(struct ath5k_hw *ah, u32 gpio, u32 val)
{
u32 data;
if (gpio >= AR5K_NUM_GPIO)
return -EINVAL;
/* GPIO output magic */
data = ath5k_hw_reg_read(ah, AR5K_GPIODO);
data &= ~(1 << gpio);
data |= (val & 1) << gpio;
ath5k_hw_reg_write(ah, data, AR5K_GPIODO);
return 0;
}
/**
* ath5k_hw_set_gpio_intr() - Initialize the GPIO interrupt (RFKill switch)
* @ah: The &struct ath5k_hw
* @gpio: The GPIO pin to use
* @interrupt_level: True to generate interrupt on active pin (high)
*
* This function is used to set up the GPIO interrupt for the hw RFKill switch.
* That switch is connected to a GPIO pin and it's number is stored on EEPROM.
* It can either open or close the circuit to indicate that we should disable
* RF/Wireless to save power (we also get that from EEPROM).
*/
void
ath5k_hw_set_gpio_intr(struct ath5k_hw *ah, unsigned int gpio,
u32 interrupt_level)
{
u32 data;
if (gpio >= AR5K_NUM_GPIO)
return;
/*
* Set the GPIO interrupt
*/
data = (ath5k_hw_reg_read(ah, AR5K_GPIOCR) &
~(AR5K_GPIOCR_INT_SEL(gpio) | AR5K_GPIOCR_INT_SELH |
AR5K_GPIOCR_INT_ENA | AR5K_GPIOCR_OUT(gpio))) |
(AR5K_GPIOCR_INT_SEL(gpio) | AR5K_GPIOCR_INT_ENA);
ath5k_hw_reg_write(ah, interrupt_level ? data :
(data | AR5K_GPIOCR_INT_SELH), AR5K_GPIOCR);
ah->ah_imr |= AR5K_IMR_GPIO;
/* Enable GPIO interrupts */
AR5K_REG_ENABLE_BITS(ah, AR5K_PIMR, AR5K_IMR_GPIO);
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.