repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
NamelessRom/android_kernel_samsung_latona | drivers/isdn/hardware/avm/t1isa.c | 4228 | 15772 | /* $Id: t1isa.c,v 1.1.2.3 2004/02/10 01:07:12 keil Exp $
*
* Module for AVM T1 HEMA-card.
*
* Copyright 1999 by Carsten Paeth <calle@calle.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/capi.h>
#include <linux/netdevice.h>
#include <linux/kernelcapi.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/gfp.h>
#include <asm/io.h>
#include <linux/isdn/capicmd.h>
#include <linux/isdn/capiutil.h>
#include <linux/isdn/capilli.h>
#include "avmcard.h"
/* ------------------------------------------------------------- */
static char *revision = "$Revision: 1.1.2.3 $";
/* ------------------------------------------------------------- */
MODULE_DESCRIPTION("CAPI4Linux: Driver for AVM T1 HEMA ISA card");
MODULE_AUTHOR("Carsten Paeth");
MODULE_LICENSE("GPL");
/* ------------------------------------------------------------- */
static int hema_irq_table[16] =
{0,
0,
0,
0x80, /* irq 3 */
0,
0x90, /* irq 5 */
0,
0xA0, /* irq 7 */
0,
0xB0, /* irq 9 */
0xC0, /* irq 10 */
0xD0, /* irq 11 */
0xE0, /* irq 12 */
0,
0,
0xF0, /* irq 15 */
};
static int t1_detectandinit(unsigned int base, unsigned irq, int cardnr)
{
unsigned char cregs[8];
unsigned char reverse_cardnr;
unsigned char dummy;
int i;
reverse_cardnr = ((cardnr & 0x01) << 3) | ((cardnr & 0x02) << 1)
| ((cardnr & 0x04) >> 1) | ((cardnr & 0x08) >> 3);
cregs[0] = (HEMA_VERSION_ID << 4) | (reverse_cardnr & 0xf);
cregs[1] = 0x00; /* fast & slow link connected to CON1 */
cregs[2] = 0x05; /* fast link 20MBit, slow link 20 MBit */
cregs[3] = 0;
cregs[4] = 0x11; /* zero wait state */
cregs[5] = hema_irq_table[irq & 0xf];
cregs[6] = 0;
cregs[7] = 0;
/*
* no one else should use the ISA bus in this moment,
* but no function there to prevent this :-(
* save_flags(flags); cli();
*/
/* board reset */
t1outp(base, T1_RESETBOARD, 0xf);
mdelay(100);
dummy = t1inp(base, T1_FASTLINK+T1_OUTSTAT); /* first read */
/* write config */
dummy = (base >> 4) & 0xff;
for (i=1;i<=0xf;i++) t1outp(base, i, dummy);
t1outp(base, HEMA_PAL_ID & 0xf, dummy);
t1outp(base, HEMA_PAL_ID >> 4, cregs[0]);
for(i=1;i<7;i++) t1outp(base, 0, cregs[i]);
t1outp(base, ((base >> 4)) & 0x3, cregs[7]);
/* restore_flags(flags); */
mdelay(100);
t1outp(base, T1_FASTLINK+T1_RESETLINK, 0);
t1outp(base, T1_SLOWLINK+T1_RESETLINK, 0);
mdelay(10);
t1outp(base, T1_FASTLINK+T1_RESETLINK, 1);
t1outp(base, T1_SLOWLINK+T1_RESETLINK, 1);
mdelay(100);
t1outp(base, T1_FASTLINK+T1_RESETLINK, 0);
t1outp(base, T1_SLOWLINK+T1_RESETLINK, 0);
mdelay(10);
t1outp(base, T1_FASTLINK+T1_ANALYSE, 0);
mdelay(5);
t1outp(base, T1_SLOWLINK+T1_ANALYSE, 0);
if (t1inp(base, T1_FASTLINK+T1_OUTSTAT) != 0x1) /* tx empty */
return 1;
if (t1inp(base, T1_FASTLINK+T1_INSTAT) != 0x0) /* rx empty */
return 2;
if (t1inp(base, T1_FASTLINK+T1_IRQENABLE) != 0x0)
return 3;
if ((t1inp(base, T1_FASTLINK+T1_FIFOSTAT) & 0xf0) != 0x70)
return 4;
if ((t1inp(base, T1_FASTLINK+T1_IRQMASTER) & 0x0e) != 0)
return 5;
if ((t1inp(base, T1_FASTLINK+T1_IDENT) & 0x7d) != 1)
return 6;
if (t1inp(base, T1_SLOWLINK+T1_OUTSTAT) != 0x1) /* tx empty */
return 7;
if ((t1inp(base, T1_SLOWLINK+T1_IRQMASTER) & 0x0e) != 0)
return 8;
if ((t1inp(base, T1_SLOWLINK+T1_IDENT) & 0x7d) != 0)
return 9;
return 0;
}
static irqreturn_t t1isa_interrupt(int interrupt, void *devptr)
{
avmcard *card = devptr;
avmctrl_info *cinfo = &card->ctrlinfo[0];
struct capi_ctr *ctrl = &cinfo->capi_ctrl;
unsigned char b1cmd;
struct sk_buff *skb;
unsigned ApplId;
unsigned MsgLen;
unsigned DataB3Len;
unsigned NCCI;
unsigned WindowSize;
unsigned long flags;
spin_lock_irqsave(&card->lock, flags);
while (b1_rx_full(card->port)) {
b1cmd = b1_get_byte(card->port);
switch (b1cmd) {
case RECEIVE_DATA_B3_IND:
ApplId = (unsigned) b1_get_word(card->port);
MsgLen = t1_get_slice(card->port, card->msgbuf);
DataB3Len = t1_get_slice(card->port, card->databuf);
spin_unlock_irqrestore(&card->lock, flags);
if (MsgLen < 30) { /* not CAPI 64Bit */
memset(card->msgbuf+MsgLen, 0, 30-MsgLen);
MsgLen = 30;
CAPIMSG_SETLEN(card->msgbuf, 30);
}
if (!(skb = alloc_skb(DataB3Len+MsgLen, GFP_ATOMIC))) {
printk(KERN_ERR "%s: incoming packet dropped\n",
card->name);
} else {
memcpy(skb_put(skb, MsgLen), card->msgbuf, MsgLen);
memcpy(skb_put(skb, DataB3Len), card->databuf, DataB3Len);
capi_ctr_handle_message(ctrl, ApplId, skb);
}
break;
case RECEIVE_MESSAGE:
ApplId = (unsigned) b1_get_word(card->port);
MsgLen = t1_get_slice(card->port, card->msgbuf);
if (!(skb = alloc_skb(MsgLen, GFP_ATOMIC))) {
spin_unlock_irqrestore(&card->lock, flags);
printk(KERN_ERR "%s: incoming packet dropped\n",
card->name);
} else {
memcpy(skb_put(skb, MsgLen), card->msgbuf, MsgLen);
if (CAPIMSG_CMD(skb->data) == CAPI_DATA_B3)
capilib_data_b3_conf(&cinfo->ncci_head, ApplId,
CAPIMSG_NCCI(skb->data),
CAPIMSG_MSGID(skb->data));
spin_unlock_irqrestore(&card->lock, flags);
capi_ctr_handle_message(ctrl, ApplId, skb);
}
break;
case RECEIVE_NEW_NCCI:
ApplId = b1_get_word(card->port);
NCCI = b1_get_word(card->port);
WindowSize = b1_get_word(card->port);
capilib_new_ncci(&cinfo->ncci_head, ApplId, NCCI, WindowSize);
spin_unlock_irqrestore(&card->lock, flags);
break;
case RECEIVE_FREE_NCCI:
ApplId = b1_get_word(card->port);
NCCI = b1_get_word(card->port);
if (NCCI != 0xffffffff)
capilib_free_ncci(&cinfo->ncci_head, ApplId, NCCI);
spin_unlock_irqrestore(&card->lock, flags);
break;
case RECEIVE_START:
b1_put_byte(card->port, SEND_POLLACK);
spin_unlock_irqrestore(&card->lock, flags);
capi_ctr_resume_output(ctrl);
break;
case RECEIVE_STOP:
spin_unlock_irqrestore(&card->lock, flags);
capi_ctr_suspend_output(ctrl);
break;
case RECEIVE_INIT:
cinfo->versionlen = t1_get_slice(card->port, cinfo->versionbuf);
spin_unlock_irqrestore(&card->lock, flags);
b1_parse_version(cinfo);
printk(KERN_INFO "%s: %s-card (%s) now active\n",
card->name,
cinfo->version[VER_CARDTYPE],
cinfo->version[VER_DRIVER]);
capi_ctr_ready(ctrl);
break;
case RECEIVE_TASK_READY:
ApplId = (unsigned) b1_get_word(card->port);
MsgLen = t1_get_slice(card->port, card->msgbuf);
spin_unlock_irqrestore(&card->lock, flags);
card->msgbuf[MsgLen] = 0;
while ( MsgLen > 0
&& ( card->msgbuf[MsgLen-1] == '\n'
|| card->msgbuf[MsgLen-1] == '\r')) {
card->msgbuf[MsgLen-1] = 0;
MsgLen--;
}
printk(KERN_INFO "%s: task %d \"%s\" ready.\n",
card->name, ApplId, card->msgbuf);
break;
case RECEIVE_DEBUGMSG:
MsgLen = t1_get_slice(card->port, card->msgbuf);
spin_unlock_irqrestore(&card->lock, flags);
card->msgbuf[MsgLen] = 0;
while ( MsgLen > 0
&& ( card->msgbuf[MsgLen-1] == '\n'
|| card->msgbuf[MsgLen-1] == '\r')) {
card->msgbuf[MsgLen-1] = 0;
MsgLen--;
}
printk(KERN_INFO "%s: DEBUG: %s\n", card->name, card->msgbuf);
break;
case 0xff:
spin_unlock_irqrestore(&card->lock, flags);
printk(KERN_ERR "%s: card reseted ?\n", card->name);
return IRQ_HANDLED;
default:
spin_unlock_irqrestore(&card->lock, flags);
printk(KERN_ERR "%s: b1_interrupt: 0x%x ???\n",
card->name, b1cmd);
return IRQ_NONE;
}
}
return IRQ_HANDLED;
}
/* ------------------------------------------------------------- */
static int t1isa_load_firmware(struct capi_ctr *ctrl, capiloaddata *data)
{
avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata);
avmcard *card = cinfo->card;
unsigned int port = card->port;
unsigned long flags;
int retval;
t1_disable_irq(port);
b1_reset(port);
if ((retval = b1_load_t4file(card, &data->firmware))) {
b1_reset(port);
printk(KERN_ERR "%s: failed to load t4file!!\n",
card->name);
return retval;
}
if (data->configuration.len > 0 && data->configuration.data) {
if ((retval = b1_load_config(card, &data->configuration))) {
b1_reset(port);
printk(KERN_ERR "%s: failed to load config!!\n",
card->name);
return retval;
}
}
if (!b1_loaded(card)) {
printk(KERN_ERR "%s: failed to load t4file.\n", card->name);
return -EIO;
}
spin_lock_irqsave(&card->lock, flags);
b1_setinterrupt(port, card->irq, card->cardtype);
b1_put_byte(port, SEND_INIT);
b1_put_word(port, CAPI_MAXAPPL);
b1_put_word(port, AVM_NCCI_PER_CHANNEL*30);
b1_put_word(port, ctrl->cnr - 1);
spin_unlock_irqrestore(&card->lock, flags);
return 0;
}
static void t1isa_reset_ctr(struct capi_ctr *ctrl)
{
avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata);
avmcard *card = cinfo->card;
unsigned int port = card->port;
unsigned long flags;
t1_disable_irq(port);
b1_reset(port);
b1_reset(port);
memset(cinfo->version, 0, sizeof(cinfo->version));
spin_lock_irqsave(&card->lock, flags);
capilib_release(&cinfo->ncci_head);
spin_unlock_irqrestore(&card->lock, flags);
capi_ctr_down(ctrl);
}
static void t1isa_remove(struct pci_dev *pdev)
{
avmctrl_info *cinfo = pci_get_drvdata(pdev);
avmcard *card;
if (!cinfo)
return;
card = cinfo->card;
t1_disable_irq(card->port);
b1_reset(card->port);
b1_reset(card->port);
t1_reset(card->port);
detach_capi_ctr(&cinfo->capi_ctrl);
free_irq(card->irq, card);
release_region(card->port, AVMB1_PORTLEN);
b1_free_card(card);
}
/* ------------------------------------------------------------- */
static u16 t1isa_send_message(struct capi_ctr *ctrl, struct sk_buff *skb);
static char *t1isa_procinfo(struct capi_ctr *ctrl);
static int t1isa_probe(struct pci_dev *pdev, int cardnr)
{
avmctrl_info *cinfo;
avmcard *card;
int retval;
card = b1_alloc_card(1);
if (!card) {
printk(KERN_WARNING "t1isa: no memory.\n");
retval = -ENOMEM;
goto err;
}
cinfo = card->ctrlinfo;
card->port = pci_resource_start(pdev, 0);
card->irq = pdev->irq;
card->cardtype = avm_t1isa;
card->cardnr = cardnr;
sprintf(card->name, "t1isa-%x", card->port);
if (!(((card->port & 0x7) == 0) && ((card->port & 0x30) != 0x30))) {
printk(KERN_WARNING "t1isa: invalid port 0x%x.\n", card->port);
retval = -EINVAL;
goto err_free;
}
if (hema_irq_table[card->irq & 0xf] == 0) {
printk(KERN_WARNING "t1isa: irq %d not valid.\n", card->irq);
retval = -EINVAL;
goto err_free;
}
if (!request_region(card->port, AVMB1_PORTLEN, card->name)) {
printk(KERN_INFO "t1isa: ports 0x%03x-0x%03x in use.\n",
card->port, card->port + AVMB1_PORTLEN);
retval = -EBUSY;
goto err_free;
}
retval = request_irq(card->irq, t1isa_interrupt, 0, card->name, card);
if (retval) {
printk(KERN_INFO "t1isa: unable to get IRQ %d.\n", card->irq);
retval = -EBUSY;
goto err_release_region;
}
if ((retval = t1_detectandinit(card->port, card->irq, card->cardnr)) != 0) {
printk(KERN_INFO "t1isa: NO card at 0x%x (%d)\n",
card->port, retval);
retval = -ENODEV;
goto err_free_irq;
}
t1_disable_irq(card->port);
b1_reset(card->port);
cinfo->capi_ctrl.owner = THIS_MODULE;
cinfo->capi_ctrl.driver_name = "t1isa";
cinfo->capi_ctrl.driverdata = cinfo;
cinfo->capi_ctrl.register_appl = b1_register_appl;
cinfo->capi_ctrl.release_appl = b1_release_appl;
cinfo->capi_ctrl.send_message = t1isa_send_message;
cinfo->capi_ctrl.load_firmware = t1isa_load_firmware;
cinfo->capi_ctrl.reset_ctr = t1isa_reset_ctr;
cinfo->capi_ctrl.procinfo = t1isa_procinfo;
cinfo->capi_ctrl.proc_fops = &b1ctl_proc_fops;
strcpy(cinfo->capi_ctrl.name, card->name);
retval = attach_capi_ctr(&cinfo->capi_ctrl);
if (retval) {
printk(KERN_INFO "t1isa: attach controller failed.\n");
goto err_free_irq;
}
printk(KERN_INFO "t1isa: AVM T1 ISA at i/o %#x, irq %d, card %d\n",
card->port, card->irq, card->cardnr);
pci_set_drvdata(pdev, cinfo);
return 0;
err_free_irq:
free_irq(card->irq, card);
err_release_region:
release_region(card->port, AVMB1_PORTLEN);
err_free:
b1_free_card(card);
err:
return retval;
}
static u16 t1isa_send_message(struct capi_ctr *ctrl, struct sk_buff *skb)
{
avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata);
avmcard *card = cinfo->card;
unsigned int port = card->port;
unsigned long flags;
u16 len = CAPIMSG_LEN(skb->data);
u8 cmd = CAPIMSG_COMMAND(skb->data);
u8 subcmd = CAPIMSG_SUBCOMMAND(skb->data);
u16 dlen, retval;
spin_lock_irqsave(&card->lock, flags);
if (CAPICMD(cmd, subcmd) == CAPI_DATA_B3_REQ) {
retval = capilib_data_b3_req(&cinfo->ncci_head,
CAPIMSG_APPID(skb->data),
CAPIMSG_NCCI(skb->data),
CAPIMSG_MSGID(skb->data));
if (retval != CAPI_NOERROR) {
spin_unlock_irqrestore(&card->lock, flags);
return retval;
}
dlen = CAPIMSG_DATALEN(skb->data);
b1_put_byte(port, SEND_DATA_B3_REQ);
t1_put_slice(port, skb->data, len);
t1_put_slice(port, skb->data + len, dlen);
} else {
b1_put_byte(port, SEND_MESSAGE);
t1_put_slice(port, skb->data, len);
}
spin_unlock_irqrestore(&card->lock, flags);
dev_kfree_skb_any(skb);
return CAPI_NOERROR;
}
/* ------------------------------------------------------------- */
static char *t1isa_procinfo(struct capi_ctr *ctrl)
{
avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata);
if (!cinfo)
return "";
sprintf(cinfo->infobuf, "%s %s 0x%x %d %d",
cinfo->cardname[0] ? cinfo->cardname : "-",
cinfo->version[VER_DRIVER] ? cinfo->version[VER_DRIVER] : "-",
cinfo->card ? cinfo->card->port : 0x0,
cinfo->card ? cinfo->card->irq : 0,
cinfo->card ? cinfo->card->cardnr : 0
);
return cinfo->infobuf;
}
/* ------------------------------------------------------------- */
#define MAX_CARDS 4
static struct pci_dev isa_dev[MAX_CARDS];
static int io[MAX_CARDS];
static int irq[MAX_CARDS];
static int cardnr[MAX_CARDS];
module_param_array(io, int, NULL, 0);
module_param_array(irq, int, NULL, 0);
module_param_array(cardnr, int, NULL, 0);
MODULE_PARM_DESC(io, "I/O base address(es)");
MODULE_PARM_DESC(irq, "IRQ number(s) (assigned)");
MODULE_PARM_DESC(cardnr, "Card number(s) (as jumpered)");
static int t1isa_add_card(struct capi_driver *driver, capicardparams *data)
{
int i;
for (i = 0; i < MAX_CARDS; i++) {
if (isa_dev[i].resource[0].start)
continue;
isa_dev[i].resource[0].start = data->port;
isa_dev[i].irq = data->irq;
if (t1isa_probe(&isa_dev[i], data->cardnr) == 0)
return 0;
}
return -ENODEV;
}
static struct capi_driver capi_driver_t1isa = {
.name = "t1isa",
.revision = "1.0",
.add_card = t1isa_add_card,
};
static int __init t1isa_init(void)
{
char rev[32];
char *p;
int i;
if ((p = strchr(revision, ':')) != NULL && p[1]) {
strlcpy(rev, p + 2, 32);
if ((p = strchr(rev, '$')) != NULL && p > rev)
*(p-1) = 0;
} else
strcpy(rev, "1.0");
for (i = 0; i < MAX_CARDS; i++) {
if (!io[i])
break;
isa_dev[i].resource[0].start = io[i];
isa_dev[i].irq = irq[i];
if (t1isa_probe(&isa_dev[i], cardnr[i]) != 0)
return -ENODEV;
}
strlcpy(capi_driver_t1isa.revision, rev, 32);
register_capi_driver(&capi_driver_t1isa);
printk(KERN_INFO "t1isa: revision %s\n", rev);
return 0;
}
static void __exit t1isa_exit(void)
{
int i;
unregister_capi_driver(&capi_driver_t1isa);
for (i = 0; i < MAX_CARDS; i++) {
if (!io[i])
break;
t1isa_remove(&isa_dev[i]);
}
}
module_init(t1isa_init);
module_exit(t1isa_exit);
| gpl-2.0 |
SerenityS/android_kernel_pantech_msm8974 | arch/mips/ath79/dev-usb.c | 4484 | 5753 | /*
* Atheros AR7XXX/AR9XXX USB Host Controller device
*
* Copyright (C) 2008-2011 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2008 Imre Kaloz <kaloz@openwrt.org>
*
* Parts of this file are based on Atheros' 2.6.15 BSP
*
* 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/delay.h>
#include <linux/irq.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/usb/ehci_pdriver.h>
#include <linux/usb/ohci_pdriver.h>
#include <asm/mach-ath79/ath79.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
#include "dev-usb.h"
static struct resource ath79_ohci_resources[] = {
[0] = {
/* .start and .end fields are filled dynamically */
.flags = IORESOURCE_MEM,
},
[1] = {
.start = ATH79_MISC_IRQ_OHCI,
.end = ATH79_MISC_IRQ_OHCI,
.flags = IORESOURCE_IRQ,
},
};
static u64 ath79_ohci_dmamask = DMA_BIT_MASK(32);
static struct usb_ohci_pdata ath79_ohci_pdata = {
};
static struct platform_device ath79_ohci_device = {
.name = "ohci-platform",
.id = -1,
.resource = ath79_ohci_resources,
.num_resources = ARRAY_SIZE(ath79_ohci_resources),
.dev = {
.dma_mask = &ath79_ohci_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &ath79_ohci_pdata,
},
};
static struct resource ath79_ehci_resources[] = {
[0] = {
/* .start and .end fields are filled dynamically */
.flags = IORESOURCE_MEM,
},
[1] = {
.start = ATH79_CPU_IRQ_USB,
.end = ATH79_CPU_IRQ_USB,
.flags = IORESOURCE_IRQ,
},
};
static u64 ath79_ehci_dmamask = DMA_BIT_MASK(32);
static struct usb_ehci_pdata ath79_ehci_pdata_v1 = {
.has_synopsys_hc_bug = 1,
.port_power_off = 1,
};
static struct usb_ehci_pdata ath79_ehci_pdata_v2 = {
.caps_offset = 0x100,
.has_tt = 1,
.port_power_off = 1,
};
static struct platform_device ath79_ehci_device = {
.name = "ehci-platform",
.id = -1,
.resource = ath79_ehci_resources,
.num_resources = ARRAY_SIZE(ath79_ehci_resources),
.dev = {
.dma_mask = &ath79_ehci_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
#define AR71XX_USB_RESET_MASK (AR71XX_RESET_USB_HOST | \
AR71XX_RESET_USB_PHY | \
AR71XX_RESET_USB_OHCI_DLL)
static void __init ath79_usb_setup(void)
{
void __iomem *usb_ctrl_base;
ath79_device_reset_set(AR71XX_USB_RESET_MASK);
mdelay(1000);
ath79_device_reset_clear(AR71XX_USB_RESET_MASK);
usb_ctrl_base = ioremap(AR71XX_USB_CTRL_BASE, AR71XX_USB_CTRL_SIZE);
/* Turning on the Buff and Desc swap bits */
__raw_writel(0xf0000, usb_ctrl_base + AR71XX_USB_CTRL_REG_CONFIG);
/* WAR for HW bug. Here it adjusts the duration between two SOFS */
__raw_writel(0x20c00, usb_ctrl_base + AR71XX_USB_CTRL_REG_FLADJ);
iounmap(usb_ctrl_base);
mdelay(900);
ath79_ohci_resources[0].start = AR71XX_OHCI_BASE;
ath79_ohci_resources[0].end = AR71XX_OHCI_BASE + AR71XX_OHCI_SIZE - 1;
platform_device_register(&ath79_ohci_device);
ath79_ehci_resources[0].start = AR71XX_EHCI_BASE;
ath79_ehci_resources[0].end = AR71XX_EHCI_BASE + AR71XX_EHCI_SIZE - 1;
ath79_ehci_device.dev.platform_data = &ath79_ehci_pdata_v1;
platform_device_register(&ath79_ehci_device);
}
static void __init ar7240_usb_setup(void)
{
void __iomem *usb_ctrl_base;
ath79_device_reset_clear(AR7240_RESET_OHCI_DLL);
ath79_device_reset_set(AR7240_RESET_USB_HOST);
mdelay(1000);
ath79_device_reset_set(AR7240_RESET_OHCI_DLL);
ath79_device_reset_clear(AR7240_RESET_USB_HOST);
usb_ctrl_base = ioremap(AR7240_USB_CTRL_BASE, AR7240_USB_CTRL_SIZE);
/* WAR for HW bug. Here it adjusts the duration between two SOFS */
__raw_writel(0x3, usb_ctrl_base + AR71XX_USB_CTRL_REG_FLADJ);
iounmap(usb_ctrl_base);
ath79_ohci_resources[0].start = AR7240_OHCI_BASE;
ath79_ohci_resources[0].end = AR7240_OHCI_BASE + AR7240_OHCI_SIZE - 1;
platform_device_register(&ath79_ohci_device);
}
static void __init ar724x_usb_setup(void)
{
ath79_device_reset_set(AR724X_RESET_USBSUS_OVERRIDE);
mdelay(10);
ath79_device_reset_clear(AR724X_RESET_USB_HOST);
mdelay(10);
ath79_device_reset_clear(AR724X_RESET_USB_PHY);
mdelay(10);
ath79_ehci_resources[0].start = AR724X_EHCI_BASE;
ath79_ehci_resources[0].end = AR724X_EHCI_BASE + AR724X_EHCI_SIZE - 1;
ath79_ehci_device.dev.platform_data = &ath79_ehci_pdata_v2;
platform_device_register(&ath79_ehci_device);
}
static void __init ar913x_usb_setup(void)
{
ath79_device_reset_set(AR913X_RESET_USBSUS_OVERRIDE);
mdelay(10);
ath79_device_reset_clear(AR913X_RESET_USB_HOST);
mdelay(10);
ath79_device_reset_clear(AR913X_RESET_USB_PHY);
mdelay(10);
ath79_ehci_resources[0].start = AR913X_EHCI_BASE;
ath79_ehci_resources[0].end = AR913X_EHCI_BASE + AR913X_EHCI_SIZE - 1;
ath79_ehci_device.dev.platform_data = &ath79_ehci_pdata_v2;
platform_device_register(&ath79_ehci_device);
}
static void __init ar933x_usb_setup(void)
{
ath79_device_reset_set(AR933X_RESET_USBSUS_OVERRIDE);
mdelay(10);
ath79_device_reset_clear(AR933X_RESET_USB_HOST);
mdelay(10);
ath79_device_reset_clear(AR933X_RESET_USB_PHY);
mdelay(10);
ath79_ehci_resources[0].start = AR933X_EHCI_BASE;
ath79_ehci_resources[0].end = AR933X_EHCI_BASE + AR933X_EHCI_SIZE - 1;
ath79_ehci_device.dev.platform_data = &ath79_ehci_pdata_v2;
platform_device_register(&ath79_ehci_device);
}
void __init ath79_register_usb(void)
{
if (soc_is_ar71xx())
ath79_usb_setup();
else if (soc_is_ar7240())
ar7240_usb_setup();
else if (soc_is_ar7241() || soc_is_ar7242())
ar724x_usb_setup();
else if (soc_is_ar913x())
ar913x_usb_setup();
else if (soc_is_ar933x())
ar933x_usb_setup();
else
BUG();
}
| gpl-2.0 |
drewx2/android_kernel_htc_dlx | virt/arch/mips/ath79/dev-usb.c | 4484 | 5753 | /*
* Atheros AR7XXX/AR9XXX USB Host Controller device
*
* Copyright (C) 2008-2011 Gabor Juhos <juhosg@openwrt.org>
* Copyright (C) 2008 Imre Kaloz <kaloz@openwrt.org>
*
* Parts of this file are based on Atheros' 2.6.15 BSP
*
* 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/delay.h>
#include <linux/irq.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/usb/ehci_pdriver.h>
#include <linux/usb/ohci_pdriver.h>
#include <asm/mach-ath79/ath79.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
#include "dev-usb.h"
static struct resource ath79_ohci_resources[] = {
[0] = {
/* .start and .end fields are filled dynamically */
.flags = IORESOURCE_MEM,
},
[1] = {
.start = ATH79_MISC_IRQ_OHCI,
.end = ATH79_MISC_IRQ_OHCI,
.flags = IORESOURCE_IRQ,
},
};
static u64 ath79_ohci_dmamask = DMA_BIT_MASK(32);
static struct usb_ohci_pdata ath79_ohci_pdata = {
};
static struct platform_device ath79_ohci_device = {
.name = "ohci-platform",
.id = -1,
.resource = ath79_ohci_resources,
.num_resources = ARRAY_SIZE(ath79_ohci_resources),
.dev = {
.dma_mask = &ath79_ohci_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &ath79_ohci_pdata,
},
};
static struct resource ath79_ehci_resources[] = {
[0] = {
/* .start and .end fields are filled dynamically */
.flags = IORESOURCE_MEM,
},
[1] = {
.start = ATH79_CPU_IRQ_USB,
.end = ATH79_CPU_IRQ_USB,
.flags = IORESOURCE_IRQ,
},
};
static u64 ath79_ehci_dmamask = DMA_BIT_MASK(32);
static struct usb_ehci_pdata ath79_ehci_pdata_v1 = {
.has_synopsys_hc_bug = 1,
.port_power_off = 1,
};
static struct usb_ehci_pdata ath79_ehci_pdata_v2 = {
.caps_offset = 0x100,
.has_tt = 1,
.port_power_off = 1,
};
static struct platform_device ath79_ehci_device = {
.name = "ehci-platform",
.id = -1,
.resource = ath79_ehci_resources,
.num_resources = ARRAY_SIZE(ath79_ehci_resources),
.dev = {
.dma_mask = &ath79_ehci_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
#define AR71XX_USB_RESET_MASK (AR71XX_RESET_USB_HOST | \
AR71XX_RESET_USB_PHY | \
AR71XX_RESET_USB_OHCI_DLL)
static void __init ath79_usb_setup(void)
{
void __iomem *usb_ctrl_base;
ath79_device_reset_set(AR71XX_USB_RESET_MASK);
mdelay(1000);
ath79_device_reset_clear(AR71XX_USB_RESET_MASK);
usb_ctrl_base = ioremap(AR71XX_USB_CTRL_BASE, AR71XX_USB_CTRL_SIZE);
/* Turning on the Buff and Desc swap bits */
__raw_writel(0xf0000, usb_ctrl_base + AR71XX_USB_CTRL_REG_CONFIG);
/* WAR for HW bug. Here it adjusts the duration between two SOFS */
__raw_writel(0x20c00, usb_ctrl_base + AR71XX_USB_CTRL_REG_FLADJ);
iounmap(usb_ctrl_base);
mdelay(900);
ath79_ohci_resources[0].start = AR71XX_OHCI_BASE;
ath79_ohci_resources[0].end = AR71XX_OHCI_BASE + AR71XX_OHCI_SIZE - 1;
platform_device_register(&ath79_ohci_device);
ath79_ehci_resources[0].start = AR71XX_EHCI_BASE;
ath79_ehci_resources[0].end = AR71XX_EHCI_BASE + AR71XX_EHCI_SIZE - 1;
ath79_ehci_device.dev.platform_data = &ath79_ehci_pdata_v1;
platform_device_register(&ath79_ehci_device);
}
static void __init ar7240_usb_setup(void)
{
void __iomem *usb_ctrl_base;
ath79_device_reset_clear(AR7240_RESET_OHCI_DLL);
ath79_device_reset_set(AR7240_RESET_USB_HOST);
mdelay(1000);
ath79_device_reset_set(AR7240_RESET_OHCI_DLL);
ath79_device_reset_clear(AR7240_RESET_USB_HOST);
usb_ctrl_base = ioremap(AR7240_USB_CTRL_BASE, AR7240_USB_CTRL_SIZE);
/* WAR for HW bug. Here it adjusts the duration between two SOFS */
__raw_writel(0x3, usb_ctrl_base + AR71XX_USB_CTRL_REG_FLADJ);
iounmap(usb_ctrl_base);
ath79_ohci_resources[0].start = AR7240_OHCI_BASE;
ath79_ohci_resources[0].end = AR7240_OHCI_BASE + AR7240_OHCI_SIZE - 1;
platform_device_register(&ath79_ohci_device);
}
static void __init ar724x_usb_setup(void)
{
ath79_device_reset_set(AR724X_RESET_USBSUS_OVERRIDE);
mdelay(10);
ath79_device_reset_clear(AR724X_RESET_USB_HOST);
mdelay(10);
ath79_device_reset_clear(AR724X_RESET_USB_PHY);
mdelay(10);
ath79_ehci_resources[0].start = AR724X_EHCI_BASE;
ath79_ehci_resources[0].end = AR724X_EHCI_BASE + AR724X_EHCI_SIZE - 1;
ath79_ehci_device.dev.platform_data = &ath79_ehci_pdata_v2;
platform_device_register(&ath79_ehci_device);
}
static void __init ar913x_usb_setup(void)
{
ath79_device_reset_set(AR913X_RESET_USBSUS_OVERRIDE);
mdelay(10);
ath79_device_reset_clear(AR913X_RESET_USB_HOST);
mdelay(10);
ath79_device_reset_clear(AR913X_RESET_USB_PHY);
mdelay(10);
ath79_ehci_resources[0].start = AR913X_EHCI_BASE;
ath79_ehci_resources[0].end = AR913X_EHCI_BASE + AR913X_EHCI_SIZE - 1;
ath79_ehci_device.dev.platform_data = &ath79_ehci_pdata_v2;
platform_device_register(&ath79_ehci_device);
}
static void __init ar933x_usb_setup(void)
{
ath79_device_reset_set(AR933X_RESET_USBSUS_OVERRIDE);
mdelay(10);
ath79_device_reset_clear(AR933X_RESET_USB_HOST);
mdelay(10);
ath79_device_reset_clear(AR933X_RESET_USB_PHY);
mdelay(10);
ath79_ehci_resources[0].start = AR933X_EHCI_BASE;
ath79_ehci_resources[0].end = AR933X_EHCI_BASE + AR933X_EHCI_SIZE - 1;
ath79_ehci_device.dev.platform_data = &ath79_ehci_pdata_v2;
platform_device_register(&ath79_ehci_device);
}
void __init ath79_register_usb(void)
{
if (soc_is_ar71xx())
ath79_usb_setup();
else if (soc_is_ar7240())
ar7240_usb_setup();
else if (soc_is_ar7241() || soc_is_ar7242())
ar724x_usb_setup();
else if (soc_is_ar913x())
ar913x_usb_setup();
else if (soc_is_ar933x())
ar933x_usb_setup();
else
BUG();
}
| gpl-2.0 |
WildfireDEV/s6 | arch/mips/oprofile/op_model_loongson2.c | 4740 | 4220 | /*
* Loongson2 performance counter driver for oprofile
*
* Copyright (C) 2009 Lemote Inc.
* Author: Yanhua <yanh@lemote.com>
* Author: Wu Zhangjin <wuzhangjin@gmail.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/oprofile.h>
#include <linux/interrupt.h>
#include <loongson.h> /* LOONGSON2_PERFCNT_IRQ */
#include "op_impl.h"
#define LOONGSON2_CPU_TYPE "mips/loongson2"
#define LOONGSON2_PERFCNT_OVERFLOW (1ULL << 31)
#define LOONGSON2_PERFCTRL_EXL (1UL << 0)
#define LOONGSON2_PERFCTRL_KERNEL (1UL << 1)
#define LOONGSON2_PERFCTRL_SUPERVISOR (1UL << 2)
#define LOONGSON2_PERFCTRL_USER (1UL << 3)
#define LOONGSON2_PERFCTRL_ENABLE (1UL << 4)
#define LOONGSON2_PERFCTRL_EVENT(idx, event) \
(((event) & 0x0f) << ((idx) ? 9 : 5))
#define read_c0_perfctrl() __read_64bit_c0_register($24, 0)
#define write_c0_perfctrl(val) __write_64bit_c0_register($24, 0, val)
#define read_c0_perfcnt() __read_64bit_c0_register($25, 0)
#define write_c0_perfcnt(val) __write_64bit_c0_register($25, 0, val)
static struct loongson2_register_config {
unsigned int ctrl;
unsigned long long reset_counter1;
unsigned long long reset_counter2;
int cnt1_enabled, cnt2_enabled;
} reg;
static char *oprofid = "LoongsonPerf";
static irqreturn_t loongson2_perfcount_handler(int irq, void *dev_id);
static void reset_counters(void *arg)
{
write_c0_perfctrl(0);
write_c0_perfcnt(0);
}
static void loongson2_reg_setup(struct op_counter_config *cfg)
{
unsigned int ctrl = 0;
reg.reset_counter1 = 0;
reg.reset_counter2 = 0;
/*
* Compute the performance counter ctrl word.
* For now, count kernel and user mode.
*/
if (cfg[0].enabled) {
ctrl |= LOONGSON2_PERFCTRL_EVENT(0, cfg[0].event);
reg.reset_counter1 = 0x80000000ULL - cfg[0].count;
}
if (cfg[1].enabled) {
ctrl |= LOONGSON2_PERFCTRL_EVENT(1, cfg[1].event);
reg.reset_counter2 = 0x80000000ULL - cfg[1].count;
}
if (cfg[0].enabled || cfg[1].enabled) {
ctrl |= LOONGSON2_PERFCTRL_EXL | LOONGSON2_PERFCTRL_ENABLE;
if (cfg[0].kernel || cfg[1].kernel)
ctrl |= LOONGSON2_PERFCTRL_KERNEL;
if (cfg[0].user || cfg[1].user)
ctrl |= LOONGSON2_PERFCTRL_USER;
}
reg.ctrl = ctrl;
reg.cnt1_enabled = cfg[0].enabled;
reg.cnt2_enabled = cfg[1].enabled;
}
static void loongson2_cpu_setup(void *args)
{
write_c0_perfcnt((reg.reset_counter2 << 32) | reg.reset_counter1);
}
static void loongson2_cpu_start(void *args)
{
/* Start all counters on current CPU */
if (reg.cnt1_enabled || reg.cnt2_enabled)
write_c0_perfctrl(reg.ctrl);
}
static void loongson2_cpu_stop(void *args)
{
/* Stop all counters on current CPU */
write_c0_perfctrl(0);
memset(®, 0, sizeof(reg));
}
static irqreturn_t loongson2_perfcount_handler(int irq, void *dev_id)
{
uint64_t counter, counter1, counter2;
struct pt_regs *regs = get_irq_regs();
int enabled;
/* Check whether the irq belongs to me */
enabled = read_c0_perfctrl() & LOONGSON2_PERFCTRL_ENABLE;
if (!enabled)
return IRQ_NONE;
enabled = reg.cnt1_enabled | reg.cnt2_enabled;
if (!enabled)
return IRQ_NONE;
counter = read_c0_perfcnt();
counter1 = counter & 0xffffffff;
counter2 = counter >> 32;
if (counter1 & LOONGSON2_PERFCNT_OVERFLOW) {
if (reg.cnt1_enabled)
oprofile_add_sample(regs, 0);
counter1 = reg.reset_counter1;
}
if (counter2 & LOONGSON2_PERFCNT_OVERFLOW) {
if (reg.cnt2_enabled)
oprofile_add_sample(regs, 1);
counter2 = reg.reset_counter2;
}
write_c0_perfcnt((counter2 << 32) | counter1);
return IRQ_HANDLED;
}
static int __init loongson2_init(void)
{
return request_irq(LOONGSON2_PERFCNT_IRQ, loongson2_perfcount_handler,
IRQF_SHARED, "Perfcounter", oprofid);
}
static void loongson2_exit(void)
{
reset_counters(NULL);
free_irq(LOONGSON2_PERFCNT_IRQ, oprofid);
}
struct op_mips_model op_model_loongson2_ops = {
.reg_setup = loongson2_reg_setup,
.cpu_setup = loongson2_cpu_setup,
.init = loongson2_init,
.exit = loongson2_exit,
.cpu_start = loongson2_cpu_start,
.cpu_stop = loongson2_cpu_stop,
.cpu_type = LOONGSON2_CPU_TYPE,
.num_counters = 2
};
| gpl-2.0 |
TeamExodus/kernel_htc_flounder | net/ipv6/netfilter/ip6t_frag.c | 4996 | 3983 | /* Kernel module to match FRAG parameters. */
/* (C) 2001-2002 Andras Kis-Szabo <kisza@sch.bme.hu>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ipv6.h>
#include <linux/types.h>
#include <net/checksum.h>
#include <net/ipv6.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter_ipv6/ip6t_frag.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Xtables: IPv6 fragment match");
MODULE_AUTHOR("Andras Kis-Szabo <kisza@sch.bme.hu>");
/* Returns 1 if the id is matched by the range, 0 otherwise */
static inline bool
id_match(u_int32_t min, u_int32_t max, u_int32_t id, bool invert)
{
bool r;
pr_debug("id_match:%c 0x%x <= 0x%x <= 0x%x\n", invert ? '!' : ' ',
min, id, max);
r = (id >= min && id <= max) ^ invert;
pr_debug(" result %s\n", r ? "PASS" : "FAILED");
return r;
}
static bool
frag_mt6(const struct sk_buff *skb, struct xt_action_param *par)
{
struct frag_hdr _frag;
const struct frag_hdr *fh;
const struct ip6t_frag *fraginfo = par->matchinfo;
unsigned int ptr = 0;
int err;
err = ipv6_find_hdr(skb, &ptr, NEXTHDR_FRAGMENT, NULL, NULL);
if (err < 0) {
if (err != -ENOENT)
par->hotdrop = true;
return false;
}
fh = skb_header_pointer(skb, ptr, sizeof(_frag), &_frag);
if (fh == NULL) {
par->hotdrop = true;
return false;
}
pr_debug("INFO %04X ", fh->frag_off);
pr_debug("OFFSET %04X ", ntohs(fh->frag_off) & ~0x7);
pr_debug("RES %02X %04X", fh->reserved, ntohs(fh->frag_off) & 0x6);
pr_debug("MF %04X ", fh->frag_off & htons(IP6_MF));
pr_debug("ID %u %08X\n", ntohl(fh->identification),
ntohl(fh->identification));
pr_debug("IPv6 FRAG id %02X ",
id_match(fraginfo->ids[0], fraginfo->ids[1],
ntohl(fh->identification),
!!(fraginfo->invflags & IP6T_FRAG_INV_IDS)));
pr_debug("res %02X %02X%04X %02X ",
fraginfo->flags & IP6T_FRAG_RES, fh->reserved,
ntohs(fh->frag_off) & 0x6,
!((fraginfo->flags & IP6T_FRAG_RES) &&
(fh->reserved || (ntohs(fh->frag_off) & 0x06))));
pr_debug("first %02X %02X %02X ",
fraginfo->flags & IP6T_FRAG_FST,
ntohs(fh->frag_off) & ~0x7,
!((fraginfo->flags & IP6T_FRAG_FST) &&
(ntohs(fh->frag_off) & ~0x7)));
pr_debug("mf %02X %02X %02X ",
fraginfo->flags & IP6T_FRAG_MF,
ntohs(fh->frag_off) & IP6_MF,
!((fraginfo->flags & IP6T_FRAG_MF) &&
!((ntohs(fh->frag_off) & IP6_MF))));
pr_debug("last %02X %02X %02X\n",
fraginfo->flags & IP6T_FRAG_NMF,
ntohs(fh->frag_off) & IP6_MF,
!((fraginfo->flags & IP6T_FRAG_NMF) &&
(ntohs(fh->frag_off) & IP6_MF)));
return (fh != NULL) &&
id_match(fraginfo->ids[0], fraginfo->ids[1],
ntohl(fh->identification),
!!(fraginfo->invflags & IP6T_FRAG_INV_IDS)) &&
!((fraginfo->flags & IP6T_FRAG_RES) &&
(fh->reserved || (ntohs(fh->frag_off) & 0x6))) &&
!((fraginfo->flags & IP6T_FRAG_FST) &&
(ntohs(fh->frag_off) & ~0x7)) &&
!((fraginfo->flags & IP6T_FRAG_MF) &&
!(ntohs(fh->frag_off) & IP6_MF)) &&
!((fraginfo->flags & IP6T_FRAG_NMF) &&
(ntohs(fh->frag_off) & IP6_MF));
}
static int frag_mt6_check(const struct xt_mtchk_param *par)
{
const struct ip6t_frag *fraginfo = par->matchinfo;
if (fraginfo->invflags & ~IP6T_FRAG_INV_MASK) {
pr_debug("unknown flags %X\n", fraginfo->invflags);
return -EINVAL;
}
return 0;
}
static struct xt_match frag_mt6_reg __read_mostly = {
.name = "frag",
.family = NFPROTO_IPV6,
.match = frag_mt6,
.matchsize = sizeof(struct ip6t_frag),
.checkentry = frag_mt6_check,
.me = THIS_MODULE,
};
static int __init frag_mt6_init(void)
{
return xt_register_match(&frag_mt6_reg);
}
static void __exit frag_mt6_exit(void)
{
xt_unregister_match(&frag_mt6_reg);
}
module_init(frag_mt6_init);
module_exit(frag_mt6_exit);
| gpl-2.0 |
kuailexs/Lenovo_A820_kernel_kk | kernel/drivers/input/touchscreen/s3c2410_ts.c | 4996 | 11211 | /*
* Samsung S3C24XX touchscreen driver
*
* This program is free software; you can redistribute it and/or modify
* it under the term 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
*
* Copyright 2004 Arnaud Patard <arnaud.patard@rtp-net.org>
* Copyright 2008 Ben Dooks <ben-linux@fluff.org>
* Copyright 2009 Simtec Electronics <linux@simtec.co.uk>
*
* Additional work by Herbert Pötzl <herbert@13thfloor.at> and
* Harald Welte <laforge@openmoko.org>
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/gpio.h>
#include <linux/input.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <plat/adc.h>
#include <plat/regs-adc.h>
#include <plat/ts.h>
#define TSC_SLEEP (S3C2410_ADCTSC_PULL_UP_DISABLE | S3C2410_ADCTSC_XY_PST(0))
#define INT_DOWN (0)
#define INT_UP (1 << 8)
#define WAIT4INT (S3C2410_ADCTSC_YM_SEN | \
S3C2410_ADCTSC_YP_SEN | \
S3C2410_ADCTSC_XP_SEN | \
S3C2410_ADCTSC_XY_PST(3))
#define AUTOPST (S3C2410_ADCTSC_YM_SEN | \
S3C2410_ADCTSC_YP_SEN | \
S3C2410_ADCTSC_XP_SEN | \
S3C2410_ADCTSC_AUTO_PST | \
S3C2410_ADCTSC_XY_PST(0))
#define FEAT_PEN_IRQ (1 << 0) /* HAS ADCCLRINTPNDNUP */
/* Per-touchscreen data. */
/**
* struct s3c2410ts - driver touchscreen state.
* @client: The ADC client we registered with the core driver.
* @dev: The device we are bound to.
* @input: The input device we registered with the input subsystem.
* @clock: The clock for the adc.
* @io: Pointer to the IO base.
* @xp: The accumulated X position data.
* @yp: The accumulated Y position data.
* @irq_tc: The interrupt number for pen up/down interrupt
* @count: The number of samples collected.
* @shift: The log2 of the maximum count to read in one go.
* @features: The features supported by the TSADC MOdule.
*/
struct s3c2410ts {
struct s3c_adc_client *client;
struct device *dev;
struct input_dev *input;
struct clk *clock;
void __iomem *io;
unsigned long xp;
unsigned long yp;
int irq_tc;
int count;
int shift;
int features;
};
static struct s3c2410ts ts;
/**
* get_down - return the down state of the pen
* @data0: The data read from ADCDAT0 register.
* @data1: The data read from ADCDAT1 register.
*
* Return non-zero if both readings show that the pen is down.
*/
static inline bool get_down(unsigned long data0, unsigned long data1)
{
/* returns true if both data values show stylus down */
return (!(data0 & S3C2410_ADCDAT0_UPDOWN) &&
!(data1 & S3C2410_ADCDAT0_UPDOWN));
}
static void touch_timer_fire(unsigned long data)
{
unsigned long data0;
unsigned long data1;
bool down;
data0 = readl(ts.io + S3C2410_ADCDAT0);
data1 = readl(ts.io + S3C2410_ADCDAT1);
down = get_down(data0, data1);
if (down) {
if (ts.count == (1 << ts.shift)) {
ts.xp >>= ts.shift;
ts.yp >>= ts.shift;
dev_dbg(ts.dev, "%s: X=%lu, Y=%lu, count=%d\n",
__func__, ts.xp, ts.yp, ts.count);
input_report_abs(ts.input, ABS_X, ts.xp);
input_report_abs(ts.input, ABS_Y, ts.yp);
input_report_key(ts.input, BTN_TOUCH, 1);
input_sync(ts.input);
ts.xp = 0;
ts.yp = 0;
ts.count = 0;
}
s3c_adc_start(ts.client, 0, 1 << ts.shift);
} else {
ts.xp = 0;
ts.yp = 0;
ts.count = 0;
input_report_key(ts.input, BTN_TOUCH, 0);
input_sync(ts.input);
writel(WAIT4INT | INT_DOWN, ts.io + S3C2410_ADCTSC);
}
}
static DEFINE_TIMER(touch_timer, touch_timer_fire, 0, 0);
/**
* stylus_irq - touchscreen stylus event interrupt
* @irq: The interrupt number
* @dev_id: The device ID.
*
* Called when the IRQ_TC is fired for a pen up or down event.
*/
static irqreturn_t stylus_irq(int irq, void *dev_id)
{
unsigned long data0;
unsigned long data1;
bool down;
data0 = readl(ts.io + S3C2410_ADCDAT0);
data1 = readl(ts.io + S3C2410_ADCDAT1);
down = get_down(data0, data1);
/* TODO we should never get an interrupt with down set while
* the timer is running, but maybe we ought to verify that the
* timer isn't running anyways. */
if (down)
s3c_adc_start(ts.client, 0, 1 << ts.shift);
else
dev_dbg(ts.dev, "%s: count=%d\n", __func__, ts.count);
if (ts.features & FEAT_PEN_IRQ) {
/* Clear pen down/up interrupt */
writel(0x0, ts.io + S3C64XX_ADCCLRINTPNDNUP);
}
return IRQ_HANDLED;
}
/**
* s3c24xx_ts_conversion - ADC conversion callback
* @client: The client that was registered with the ADC core.
* @data0: The reading from ADCDAT0.
* @data1: The reading from ADCDAT1.
* @left: The number of samples left.
*
* Called when a conversion has finished.
*/
static void s3c24xx_ts_conversion(struct s3c_adc_client *client,
unsigned data0, unsigned data1,
unsigned *left)
{
dev_dbg(ts.dev, "%s: %d,%d\n", __func__, data0, data1);
ts.xp += data0;
ts.yp += data1;
ts.count++;
/* From tests, it seems that it is unlikely to get a pen-up
* event during the conversion process which means we can
* ignore any pen-up events with less than the requisite
* count done.
*
* In several thousand conversions, no pen-ups where detected
* before count completed.
*/
}
/**
* s3c24xx_ts_select - ADC selection callback.
* @client: The client that was registered with the ADC core.
* @select: The reason for select.
*
* Called when the ADC core selects (or deslects) us as a client.
*/
static void s3c24xx_ts_select(struct s3c_adc_client *client, unsigned select)
{
if (select) {
writel(S3C2410_ADCTSC_PULL_UP_DISABLE | AUTOPST,
ts.io + S3C2410_ADCTSC);
} else {
mod_timer(&touch_timer, jiffies+1);
writel(WAIT4INT | INT_UP, ts.io + S3C2410_ADCTSC);
}
}
/**
* s3c2410ts_probe - device core probe entry point
* @pdev: The device we are being bound to.
*
* Initialise, find and allocate any resources we need to run and then
* register with the ADC and input systems.
*/
static int __devinit s3c2410ts_probe(struct platform_device *pdev)
{
struct s3c2410_ts_mach_info *info;
struct device *dev = &pdev->dev;
struct input_dev *input_dev;
struct resource *res;
int ret = -EINVAL;
/* Initialise input stuff */
memset(&ts, 0, sizeof(struct s3c2410ts));
ts.dev = dev;
info = pdev->dev.platform_data;
if (!info) {
dev_err(dev, "no platform data, cannot attach\n");
return -EINVAL;
}
dev_dbg(dev, "initialising touchscreen\n");
ts.clock = clk_get(dev, "adc");
if (IS_ERR(ts.clock)) {
dev_err(dev, "cannot get adc clock source\n");
return -ENOENT;
}
clk_enable(ts.clock);
dev_dbg(dev, "got and enabled clocks\n");
ts.irq_tc = ret = platform_get_irq(pdev, 0);
if (ret < 0) {
dev_err(dev, "no resource for interrupt\n");
goto err_clk;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(dev, "no resource for registers\n");
ret = -ENOENT;
goto err_clk;
}
ts.io = ioremap(res->start, resource_size(res));
if (ts.io == NULL) {
dev_err(dev, "cannot map registers\n");
ret = -ENOMEM;
goto err_clk;
}
/* inititalise the gpio */
if (info->cfg_gpio)
info->cfg_gpio(to_platform_device(ts.dev));
ts.client = s3c_adc_register(pdev, s3c24xx_ts_select,
s3c24xx_ts_conversion, 1);
if (IS_ERR(ts.client)) {
dev_err(dev, "failed to register adc client\n");
ret = PTR_ERR(ts.client);
goto err_iomap;
}
/* Initialise registers */
if ((info->delay & 0xffff) > 0)
writel(info->delay & 0xffff, ts.io + S3C2410_ADCDLY);
writel(WAIT4INT | INT_DOWN, ts.io + S3C2410_ADCTSC);
input_dev = input_allocate_device();
if (!input_dev) {
dev_err(dev, "Unable to allocate the input device !!\n");
ret = -ENOMEM;
goto err_iomap;
}
ts.input = input_dev;
ts.input->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
ts.input->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(ts.input, ABS_X, 0, 0x3FF, 0, 0);
input_set_abs_params(ts.input, ABS_Y, 0, 0x3FF, 0, 0);
ts.input->name = "S3C24XX TouchScreen";
ts.input->id.bustype = BUS_HOST;
ts.input->id.vendor = 0xDEAD;
ts.input->id.product = 0xBEEF;
ts.input->id.version = 0x0102;
ts.shift = info->oversampling_shift;
ts.features = platform_get_device_id(pdev)->driver_data;
ret = request_irq(ts.irq_tc, stylus_irq, 0,
"s3c2410_ts_pen", ts.input);
if (ret) {
dev_err(dev, "cannot get TC interrupt\n");
goto err_inputdev;
}
dev_info(dev, "driver attached, registering input device\n");
/* All went ok, so register to the input system */
ret = input_register_device(ts.input);
if (ret < 0) {
dev_err(dev, "failed to register input device\n");
ret = -EIO;
goto err_tcirq;
}
return 0;
err_tcirq:
free_irq(ts.irq_tc, ts.input);
err_inputdev:
input_free_device(ts.input);
err_iomap:
iounmap(ts.io);
err_clk:
del_timer_sync(&touch_timer);
clk_put(ts.clock);
return ret;
}
/**
* s3c2410ts_remove - device core removal entry point
* @pdev: The device we are being removed from.
*
* Free up our state ready to be removed.
*/
static int __devexit s3c2410ts_remove(struct platform_device *pdev)
{
free_irq(ts.irq_tc, ts.input);
del_timer_sync(&touch_timer);
clk_disable(ts.clock);
clk_put(ts.clock);
input_unregister_device(ts.input);
iounmap(ts.io);
return 0;
}
#ifdef CONFIG_PM
static int s3c2410ts_suspend(struct device *dev)
{
writel(TSC_SLEEP, ts.io + S3C2410_ADCTSC);
disable_irq(ts.irq_tc);
clk_disable(ts.clock);
return 0;
}
static int s3c2410ts_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct s3c2410_ts_mach_info *info = pdev->dev.platform_data;
clk_enable(ts.clock);
enable_irq(ts.irq_tc);
/* Initialise registers */
if ((info->delay & 0xffff) > 0)
writel(info->delay & 0xffff, ts.io + S3C2410_ADCDLY);
writel(WAIT4INT | INT_DOWN, ts.io + S3C2410_ADCTSC);
return 0;
}
static struct dev_pm_ops s3c_ts_pmops = {
.suspend = s3c2410ts_suspend,
.resume = s3c2410ts_resume,
};
#endif
static struct platform_device_id s3cts_driver_ids[] = {
{ "s3c2410-ts", 0 },
{ "s3c2440-ts", 0 },
{ "s3c64xx-ts", FEAT_PEN_IRQ },
{ }
};
MODULE_DEVICE_TABLE(platform, s3cts_driver_ids);
static struct platform_driver s3c_ts_driver = {
.driver = {
.name = "samsung-ts",
.owner = THIS_MODULE,
#ifdef CONFIG_PM
.pm = &s3c_ts_pmops,
#endif
},
.id_table = s3cts_driver_ids,
.probe = s3c2410ts_probe,
.remove = __devexit_p(s3c2410ts_remove),
};
module_platform_driver(s3c_ts_driver);
MODULE_AUTHOR("Arnaud Patard <arnaud.patard@rtp-net.org>, "
"Ben Dooks <ben@simtec.co.uk>, "
"Simtec Electronics <linux@simtec.co.uk>");
MODULE_DESCRIPTION("S3C24XX Touchscreen driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
kazukioishi/android_kernel_samsung_klte | drivers/ata/sata_vsc.c | 5508 | 12415 | /*
* sata_vsc.c - Vitesse VSC7174 4 port DPA SATA
*
* Maintained by: Jeremy Higdon @ SGI
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2004 SGI
*
* Bits from Jeff Garzik, Copyright RedHat, Inc.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* Vitesse hardware documentation presumably available under NDA.
* Intel 31244 (same hardware interface) documentation presumably
* available from http://developer.intel.com/
*
*/
#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/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "sata_vsc"
#define DRV_VERSION "2.3"
enum {
VSC_MMIO_BAR = 0,
/* Interrupt register offsets (from chip base address) */
VSC_SATA_INT_STAT_OFFSET = 0x00,
VSC_SATA_INT_MASK_OFFSET = 0x04,
/* Taskfile registers offsets */
VSC_SATA_TF_CMD_OFFSET = 0x00,
VSC_SATA_TF_DATA_OFFSET = 0x00,
VSC_SATA_TF_ERROR_OFFSET = 0x04,
VSC_SATA_TF_FEATURE_OFFSET = 0x06,
VSC_SATA_TF_NSECT_OFFSET = 0x08,
VSC_SATA_TF_LBAL_OFFSET = 0x0c,
VSC_SATA_TF_LBAM_OFFSET = 0x10,
VSC_SATA_TF_LBAH_OFFSET = 0x14,
VSC_SATA_TF_DEVICE_OFFSET = 0x18,
VSC_SATA_TF_STATUS_OFFSET = 0x1c,
VSC_SATA_TF_COMMAND_OFFSET = 0x1d,
VSC_SATA_TF_ALTSTATUS_OFFSET = 0x28,
VSC_SATA_TF_CTL_OFFSET = 0x29,
/* DMA base */
VSC_SATA_UP_DESCRIPTOR_OFFSET = 0x64,
VSC_SATA_UP_DATA_BUFFER_OFFSET = 0x6C,
VSC_SATA_DMA_CMD_OFFSET = 0x70,
/* SCRs base */
VSC_SATA_SCR_STATUS_OFFSET = 0x100,
VSC_SATA_SCR_ERROR_OFFSET = 0x104,
VSC_SATA_SCR_CONTROL_OFFSET = 0x108,
/* Port stride */
VSC_SATA_PORT_OFFSET = 0x200,
/* Error interrupt status bit offsets */
VSC_SATA_INT_ERROR_CRC = 0x40,
VSC_SATA_INT_ERROR_T = 0x20,
VSC_SATA_INT_ERROR_P = 0x10,
VSC_SATA_INT_ERROR_R = 0x8,
VSC_SATA_INT_ERROR_E = 0x4,
VSC_SATA_INT_ERROR_M = 0x2,
VSC_SATA_INT_PHY_CHANGE = 0x1,
VSC_SATA_INT_ERROR = (VSC_SATA_INT_ERROR_CRC | VSC_SATA_INT_ERROR_T | \
VSC_SATA_INT_ERROR_P | VSC_SATA_INT_ERROR_R | \
VSC_SATA_INT_ERROR_E | VSC_SATA_INT_ERROR_M | \
VSC_SATA_INT_PHY_CHANGE),
};
static int vsc_sata_scr_read(struct ata_link *link,
unsigned int sc_reg, u32 *val)
{
if (sc_reg > SCR_CONTROL)
return -EINVAL;
*val = readl(link->ap->ioaddr.scr_addr + (sc_reg * 4));
return 0;
}
static int vsc_sata_scr_write(struct ata_link *link,
unsigned int sc_reg, u32 val)
{
if (sc_reg > SCR_CONTROL)
return -EINVAL;
writel(val, link->ap->ioaddr.scr_addr + (sc_reg * 4));
return 0;
}
static void vsc_freeze(struct ata_port *ap)
{
void __iomem *mask_addr;
mask_addr = ap->host->iomap[VSC_MMIO_BAR] +
VSC_SATA_INT_MASK_OFFSET + ap->port_no;
writeb(0, mask_addr);
}
static void vsc_thaw(struct ata_port *ap)
{
void __iomem *mask_addr;
mask_addr = ap->host->iomap[VSC_MMIO_BAR] +
VSC_SATA_INT_MASK_OFFSET + ap->port_no;
writeb(0xff, mask_addr);
}
static void vsc_intr_mask_update(struct ata_port *ap, u8 ctl)
{
void __iomem *mask_addr;
u8 mask;
mask_addr = ap->host->iomap[VSC_MMIO_BAR] +
VSC_SATA_INT_MASK_OFFSET + ap->port_no;
mask = readb(mask_addr);
if (ctl & ATA_NIEN)
mask |= 0x80;
else
mask &= 0x7F;
writeb(mask, mask_addr);
}
static void vsc_sata_tf_load(struct ata_port *ap, const struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
/*
* The only thing the ctl register is used for is SRST.
* That is not enabled or disabled via tf_load.
* However, if ATA_NIEN is changed, then we need to change
* the interrupt register.
*/
if ((tf->ctl & ATA_NIEN) != (ap->last_ctl & ATA_NIEN)) {
ap->last_ctl = tf->ctl;
vsc_intr_mask_update(ap, tf->ctl & ATA_NIEN);
}
if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
writew(tf->feature | (((u16)tf->hob_feature) << 8),
ioaddr->feature_addr);
writew(tf->nsect | (((u16)tf->hob_nsect) << 8),
ioaddr->nsect_addr);
writew(tf->lbal | (((u16)tf->hob_lbal) << 8),
ioaddr->lbal_addr);
writew(tf->lbam | (((u16)tf->hob_lbam) << 8),
ioaddr->lbam_addr);
writew(tf->lbah | (((u16)tf->hob_lbah) << 8),
ioaddr->lbah_addr);
} else if (is_addr) {
writew(tf->feature, ioaddr->feature_addr);
writew(tf->nsect, ioaddr->nsect_addr);
writew(tf->lbal, ioaddr->lbal_addr);
writew(tf->lbam, ioaddr->lbam_addr);
writew(tf->lbah, ioaddr->lbah_addr);
}
if (tf->flags & ATA_TFLAG_DEVICE)
writeb(tf->device, ioaddr->device_addr);
ata_wait_idle(ap);
}
static void vsc_sata_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
u16 nsect, lbal, lbam, lbah, feature;
tf->command = ata_sff_check_status(ap);
tf->device = readw(ioaddr->device_addr);
feature = readw(ioaddr->error_addr);
nsect = readw(ioaddr->nsect_addr);
lbal = readw(ioaddr->lbal_addr);
lbam = readw(ioaddr->lbam_addr);
lbah = readw(ioaddr->lbah_addr);
tf->feature = feature;
tf->nsect = nsect;
tf->lbal = lbal;
tf->lbam = lbam;
tf->lbah = lbah;
if (tf->flags & ATA_TFLAG_LBA48) {
tf->hob_feature = feature >> 8;
tf->hob_nsect = nsect >> 8;
tf->hob_lbal = lbal >> 8;
tf->hob_lbam = lbam >> 8;
tf->hob_lbah = lbah >> 8;
}
}
static inline void vsc_error_intr(u8 port_status, struct ata_port *ap)
{
if (port_status & (VSC_SATA_INT_PHY_CHANGE | VSC_SATA_INT_ERROR_M))
ata_port_freeze(ap);
else
ata_port_abort(ap);
}
static void vsc_port_intr(u8 port_status, struct ata_port *ap)
{
struct ata_queued_cmd *qc;
int handled = 0;
if (unlikely(port_status & VSC_SATA_INT_ERROR)) {
vsc_error_intr(port_status, ap);
return;
}
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && likely(!(qc->tf.flags & ATA_TFLAG_POLLING)))
handled = ata_bmdma_port_intr(ap, qc);
/* We received an interrupt during a polled command,
* or some other spurious condition. Interrupt reporting
* with this hardware is fairly reliable so it is safe to
* simply clear the interrupt
*/
if (unlikely(!handled))
ap->ops->sff_check_status(ap);
}
/*
* vsc_sata_interrupt
*
* Read the interrupt register and process for the devices that have
* them pending.
*/
static irqreturn_t vsc_sata_interrupt(int irq, void *dev_instance)
{
struct ata_host *host = dev_instance;
unsigned int i;
unsigned int handled = 0;
u32 status;
status = readl(host->iomap[VSC_MMIO_BAR] + VSC_SATA_INT_STAT_OFFSET);
if (unlikely(status == 0xffffffff || status == 0)) {
if (status)
dev_err(host->dev,
": IRQ status == 0xffffffff, PCI fault or device removal?\n");
goto out;
}
spin_lock(&host->lock);
for (i = 0; i < host->n_ports; i++) {
u8 port_status = (status >> (8 * i)) & 0xff;
if (port_status) {
vsc_port_intr(port_status, host->ports[i]);
handled++;
}
}
spin_unlock(&host->lock);
out:
return IRQ_RETVAL(handled);
}
static struct scsi_host_template vsc_sata_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations vsc_sata_ops = {
.inherits = &ata_bmdma_port_ops,
/* The IRQ handling is not quite standard SFF behaviour so we
cannot use the default lost interrupt handler */
.lost_interrupt = ATA_OP_NULL,
.sff_tf_load = vsc_sata_tf_load,
.sff_tf_read = vsc_sata_tf_read,
.freeze = vsc_freeze,
.thaw = vsc_thaw,
.scr_read = vsc_sata_scr_read,
.scr_write = vsc_sata_scr_write,
};
static void __devinit vsc_sata_setup_port(struct ata_ioports *port,
void __iomem *base)
{
port->cmd_addr = base + VSC_SATA_TF_CMD_OFFSET;
port->data_addr = base + VSC_SATA_TF_DATA_OFFSET;
port->error_addr = base + VSC_SATA_TF_ERROR_OFFSET;
port->feature_addr = base + VSC_SATA_TF_FEATURE_OFFSET;
port->nsect_addr = base + VSC_SATA_TF_NSECT_OFFSET;
port->lbal_addr = base + VSC_SATA_TF_LBAL_OFFSET;
port->lbam_addr = base + VSC_SATA_TF_LBAM_OFFSET;
port->lbah_addr = base + VSC_SATA_TF_LBAH_OFFSET;
port->device_addr = base + VSC_SATA_TF_DEVICE_OFFSET;
port->status_addr = base + VSC_SATA_TF_STATUS_OFFSET;
port->command_addr = base + VSC_SATA_TF_COMMAND_OFFSET;
port->altstatus_addr = base + VSC_SATA_TF_ALTSTATUS_OFFSET;
port->ctl_addr = base + VSC_SATA_TF_CTL_OFFSET;
port->bmdma_addr = base + VSC_SATA_DMA_CMD_OFFSET;
port->scr_addr = base + VSC_SATA_SCR_STATUS_OFFSET;
writel(0, base + VSC_SATA_UP_DESCRIPTOR_OFFSET);
writel(0, base + VSC_SATA_UP_DATA_BUFFER_OFFSET);
}
static int __devinit vsc_sata_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static const struct ata_port_info pi = {
.flags = ATA_FLAG_SATA,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &vsc_sata_ops,
};
const struct ata_port_info *ppi[] = { &pi, NULL };
struct ata_host *host;
void __iomem *mmio_base;
int i, rc;
u8 cls;
ata_print_version_once(&pdev->dev, DRV_VERSION);
/* allocate host */
host = ata_host_alloc_pinfo(&pdev->dev, ppi, 4);
if (!host)
return -ENOMEM;
rc = pcim_enable_device(pdev);
if (rc)
return rc;
/* check if we have needed resource mapped */
if (pci_resource_len(pdev, 0) == 0)
return -ENODEV;
/* map IO regions and initialize host accordingly */
rc = pcim_iomap_regions(pdev, 1 << VSC_MMIO_BAR, DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(pdev);
if (rc)
return rc;
host->iomap = pcim_iomap_table(pdev);
mmio_base = host->iomap[VSC_MMIO_BAR];
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
unsigned int offset = (i + 1) * VSC_SATA_PORT_OFFSET;
vsc_sata_setup_port(&ap->ioaddr, mmio_base + offset);
ata_port_pbar_desc(ap, VSC_MMIO_BAR, -1, "mmio");
ata_port_pbar_desc(ap, VSC_MMIO_BAR, offset, "port");
}
/*
* Use 32 bit DMA mask, because 64 bit address support is poor.
*/
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc)
return rc;
rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc)
return rc;
/*
* Due to a bug in the chip, the default cache line size can't be
* used (unless the default is non-zero).
*/
pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &cls);
if (cls == 0x00)
pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, 0x80);
if (pci_enable_msi(pdev) == 0)
pci_intx(pdev, 0);
/*
* Config offset 0x98 is "Extended Control and Status Register 0"
* Default value is (1 << 28). All bits except bit 28 are reserved in
* DPA mode. If bit 28 is set, LED 0 reflects all ports' activity.
* If bit 28 is clear, each port has its own LED.
*/
pci_write_config_dword(pdev, 0x98, 0);
pci_set_master(pdev);
return ata_host_activate(host, pdev->irq, vsc_sata_interrupt,
IRQF_SHARED, &vsc_sata_sht);
}
static const struct pci_device_id vsc_sata_pci_tbl[] = {
{ PCI_VENDOR_ID_VITESSE, 0x7174,
PCI_ANY_ID, PCI_ANY_ID, 0x10600, 0xFFFFFF, 0 },
{ PCI_VENDOR_ID_INTEL, 0x3200,
PCI_ANY_ID, PCI_ANY_ID, 0x10600, 0xFFFFFF, 0 },
{ } /* terminate list */
};
static struct pci_driver vsc_sata_pci_driver = {
.name = DRV_NAME,
.id_table = vsc_sata_pci_tbl,
.probe = vsc_sata_init_one,
.remove = ata_pci_remove_one,
};
static int __init vsc_sata_init(void)
{
return pci_register_driver(&vsc_sata_pci_driver);
}
static void __exit vsc_sata_exit(void)
{
pci_unregister_driver(&vsc_sata_pci_driver);
}
MODULE_AUTHOR("Jeremy Higdon");
MODULE_DESCRIPTION("low-level driver for Vitesse VSC7174 SATA controller");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, vsc_sata_pci_tbl);
MODULE_VERSION(DRV_VERSION);
module_init(vsc_sata_init);
module_exit(vsc_sata_exit);
| gpl-2.0 |
fduchene/mptcp-rpi | drivers/ata/sata_sx4.c | 5508 | 40430 | /*
* sata_sx4.c - Promise SATA
*
* Maintained by: Jeff Garzik <jgarzik@pobox.com>
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2003-2004 Red Hat, Inc.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* Hardware documentation available under NDA.
*
*/
/*
Theory of operation
-------------------
The SX4 (PDC20621) chip features a single Host DMA (HDMA) copy
engine, DIMM memory, and four ATA engines (one per SATA port).
Data is copied to/from DIMM memory by the HDMA engine, before
handing off to one (or more) of the ATA engines. The ATA
engines operate solely on DIMM memory.
The SX4 behaves like a PATA chip, with no SATA controls or
knowledge whatsoever, leading to the presumption that
PATA<->SATA bridges exist on SX4 boards, external to the
PDC20621 chip itself.
The chip is quite capable, supporting an XOR engine and linked
hardware commands (permits a string to transactions to be
submitted and waited-on as a single unit), and an optional
microprocessor.
The limiting factor is largely software. This Linux driver was
written to multiplex the single HDMA engine to copy disk
transactions into a fixed DIMM memory space, from where an ATA
engine takes over. As a result, each WRITE looks like this:
submit HDMA packet to hardware
hardware copies data from system memory to DIMM
hardware raises interrupt
submit ATA packet to hardware
hardware executes ATA WRITE command, w/ data in DIMM
hardware raises interrupt
and each READ looks like this:
submit ATA packet to hardware
hardware executes ATA READ command, w/ data in DIMM
hardware raises interrupt
submit HDMA packet to hardware
hardware copies data from DIMM to system memory
hardware raises interrupt
This is a very slow, lock-step way of doing things that can
certainly be improved by motivated kernel hackers.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_cmnd.h>
#include <linux/libata.h>
#include "sata_promise.h"
#define DRV_NAME "sata_sx4"
#define DRV_VERSION "0.12"
enum {
PDC_MMIO_BAR = 3,
PDC_DIMM_BAR = 4,
PDC_PRD_TBL = 0x44, /* Direct command DMA table addr */
PDC_PKT_SUBMIT = 0x40, /* Command packet pointer addr */
PDC_HDMA_PKT_SUBMIT = 0x100, /* Host DMA packet pointer addr */
PDC_INT_SEQMASK = 0x40, /* Mask of asserted SEQ INTs */
PDC_HDMA_CTLSTAT = 0x12C, /* Host DMA control / status */
PDC_CTLSTAT = 0x60, /* IDEn control / status */
PDC_20621_SEQCTL = 0x400,
PDC_20621_SEQMASK = 0x480,
PDC_20621_GENERAL_CTL = 0x484,
PDC_20621_PAGE_SIZE = (32 * 1024),
/* chosen, not constant, values; we design our own DIMM mem map */
PDC_20621_DIMM_WINDOW = 0x0C, /* page# for 32K DIMM window */
PDC_20621_DIMM_BASE = 0x00200000,
PDC_20621_DIMM_DATA = (64 * 1024),
PDC_DIMM_DATA_STEP = (256 * 1024),
PDC_DIMM_WINDOW_STEP = (8 * 1024),
PDC_DIMM_HOST_PRD = (6 * 1024),
PDC_DIMM_HOST_PKT = (128 * 0),
PDC_DIMM_HPKT_PRD = (128 * 1),
PDC_DIMM_ATA_PKT = (128 * 2),
PDC_DIMM_APKT_PRD = (128 * 3),
PDC_DIMM_HEADER_SZ = PDC_DIMM_APKT_PRD + 128,
PDC_PAGE_WINDOW = 0x40,
PDC_PAGE_DATA = PDC_PAGE_WINDOW +
(PDC_20621_DIMM_DATA / PDC_20621_PAGE_SIZE),
PDC_PAGE_SET = PDC_DIMM_DATA_STEP / PDC_20621_PAGE_SIZE,
PDC_CHIP0_OFS = 0xC0000, /* offset of chip #0 */
PDC_20621_ERR_MASK = (1<<19) | (1<<20) | (1<<21) | (1<<22) |
(1<<23),
board_20621 = 0, /* FastTrak S150 SX4 */
PDC_MASK_INT = (1 << 10), /* HDMA/ATA mask int */
PDC_RESET = (1 << 11), /* HDMA/ATA reset */
PDC_DMA_ENABLE = (1 << 7), /* DMA start/stop */
PDC_MAX_HDMA = 32,
PDC_HDMA_Q_MASK = (PDC_MAX_HDMA - 1),
PDC_DIMM0_SPD_DEV_ADDRESS = 0x50,
PDC_DIMM1_SPD_DEV_ADDRESS = 0x51,
PDC_I2C_CONTROL = 0x48,
PDC_I2C_ADDR_DATA = 0x4C,
PDC_DIMM0_CONTROL = 0x80,
PDC_DIMM1_CONTROL = 0x84,
PDC_SDRAM_CONTROL = 0x88,
PDC_I2C_WRITE = 0, /* master -> slave */
PDC_I2C_READ = (1 << 6), /* master <- slave */
PDC_I2C_START = (1 << 7), /* start I2C proto */
PDC_I2C_MASK_INT = (1 << 5), /* mask I2C interrupt */
PDC_I2C_COMPLETE = (1 << 16), /* I2C normal compl. */
PDC_I2C_NO_ACK = (1 << 20), /* slave no-ack addr */
PDC_DIMM_SPD_SUBADDRESS_START = 0x00,
PDC_DIMM_SPD_SUBADDRESS_END = 0x7F,
PDC_DIMM_SPD_ROW_NUM = 3,
PDC_DIMM_SPD_COLUMN_NUM = 4,
PDC_DIMM_SPD_MODULE_ROW = 5,
PDC_DIMM_SPD_TYPE = 11,
PDC_DIMM_SPD_FRESH_RATE = 12,
PDC_DIMM_SPD_BANK_NUM = 17,
PDC_DIMM_SPD_CAS_LATENCY = 18,
PDC_DIMM_SPD_ATTRIBUTE = 21,
PDC_DIMM_SPD_ROW_PRE_CHARGE = 27,
PDC_DIMM_SPD_ROW_ACTIVE_DELAY = 28,
PDC_DIMM_SPD_RAS_CAS_DELAY = 29,
PDC_DIMM_SPD_ACTIVE_PRECHARGE = 30,
PDC_DIMM_SPD_SYSTEM_FREQ = 126,
PDC_CTL_STATUS = 0x08,
PDC_DIMM_WINDOW_CTLR = 0x0C,
PDC_TIME_CONTROL = 0x3C,
PDC_TIME_PERIOD = 0x40,
PDC_TIME_COUNTER = 0x44,
PDC_GENERAL_CTLR = 0x484,
PCI_PLL_INIT = 0x8A531824,
PCI_X_TCOUNT = 0xEE1E5CFF,
/* PDC_TIME_CONTROL bits */
PDC_TIMER_BUZZER = (1 << 10),
PDC_TIMER_MODE_PERIODIC = 0, /* bits 9:8 == 00 */
PDC_TIMER_MODE_ONCE = (1 << 8), /* bits 9:8 == 01 */
PDC_TIMER_ENABLE = (1 << 7),
PDC_TIMER_MASK_INT = (1 << 5),
PDC_TIMER_SEQ_MASK = 0x1f, /* SEQ ID for timer */
PDC_TIMER_DEFAULT = PDC_TIMER_MODE_ONCE |
PDC_TIMER_ENABLE |
PDC_TIMER_MASK_INT,
};
#define ECC_ERASE_BUF_SZ (128 * 1024)
struct pdc_port_priv {
u8 dimm_buf[(ATA_PRD_SZ * ATA_MAX_PRD) + 512];
u8 *pkt;
dma_addr_t pkt_dma;
};
struct pdc_host_priv {
unsigned int doing_hdma;
unsigned int hdma_prod;
unsigned int hdma_cons;
struct {
struct ata_queued_cmd *qc;
unsigned int seq;
unsigned long pkt_ofs;
} hdma[32];
};
static int pdc_sata_init_one(struct pci_dev *pdev, const struct pci_device_id *ent);
static void pdc_error_handler(struct ata_port *ap);
static void pdc_freeze(struct ata_port *ap);
static void pdc_thaw(struct ata_port *ap);
static int pdc_port_start(struct ata_port *ap);
static void pdc20621_qc_prep(struct ata_queued_cmd *qc);
static void pdc_tf_load_mmio(struct ata_port *ap, const struct ata_taskfile *tf);
static void pdc_exec_command_mmio(struct ata_port *ap, const struct ata_taskfile *tf);
static unsigned int pdc20621_dimm_init(struct ata_host *host);
static int pdc20621_detect_dimm(struct ata_host *host);
static unsigned int pdc20621_i2c_read(struct ata_host *host,
u32 device, u32 subaddr, u32 *pdata);
static int pdc20621_prog_dimm0(struct ata_host *host);
static unsigned int pdc20621_prog_dimm_global(struct ata_host *host);
#ifdef ATA_VERBOSE_DEBUG
static void pdc20621_get_from_dimm(struct ata_host *host,
void *psource, u32 offset, u32 size);
#endif
static void pdc20621_put_to_dimm(struct ata_host *host,
void *psource, u32 offset, u32 size);
static void pdc20621_irq_clear(struct ata_port *ap);
static unsigned int pdc20621_qc_issue(struct ata_queued_cmd *qc);
static int pdc_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
static void pdc_post_internal_cmd(struct ata_queued_cmd *qc);
static int pdc_check_atapi_dma(struct ata_queued_cmd *qc);
static struct scsi_host_template pdc_sata_sht = {
ATA_BASE_SHT(DRV_NAME),
.sg_tablesize = LIBATA_MAX_PRD,
.dma_boundary = ATA_DMA_BOUNDARY,
};
/* TODO: inherit from base port_ops after converting to new EH */
static struct ata_port_operations pdc_20621_ops = {
.inherits = &ata_sff_port_ops,
.check_atapi_dma = pdc_check_atapi_dma,
.qc_prep = pdc20621_qc_prep,
.qc_issue = pdc20621_qc_issue,
.freeze = pdc_freeze,
.thaw = pdc_thaw,
.softreset = pdc_softreset,
.error_handler = pdc_error_handler,
.lost_interrupt = ATA_OP_NULL,
.post_internal_cmd = pdc_post_internal_cmd,
.port_start = pdc_port_start,
.sff_tf_load = pdc_tf_load_mmio,
.sff_exec_command = pdc_exec_command_mmio,
.sff_irq_clear = pdc20621_irq_clear,
};
static const struct ata_port_info pdc_port_info[] = {
/* board_20621 */
{
.flags = ATA_FLAG_SATA | ATA_FLAG_NO_ATAPI |
ATA_FLAG_PIO_POLLING,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &pdc_20621_ops,
},
};
static const struct pci_device_id pdc_sata_pci_tbl[] = {
{ PCI_VDEVICE(PROMISE, 0x6622), board_20621 },
{ } /* terminate list */
};
static struct pci_driver pdc_sata_pci_driver = {
.name = DRV_NAME,
.id_table = pdc_sata_pci_tbl,
.probe = pdc_sata_init_one,
.remove = ata_pci_remove_one,
};
static int pdc_port_start(struct ata_port *ap)
{
struct device *dev = ap->host->dev;
struct pdc_port_priv *pp;
pp = devm_kzalloc(dev, sizeof(*pp), GFP_KERNEL);
if (!pp)
return -ENOMEM;
pp->pkt = dmam_alloc_coherent(dev, 128, &pp->pkt_dma, GFP_KERNEL);
if (!pp->pkt)
return -ENOMEM;
ap->private_data = pp;
return 0;
}
static inline void pdc20621_ata_sg(struct ata_taskfile *tf, u8 *buf,
unsigned int portno,
unsigned int total_len)
{
u32 addr;
unsigned int dw = PDC_DIMM_APKT_PRD >> 2;
__le32 *buf32 = (__le32 *) buf;
/* output ATA packet S/G table */
addr = PDC_20621_DIMM_BASE + PDC_20621_DIMM_DATA +
(PDC_DIMM_DATA_STEP * portno);
VPRINTK("ATA sg addr 0x%x, %d\n", addr, addr);
buf32[dw] = cpu_to_le32(addr);
buf32[dw + 1] = cpu_to_le32(total_len | ATA_PRD_EOT);
VPRINTK("ATA PSG @ %x == (0x%x, 0x%x)\n",
PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_APKT_PRD,
buf32[dw], buf32[dw + 1]);
}
static inline void pdc20621_host_sg(struct ata_taskfile *tf, u8 *buf,
unsigned int portno,
unsigned int total_len)
{
u32 addr;
unsigned int dw = PDC_DIMM_HPKT_PRD >> 2;
__le32 *buf32 = (__le32 *) buf;
/* output Host DMA packet S/G table */
addr = PDC_20621_DIMM_BASE + PDC_20621_DIMM_DATA +
(PDC_DIMM_DATA_STEP * portno);
buf32[dw] = cpu_to_le32(addr);
buf32[dw + 1] = cpu_to_le32(total_len | ATA_PRD_EOT);
VPRINTK("HOST PSG @ %x == (0x%x, 0x%x)\n",
PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HPKT_PRD,
buf32[dw], buf32[dw + 1]);
}
static inline unsigned int pdc20621_ata_pkt(struct ata_taskfile *tf,
unsigned int devno, u8 *buf,
unsigned int portno)
{
unsigned int i, dw;
__le32 *buf32 = (__le32 *) buf;
u8 dev_reg;
unsigned int dimm_sg = PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_APKT_PRD;
VPRINTK("ENTER, dimm_sg == 0x%x, %d\n", dimm_sg, dimm_sg);
i = PDC_DIMM_ATA_PKT;
/*
* Set up ATA packet
*/
if ((tf->protocol == ATA_PROT_DMA) && (!(tf->flags & ATA_TFLAG_WRITE)))
buf[i++] = PDC_PKT_READ;
else if (tf->protocol == ATA_PROT_NODATA)
buf[i++] = PDC_PKT_NODATA;
else
buf[i++] = 0;
buf[i++] = 0; /* reserved */
buf[i++] = portno + 1; /* seq. id */
buf[i++] = 0xff; /* delay seq. id */
/* dimm dma S/G, and next-pkt */
dw = i >> 2;
if (tf->protocol == ATA_PROT_NODATA)
buf32[dw] = 0;
else
buf32[dw] = cpu_to_le32(dimm_sg);
buf32[dw + 1] = 0;
i += 8;
if (devno == 0)
dev_reg = ATA_DEVICE_OBS;
else
dev_reg = ATA_DEVICE_OBS | ATA_DEV1;
/* select device */
buf[i++] = (1 << 5) | PDC_PKT_CLEAR_BSY | ATA_REG_DEVICE;
buf[i++] = dev_reg;
/* device control register */
buf[i++] = (1 << 5) | PDC_REG_DEVCTL;
buf[i++] = tf->ctl;
return i;
}
static inline void pdc20621_host_pkt(struct ata_taskfile *tf, u8 *buf,
unsigned int portno)
{
unsigned int dw;
u32 tmp;
__le32 *buf32 = (__le32 *) buf;
unsigned int host_sg = PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HOST_PRD;
unsigned int dimm_sg = PDC_20621_DIMM_BASE +
(PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HPKT_PRD;
VPRINTK("ENTER, dimm_sg == 0x%x, %d\n", dimm_sg, dimm_sg);
VPRINTK("host_sg == 0x%x, %d\n", host_sg, host_sg);
dw = PDC_DIMM_HOST_PKT >> 2;
/*
* Set up Host DMA packet
*/
if ((tf->protocol == ATA_PROT_DMA) && (!(tf->flags & ATA_TFLAG_WRITE)))
tmp = PDC_PKT_READ;
else
tmp = 0;
tmp |= ((portno + 1 + 4) << 16); /* seq. id */
tmp |= (0xff << 24); /* delay seq. id */
buf32[dw + 0] = cpu_to_le32(tmp);
buf32[dw + 1] = cpu_to_le32(host_sg);
buf32[dw + 2] = cpu_to_le32(dimm_sg);
buf32[dw + 3] = 0;
VPRINTK("HOST PKT @ %x == (0x%x 0x%x 0x%x 0x%x)\n",
PDC_20621_DIMM_BASE + (PDC_DIMM_WINDOW_STEP * portno) +
PDC_DIMM_HOST_PKT,
buf32[dw + 0],
buf32[dw + 1],
buf32[dw + 2],
buf32[dw + 3]);
}
static void pdc20621_dma_prep(struct ata_queued_cmd *qc)
{
struct scatterlist *sg;
struct ata_port *ap = qc->ap;
struct pdc_port_priv *pp = ap->private_data;
void __iomem *mmio = ap->host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = ap->host->iomap[PDC_DIMM_BAR];
unsigned int portno = ap->port_no;
unsigned int i, si, idx, total_len = 0, sgt_len;
__le32 *buf = (__le32 *) &pp->dimm_buf[PDC_DIMM_HEADER_SZ];
WARN_ON(!(qc->flags & ATA_QCFLAG_DMAMAP));
VPRINTK("ata%u: ENTER\n", ap->print_id);
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/*
* Build S/G table
*/
idx = 0;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
buf[idx++] = cpu_to_le32(sg_dma_address(sg));
buf[idx++] = cpu_to_le32(sg_dma_len(sg));
total_len += sg_dma_len(sg);
}
buf[idx - 1] |= cpu_to_le32(ATA_PRD_EOT);
sgt_len = idx * 4;
/*
* Build ATA, host DMA packets
*/
pdc20621_host_sg(&qc->tf, &pp->dimm_buf[0], portno, total_len);
pdc20621_host_pkt(&qc->tf, &pp->dimm_buf[0], portno);
pdc20621_ata_sg(&qc->tf, &pp->dimm_buf[0], portno, total_len);
i = pdc20621_ata_pkt(&qc->tf, qc->dev->devno, &pp->dimm_buf[0], portno);
if (qc->tf.flags & ATA_TFLAG_LBA48)
i = pdc_prep_lba48(&qc->tf, &pp->dimm_buf[0], i);
else
i = pdc_prep_lba28(&qc->tf, &pp->dimm_buf[0], i);
pdc_pkt_footer(&qc->tf, &pp->dimm_buf[0], i);
/* copy three S/G tables and two packets to DIMM MMIO window */
memcpy_toio(dimm_mmio + (portno * PDC_DIMM_WINDOW_STEP),
&pp->dimm_buf, PDC_DIMM_HEADER_SZ);
memcpy_toio(dimm_mmio + (portno * PDC_DIMM_WINDOW_STEP) +
PDC_DIMM_HOST_PRD,
&pp->dimm_buf[PDC_DIMM_HEADER_SZ], sgt_len);
/* force host FIFO dump */
writel(0x00000001, mmio + PDC_20621_GENERAL_CTL);
readl(dimm_mmio); /* MMIO PCI posting flush */
VPRINTK("ata pkt buf ofs %u, prd size %u, mmio copied\n", i, sgt_len);
}
static void pdc20621_nodata_prep(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pdc_port_priv *pp = ap->private_data;
void __iomem *mmio = ap->host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = ap->host->iomap[PDC_DIMM_BAR];
unsigned int portno = ap->port_no;
unsigned int i;
VPRINTK("ata%u: ENTER\n", ap->print_id);
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
i = pdc20621_ata_pkt(&qc->tf, qc->dev->devno, &pp->dimm_buf[0], portno);
if (qc->tf.flags & ATA_TFLAG_LBA48)
i = pdc_prep_lba48(&qc->tf, &pp->dimm_buf[0], i);
else
i = pdc_prep_lba28(&qc->tf, &pp->dimm_buf[0], i);
pdc_pkt_footer(&qc->tf, &pp->dimm_buf[0], i);
/* copy three S/G tables and two packets to DIMM MMIO window */
memcpy_toio(dimm_mmio + (portno * PDC_DIMM_WINDOW_STEP),
&pp->dimm_buf, PDC_DIMM_HEADER_SZ);
/* force host FIFO dump */
writel(0x00000001, mmio + PDC_20621_GENERAL_CTL);
readl(dimm_mmio); /* MMIO PCI posting flush */
VPRINTK("ata pkt buf ofs %u, mmio copied\n", i);
}
static void pdc20621_qc_prep(struct ata_queued_cmd *qc)
{
switch (qc->tf.protocol) {
case ATA_PROT_DMA:
pdc20621_dma_prep(qc);
break;
case ATA_PROT_NODATA:
pdc20621_nodata_prep(qc);
break;
default:
break;
}
}
static void __pdc20621_push_hdma(struct ata_queued_cmd *qc,
unsigned int seq,
u32 pkt_ofs)
{
struct ata_port *ap = qc->ap;
struct ata_host *host = ap->host;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
writel(0x00000001, mmio + PDC_20621_SEQCTL + (seq * 4));
readl(mmio + PDC_20621_SEQCTL + (seq * 4)); /* flush */
writel(pkt_ofs, mmio + PDC_HDMA_PKT_SUBMIT);
readl(mmio + PDC_HDMA_PKT_SUBMIT); /* flush */
}
static void pdc20621_push_hdma(struct ata_queued_cmd *qc,
unsigned int seq,
u32 pkt_ofs)
{
struct ata_port *ap = qc->ap;
struct pdc_host_priv *pp = ap->host->private_data;
unsigned int idx = pp->hdma_prod & PDC_HDMA_Q_MASK;
if (!pp->doing_hdma) {
__pdc20621_push_hdma(qc, seq, pkt_ofs);
pp->doing_hdma = 1;
return;
}
pp->hdma[idx].qc = qc;
pp->hdma[idx].seq = seq;
pp->hdma[idx].pkt_ofs = pkt_ofs;
pp->hdma_prod++;
}
static void pdc20621_pop_hdma(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct pdc_host_priv *pp = ap->host->private_data;
unsigned int idx = pp->hdma_cons & PDC_HDMA_Q_MASK;
/* if nothing on queue, we're done */
if (pp->hdma_prod == pp->hdma_cons) {
pp->doing_hdma = 0;
return;
}
__pdc20621_push_hdma(pp->hdma[idx].qc, pp->hdma[idx].seq,
pp->hdma[idx].pkt_ofs);
pp->hdma_cons++;
}
#ifdef ATA_VERBOSE_DEBUG
static void pdc20621_dump_hdma(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned int port_no = ap->port_no;
void __iomem *dimm_mmio = ap->host->iomap[PDC_DIMM_BAR];
dimm_mmio += (port_no * PDC_DIMM_WINDOW_STEP);
dimm_mmio += PDC_DIMM_HOST_PKT;
printk(KERN_ERR "HDMA[0] == 0x%08X\n", readl(dimm_mmio));
printk(KERN_ERR "HDMA[1] == 0x%08X\n", readl(dimm_mmio + 4));
printk(KERN_ERR "HDMA[2] == 0x%08X\n", readl(dimm_mmio + 8));
printk(KERN_ERR "HDMA[3] == 0x%08X\n", readl(dimm_mmio + 12));
}
#else
static inline void pdc20621_dump_hdma(struct ata_queued_cmd *qc) { }
#endif /* ATA_VERBOSE_DEBUG */
static void pdc20621_packet_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_host *host = ap->host;
unsigned int port_no = ap->port_no;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
u8 seq = (u8) (port_no + 1);
unsigned int port_ofs;
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
VPRINTK("ata%u: ENTER\n", ap->print_id);
wmb(); /* flush PRD, pkt writes */
port_ofs = PDC_20621_DIMM_BASE + (PDC_DIMM_WINDOW_STEP * port_no);
/* if writing, we (1) DMA to DIMM, then (2) do ATA command */
if (rw && qc->tf.protocol == ATA_PROT_DMA) {
seq += 4;
pdc20621_dump_hdma(qc);
pdc20621_push_hdma(qc, seq, port_ofs + PDC_DIMM_HOST_PKT);
VPRINTK("queued ofs 0x%x (%u), seq %u\n",
port_ofs + PDC_DIMM_HOST_PKT,
port_ofs + PDC_DIMM_HOST_PKT,
seq);
} else {
writel(0x00000001, mmio + PDC_20621_SEQCTL + (seq * 4));
readl(mmio + PDC_20621_SEQCTL + (seq * 4)); /* flush */
writel(port_ofs + PDC_DIMM_ATA_PKT,
ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
readl(ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
VPRINTK("submitted ofs 0x%x (%u), seq %u\n",
port_ofs + PDC_DIMM_ATA_PKT,
port_ofs + PDC_DIMM_ATA_PKT,
seq);
}
}
static unsigned int pdc20621_qc_issue(struct ata_queued_cmd *qc)
{
switch (qc->tf.protocol) {
case ATA_PROT_NODATA:
if (qc->tf.flags & ATA_TFLAG_POLLING)
break;
/*FALLTHROUGH*/
case ATA_PROT_DMA:
pdc20621_packet_start(qc);
return 0;
case ATAPI_PROT_DMA:
BUG();
break;
default:
break;
}
return ata_sff_qc_issue(qc);
}
static inline unsigned int pdc20621_host_intr(struct ata_port *ap,
struct ata_queued_cmd *qc,
unsigned int doing_hdma,
void __iomem *mmio)
{
unsigned int port_no = ap->port_no;
unsigned int port_ofs =
PDC_20621_DIMM_BASE + (PDC_DIMM_WINDOW_STEP * port_no);
u8 status;
unsigned int handled = 0;
VPRINTK("ENTER\n");
if ((qc->tf.protocol == ATA_PROT_DMA) && /* read */
(!(qc->tf.flags & ATA_TFLAG_WRITE))) {
/* step two - DMA from DIMM to host */
if (doing_hdma) {
VPRINTK("ata%u: read hdma, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* get drive status; clear intr; complete txn */
qc->err_mask |= ac_err_mask(ata_wait_idle(ap));
ata_qc_complete(qc);
pdc20621_pop_hdma(qc);
}
/* step one - exec ATA command */
else {
u8 seq = (u8) (port_no + 1 + 4);
VPRINTK("ata%u: read ata, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* submit hdma pkt */
pdc20621_dump_hdma(qc);
pdc20621_push_hdma(qc, seq,
port_ofs + PDC_DIMM_HOST_PKT);
}
handled = 1;
} else if (qc->tf.protocol == ATA_PROT_DMA) { /* write */
/* step one - DMA from host to DIMM */
if (doing_hdma) {
u8 seq = (u8) (port_no + 1);
VPRINTK("ata%u: write hdma, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* submit ata pkt */
writel(0x00000001, mmio + PDC_20621_SEQCTL + (seq * 4));
readl(mmio + PDC_20621_SEQCTL + (seq * 4));
writel(port_ofs + PDC_DIMM_ATA_PKT,
ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
readl(ap->ioaddr.cmd_addr + PDC_PKT_SUBMIT);
}
/* step two - execute ATA command */
else {
VPRINTK("ata%u: write ata, 0x%x 0x%x\n", ap->print_id,
readl(mmio + 0x104), readl(mmio + PDC_HDMA_CTLSTAT));
/* get drive status; clear intr; complete txn */
qc->err_mask |= ac_err_mask(ata_wait_idle(ap));
ata_qc_complete(qc);
pdc20621_pop_hdma(qc);
}
handled = 1;
/* command completion, but no data xfer */
} else if (qc->tf.protocol == ATA_PROT_NODATA) {
status = ata_sff_busy_wait(ap, ATA_BUSY | ATA_DRQ, 1000);
DPRINTK("BUS_NODATA (drv_stat 0x%X)\n", status);
qc->err_mask |= ac_err_mask(status);
ata_qc_complete(qc);
handled = 1;
} else {
ap->stats.idle_irq++;
}
return handled;
}
static void pdc20621_irq_clear(struct ata_port *ap)
{
ioread8(ap->ioaddr.status_addr);
}
static irqreturn_t pdc20621_interrupt(int irq, void *dev_instance)
{
struct ata_host *host = dev_instance;
struct ata_port *ap;
u32 mask = 0;
unsigned int i, tmp, port_no;
unsigned int handled = 0;
void __iomem *mmio_base;
VPRINTK("ENTER\n");
if (!host || !host->iomap[PDC_MMIO_BAR]) {
VPRINTK("QUICK EXIT\n");
return IRQ_NONE;
}
mmio_base = host->iomap[PDC_MMIO_BAR];
/* reading should also clear interrupts */
mmio_base += PDC_CHIP0_OFS;
mask = readl(mmio_base + PDC_20621_SEQMASK);
VPRINTK("mask == 0x%x\n", mask);
if (mask == 0xffffffff) {
VPRINTK("QUICK EXIT 2\n");
return IRQ_NONE;
}
mask &= 0xffff; /* only 16 tags possible */
if (!mask) {
VPRINTK("QUICK EXIT 3\n");
return IRQ_NONE;
}
spin_lock(&host->lock);
for (i = 1; i < 9; i++) {
port_no = i - 1;
if (port_no > 3)
port_no -= 4;
if (port_no >= host->n_ports)
ap = NULL;
else
ap = host->ports[port_no];
tmp = mask & (1 << i);
VPRINTK("seq %u, port_no %u, ap %p, tmp %x\n", i, port_no, ap, tmp);
if (tmp && ap) {
struct ata_queued_cmd *qc;
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && (!(qc->tf.flags & ATA_TFLAG_POLLING)))
handled += pdc20621_host_intr(ap, qc, (i > 4),
mmio_base);
}
}
spin_unlock(&host->lock);
VPRINTK("mask == 0x%x\n", mask);
VPRINTK("EXIT\n");
return IRQ_RETVAL(handled);
}
static void pdc_freeze(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.cmd_addr;
u32 tmp;
/* FIXME: if all 4 ATA engines are stopped, also stop HDMA engine */
tmp = readl(mmio + PDC_CTLSTAT);
tmp |= PDC_MASK_INT;
tmp &= ~PDC_DMA_ENABLE;
writel(tmp, mmio + PDC_CTLSTAT);
readl(mmio + PDC_CTLSTAT); /* flush */
}
static void pdc_thaw(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.cmd_addr;
u32 tmp;
/* FIXME: start HDMA engine, if zero ATA engines running */
/* clear IRQ */
ioread8(ap->ioaddr.status_addr);
/* turn IRQ back on */
tmp = readl(mmio + PDC_CTLSTAT);
tmp &= ~PDC_MASK_INT;
writel(tmp, mmio + PDC_CTLSTAT);
readl(mmio + PDC_CTLSTAT); /* flush */
}
static void pdc_reset_port(struct ata_port *ap)
{
void __iomem *mmio = ap->ioaddr.cmd_addr + PDC_CTLSTAT;
unsigned int i;
u32 tmp;
/* FIXME: handle HDMA copy engine */
for (i = 11; i > 0; i--) {
tmp = readl(mmio);
if (tmp & PDC_RESET)
break;
udelay(100);
tmp |= PDC_RESET;
writel(tmp, mmio);
}
tmp &= ~PDC_RESET;
writel(tmp, mmio);
readl(mmio); /* flush */
}
static int pdc_softreset(struct ata_link *link, unsigned int *class,
unsigned long deadline)
{
pdc_reset_port(link->ap);
return ata_sff_softreset(link, class, deadline);
}
static void pdc_error_handler(struct ata_port *ap)
{
if (!(ap->pflags & ATA_PFLAG_FROZEN))
pdc_reset_port(ap);
ata_sff_error_handler(ap);
}
static void pdc_post_internal_cmd(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
/* make DMA engine forget about the failed command */
if (qc->flags & ATA_QCFLAG_FAILED)
pdc_reset_port(ap);
}
static int pdc_check_atapi_dma(struct ata_queued_cmd *qc)
{
u8 *scsicmd = qc->scsicmd->cmnd;
int pio = 1; /* atapi dma off by default */
/* Whitelist commands that may use DMA. */
switch (scsicmd[0]) {
case WRITE_12:
case WRITE_10:
case WRITE_6:
case READ_12:
case READ_10:
case READ_6:
case 0xad: /* READ_DVD_STRUCTURE */
case 0xbe: /* READ_CD */
pio = 0;
}
/* -45150 (FFFF4FA2) to -1 (FFFFFFFF) shall use PIO mode */
if (scsicmd[0] == WRITE_10) {
unsigned int lba =
(scsicmd[2] << 24) |
(scsicmd[3] << 16) |
(scsicmd[4] << 8) |
scsicmd[5];
if (lba >= 0xFFFF4FA2)
pio = 1;
}
return pio;
}
static void pdc_tf_load_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
{
WARN_ON(tf->protocol == ATA_PROT_DMA ||
tf->protocol == ATAPI_PROT_DMA);
ata_sff_tf_load(ap, tf);
}
static void pdc_exec_command_mmio(struct ata_port *ap, const struct ata_taskfile *tf)
{
WARN_ON(tf->protocol == ATA_PROT_DMA ||
tf->protocol == ATAPI_PROT_DMA);
ata_sff_exec_command(ap, tf);
}
static void pdc_sata_setup_port(struct ata_ioports *port, void __iomem *base)
{
port->cmd_addr = base;
port->data_addr = base;
port->feature_addr =
port->error_addr = base + 0x4;
port->nsect_addr = base + 0x8;
port->lbal_addr = base + 0xc;
port->lbam_addr = base + 0x10;
port->lbah_addr = base + 0x14;
port->device_addr = base + 0x18;
port->command_addr =
port->status_addr = base + 0x1c;
port->altstatus_addr =
port->ctl_addr = base + 0x38;
}
#ifdef ATA_VERBOSE_DEBUG
static void pdc20621_get_from_dimm(struct ata_host *host, void *psource,
u32 offset, u32 size)
{
u32 window_size;
u16 idx;
u8 page_mask;
long dist;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = host->iomap[PDC_DIMM_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
page_mask = 0x00;
window_size = 0x2000 * 4; /* 32K byte uchar size */
idx = (u16) (offset / window_size);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
offset -= (idx * window_size);
idx++;
dist = ((long) (window_size - (offset + size))) >= 0 ? size :
(long) (window_size - offset);
memcpy_fromio((char *) psource, (char *) (dimm_mmio + offset / 4),
dist);
psource += dist;
size -= dist;
for (; (long) size >= (long) window_size ;) {
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_fromio((char *) psource, (char *) (dimm_mmio),
window_size / 4);
psource += window_size;
size -= window_size;
idx++;
}
if (size) {
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_fromio((char *) psource, (char *) (dimm_mmio),
size / 4);
}
}
#endif
static void pdc20621_put_to_dimm(struct ata_host *host, void *psource,
u32 offset, u32 size)
{
u32 window_size;
u16 idx;
u8 page_mask;
long dist;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
void __iomem *dimm_mmio = host->iomap[PDC_DIMM_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
page_mask = 0x00;
window_size = 0x2000 * 4; /* 32K byte uchar size */
idx = (u16) (offset / window_size);
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
offset -= (idx * window_size);
idx++;
dist = ((long)(s32)(window_size - (offset + size))) >= 0 ? size :
(long) (window_size - offset);
memcpy_toio(dimm_mmio + offset / 4, psource, dist);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
psource += dist;
size -= dist;
for (; (long) size >= (long) window_size ;) {
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_toio(dimm_mmio, psource, window_size / 4);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
psource += window_size;
size -= window_size;
idx++;
}
if (size) {
writel(((idx) << page_mask), mmio + PDC_DIMM_WINDOW_CTLR);
readl(mmio + PDC_DIMM_WINDOW_CTLR);
memcpy_toio(dimm_mmio, psource, size / 4);
writel(0x01, mmio + PDC_GENERAL_CTLR);
readl(mmio + PDC_GENERAL_CTLR);
}
}
static unsigned int pdc20621_i2c_read(struct ata_host *host, u32 device,
u32 subaddr, u32 *pdata)
{
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
u32 i2creg = 0;
u32 status;
u32 count = 0;
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
i2creg |= device << 24;
i2creg |= subaddr << 16;
/* Set the device and subaddress */
writel(i2creg, mmio + PDC_I2C_ADDR_DATA);
readl(mmio + PDC_I2C_ADDR_DATA);
/* Write Control to perform read operation, mask int */
writel(PDC_I2C_READ | PDC_I2C_START | PDC_I2C_MASK_INT,
mmio + PDC_I2C_CONTROL);
for (count = 0; count <= 1000; count ++) {
status = readl(mmio + PDC_I2C_CONTROL);
if (status & PDC_I2C_COMPLETE) {
status = readl(mmio + PDC_I2C_ADDR_DATA);
break;
} else if (count == 1000)
return 0;
}
*pdata = (status >> 8) & 0x000000ff;
return 1;
}
static int pdc20621_detect_dimm(struct ata_host *host)
{
u32 data = 0;
if (pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
PDC_DIMM_SPD_SYSTEM_FREQ, &data)) {
if (data == 100)
return 100;
} else
return 0;
if (pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS, 9, &data)) {
if (data <= 0x75)
return 133;
} else
return 0;
return 0;
}
static int pdc20621_prog_dimm0(struct ata_host *host)
{
u32 spd0[50];
u32 data = 0;
int size, i;
u8 bdimmsize;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
static const struct {
unsigned int reg;
unsigned int ofs;
} pdc_i2c_read_data [] = {
{ PDC_DIMM_SPD_TYPE, 11 },
{ PDC_DIMM_SPD_FRESH_RATE, 12 },
{ PDC_DIMM_SPD_COLUMN_NUM, 4 },
{ PDC_DIMM_SPD_ATTRIBUTE, 21 },
{ PDC_DIMM_SPD_ROW_NUM, 3 },
{ PDC_DIMM_SPD_BANK_NUM, 17 },
{ PDC_DIMM_SPD_MODULE_ROW, 5 },
{ PDC_DIMM_SPD_ROW_PRE_CHARGE, 27 },
{ PDC_DIMM_SPD_ROW_ACTIVE_DELAY, 28 },
{ PDC_DIMM_SPD_RAS_CAS_DELAY, 29 },
{ PDC_DIMM_SPD_ACTIVE_PRECHARGE, 30 },
{ PDC_DIMM_SPD_CAS_LATENCY, 18 },
};
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
for (i = 0; i < ARRAY_SIZE(pdc_i2c_read_data); i++)
pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
pdc_i2c_read_data[i].reg,
&spd0[pdc_i2c_read_data[i].ofs]);
data |= (spd0[4] - 8) | ((spd0[21] != 0) << 3) | ((spd0[3]-11) << 4);
data |= ((spd0[17] / 4) << 6) | ((spd0[5] / 2) << 7) |
((((spd0[27] + 9) / 10) - 1) << 8) ;
data |= (((((spd0[29] > spd0[28])
? spd0[29] : spd0[28]) + 9) / 10) - 1) << 10;
data |= ((spd0[30] - spd0[29] + 9) / 10 - 2) << 12;
if (spd0[18] & 0x08)
data |= ((0x03) << 14);
else if (spd0[18] & 0x04)
data |= ((0x02) << 14);
else if (spd0[18] & 0x01)
data |= ((0x01) << 14);
else
data |= (0 << 14);
/*
Calculate the size of bDIMMSize (power of 2) and
merge the DIMM size by program start/end address.
*/
bdimmsize = spd0[4] + (spd0[5] / 2) + spd0[3] + (spd0[17] / 2) + 3;
size = (1 << bdimmsize) >> 20; /* size = xxx(MB) */
data |= (((size / 16) - 1) << 16);
data |= (0 << 23);
data |= 8;
writel(data, mmio + PDC_DIMM0_CONTROL);
readl(mmio + PDC_DIMM0_CONTROL);
return size;
}
static unsigned int pdc20621_prog_dimm_global(struct ata_host *host)
{
u32 data, spd0;
int error, i;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/*
Set To Default : DIMM Module Global Control Register (0x022259F1)
DIMM Arbitration Disable (bit 20)
DIMM Data/Control Output Driving Selection (bit12 - bit15)
Refresh Enable (bit 17)
*/
data = 0x022259F1;
writel(data, mmio + PDC_SDRAM_CONTROL);
readl(mmio + PDC_SDRAM_CONTROL);
/* Turn on for ECC */
pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
PDC_DIMM_SPD_TYPE, &spd0);
if (spd0 == 0x02) {
data |= (0x01 << 16);
writel(data, mmio + PDC_SDRAM_CONTROL);
readl(mmio + PDC_SDRAM_CONTROL);
printk(KERN_ERR "Local DIMM ECC Enabled\n");
}
/* DIMM Initialization Select/Enable (bit 18/19) */
data &= (~(1<<18));
data |= (1<<19);
writel(data, mmio + PDC_SDRAM_CONTROL);
error = 1;
for (i = 1; i <= 10; i++) { /* polling ~5 secs */
data = readl(mmio + PDC_SDRAM_CONTROL);
if (!(data & (1<<19))) {
error = 0;
break;
}
msleep(i*100);
}
return error;
}
static unsigned int pdc20621_dimm_init(struct ata_host *host)
{
int speed, size, length;
u32 addr, spd0, pci_status;
u32 time_period = 0;
u32 tcount = 0;
u32 ticks = 0;
u32 clock = 0;
u32 fparam = 0;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/* Initialize PLL based upon PCI Bus Frequency */
/* Initialize Time Period Register */
writel(0xffffffff, mmio + PDC_TIME_PERIOD);
time_period = readl(mmio + PDC_TIME_PERIOD);
VPRINTK("Time Period Register (0x40): 0x%x\n", time_period);
/* Enable timer */
writel(PDC_TIMER_DEFAULT, mmio + PDC_TIME_CONTROL);
readl(mmio + PDC_TIME_CONTROL);
/* Wait 3 seconds */
msleep(3000);
/*
When timer is enabled, counter is decreased every internal
clock cycle.
*/
tcount = readl(mmio + PDC_TIME_COUNTER);
VPRINTK("Time Counter Register (0x44): 0x%x\n", tcount);
/*
If SX4 is on PCI-X bus, after 3 seconds, the timer counter
register should be >= (0xffffffff - 3x10^8).
*/
if (tcount >= PCI_X_TCOUNT) {
ticks = (time_period - tcount);
VPRINTK("Num counters 0x%x (%d)\n", ticks, ticks);
clock = (ticks / 300000);
VPRINTK("10 * Internal clk = 0x%x (%d)\n", clock, clock);
clock = (clock * 33);
VPRINTK("10 * Internal clk * 33 = 0x%x (%d)\n", clock, clock);
/* PLL F Param (bit 22:16) */
fparam = (1400000 / clock) - 2;
VPRINTK("PLL F Param: 0x%x (%d)\n", fparam, fparam);
/* OD param = 0x2 (bit 31:30), R param = 0x5 (bit 29:25) */
pci_status = (0x8a001824 | (fparam << 16));
} else
pci_status = PCI_PLL_INIT;
/* Initialize PLL. */
VPRINTK("pci_status: 0x%x\n", pci_status);
writel(pci_status, mmio + PDC_CTL_STATUS);
readl(mmio + PDC_CTL_STATUS);
/*
Read SPD of DIMM by I2C interface,
and program the DIMM Module Controller.
*/
if (!(speed = pdc20621_detect_dimm(host))) {
printk(KERN_ERR "Detect Local DIMM Fail\n");
return 1; /* DIMM error */
}
VPRINTK("Local DIMM Speed = %d\n", speed);
/* Programming DIMM0 Module Control Register (index_CID0:80h) */
size = pdc20621_prog_dimm0(host);
VPRINTK("Local DIMM Size = %dMB\n", size);
/* Programming DIMM Module Global Control Register (index_CID0:88h) */
if (pdc20621_prog_dimm_global(host)) {
printk(KERN_ERR "Programming DIMM Module Global Control Register Fail\n");
return 1;
}
#ifdef ATA_VERBOSE_DEBUG
{
u8 test_parttern1[40] =
{0x55,0xAA,'P','r','o','m','i','s','e',' ',
'N','o','t',' ','Y','e','t',' ',
'D','e','f','i','n','e','d',' ',
'1','.','1','0',
'9','8','0','3','1','6','1','2',0,0};
u8 test_parttern2[40] = {0};
pdc20621_put_to_dimm(host, test_parttern2, 0x10040, 40);
pdc20621_put_to_dimm(host, test_parttern2, 0x40, 40);
pdc20621_put_to_dimm(host, test_parttern1, 0x10040, 40);
pdc20621_get_from_dimm(host, test_parttern2, 0x40, 40);
printk(KERN_ERR "%x, %x, %s\n", test_parttern2[0],
test_parttern2[1], &(test_parttern2[2]));
pdc20621_get_from_dimm(host, test_parttern2, 0x10040,
40);
printk(KERN_ERR "%x, %x, %s\n", test_parttern2[0],
test_parttern2[1], &(test_parttern2[2]));
pdc20621_put_to_dimm(host, test_parttern1, 0x40, 40);
pdc20621_get_from_dimm(host, test_parttern2, 0x40, 40);
printk(KERN_ERR "%x, %x, %s\n", test_parttern2[0],
test_parttern2[1], &(test_parttern2[2]));
}
#endif
/* ECC initiliazation. */
pdc20621_i2c_read(host, PDC_DIMM0_SPD_DEV_ADDRESS,
PDC_DIMM_SPD_TYPE, &spd0);
if (spd0 == 0x02) {
void *buf;
VPRINTK("Start ECC initialization\n");
addr = 0;
length = size * 1024 * 1024;
buf = kzalloc(ECC_ERASE_BUF_SZ, GFP_KERNEL);
while (addr < length) {
pdc20621_put_to_dimm(host, buf, addr,
ECC_ERASE_BUF_SZ);
addr += ECC_ERASE_BUF_SZ;
}
kfree(buf);
VPRINTK("Finish ECC initialization\n");
}
return 0;
}
static void pdc_20621_init(struct ata_host *host)
{
u32 tmp;
void __iomem *mmio = host->iomap[PDC_MMIO_BAR];
/* hard-code chip #0 */
mmio += PDC_CHIP0_OFS;
/*
* Select page 0x40 for our 32k DIMM window
*/
tmp = readl(mmio + PDC_20621_DIMM_WINDOW) & 0xffff0000;
tmp |= PDC_PAGE_WINDOW; /* page 40h; arbitrarily selected */
writel(tmp, mmio + PDC_20621_DIMM_WINDOW);
/*
* Reset Host DMA
*/
tmp = readl(mmio + PDC_HDMA_CTLSTAT);
tmp |= PDC_RESET;
writel(tmp, mmio + PDC_HDMA_CTLSTAT);
readl(mmio + PDC_HDMA_CTLSTAT); /* flush */
udelay(10);
tmp = readl(mmio + PDC_HDMA_CTLSTAT);
tmp &= ~PDC_RESET;
writel(tmp, mmio + PDC_HDMA_CTLSTAT);
readl(mmio + PDC_HDMA_CTLSTAT); /* flush */
}
static int pdc_sata_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
const struct ata_port_info *ppi[] =
{ &pdc_port_info[ent->driver_data], NULL };
struct ata_host *host;
struct pdc_host_priv *hpriv;
int i, rc;
ata_print_version_once(&pdev->dev, DRV_VERSION);
/* allocate host */
host = ata_host_alloc_pinfo(&pdev->dev, ppi, 4);
hpriv = devm_kzalloc(&pdev->dev, sizeof(*hpriv), GFP_KERNEL);
if (!host || !hpriv)
return -ENOMEM;
host->private_data = hpriv;
/* acquire resources and fill host */
rc = pcim_enable_device(pdev);
if (rc)
return rc;
rc = pcim_iomap_regions(pdev, (1 << PDC_MMIO_BAR) | (1 << PDC_DIMM_BAR),
DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(pdev);
if (rc)
return rc;
host->iomap = pcim_iomap_table(pdev);
for (i = 0; i < 4; i++) {
struct ata_port *ap = host->ports[i];
void __iomem *base = host->iomap[PDC_MMIO_BAR] + PDC_CHIP0_OFS;
unsigned int offset = 0x200 + i * 0x80;
pdc_sata_setup_port(&ap->ioaddr, base + offset);
ata_port_pbar_desc(ap, PDC_MMIO_BAR, -1, "mmio");
ata_port_pbar_desc(ap, PDC_DIMM_BAR, -1, "dimm");
ata_port_pbar_desc(ap, PDC_MMIO_BAR, offset, "port");
}
/* configure and activate */
rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
if (pdc20621_dimm_init(host))
return -ENOMEM;
pdc_20621_init(host);
pci_set_master(pdev);
return ata_host_activate(host, pdev->irq, pdc20621_interrupt,
IRQF_SHARED, &pdc_sata_sht);
}
static int __init pdc_sata_init(void)
{
return pci_register_driver(&pdc_sata_pci_driver);
}
static void __exit pdc_sata_exit(void)
{
pci_unregister_driver(&pdc_sata_pci_driver);
}
MODULE_AUTHOR("Jeff Garzik");
MODULE_DESCRIPTION("Promise SATA low-level driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, pdc_sata_pci_tbl);
MODULE_VERSION(DRV_VERSION);
module_init(pdc_sata_init);
module_exit(pdc_sata_exit);
| gpl-2.0 |
nasty007/android_kernel_lge_mako | drivers/ata/sata_vsc.c | 5508 | 12415 | /*
* sata_vsc.c - Vitesse VSC7174 4 port DPA SATA
*
* Maintained by: Jeremy Higdon @ SGI
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2004 SGI
*
* Bits from Jeff Garzik, Copyright RedHat, Inc.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* Vitesse hardware documentation presumably available under NDA.
* Intel 31244 (same hardware interface) documentation presumably
* available from http://developer.intel.com/
*
*/
#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/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#define DRV_NAME "sata_vsc"
#define DRV_VERSION "2.3"
enum {
VSC_MMIO_BAR = 0,
/* Interrupt register offsets (from chip base address) */
VSC_SATA_INT_STAT_OFFSET = 0x00,
VSC_SATA_INT_MASK_OFFSET = 0x04,
/* Taskfile registers offsets */
VSC_SATA_TF_CMD_OFFSET = 0x00,
VSC_SATA_TF_DATA_OFFSET = 0x00,
VSC_SATA_TF_ERROR_OFFSET = 0x04,
VSC_SATA_TF_FEATURE_OFFSET = 0x06,
VSC_SATA_TF_NSECT_OFFSET = 0x08,
VSC_SATA_TF_LBAL_OFFSET = 0x0c,
VSC_SATA_TF_LBAM_OFFSET = 0x10,
VSC_SATA_TF_LBAH_OFFSET = 0x14,
VSC_SATA_TF_DEVICE_OFFSET = 0x18,
VSC_SATA_TF_STATUS_OFFSET = 0x1c,
VSC_SATA_TF_COMMAND_OFFSET = 0x1d,
VSC_SATA_TF_ALTSTATUS_OFFSET = 0x28,
VSC_SATA_TF_CTL_OFFSET = 0x29,
/* DMA base */
VSC_SATA_UP_DESCRIPTOR_OFFSET = 0x64,
VSC_SATA_UP_DATA_BUFFER_OFFSET = 0x6C,
VSC_SATA_DMA_CMD_OFFSET = 0x70,
/* SCRs base */
VSC_SATA_SCR_STATUS_OFFSET = 0x100,
VSC_SATA_SCR_ERROR_OFFSET = 0x104,
VSC_SATA_SCR_CONTROL_OFFSET = 0x108,
/* Port stride */
VSC_SATA_PORT_OFFSET = 0x200,
/* Error interrupt status bit offsets */
VSC_SATA_INT_ERROR_CRC = 0x40,
VSC_SATA_INT_ERROR_T = 0x20,
VSC_SATA_INT_ERROR_P = 0x10,
VSC_SATA_INT_ERROR_R = 0x8,
VSC_SATA_INT_ERROR_E = 0x4,
VSC_SATA_INT_ERROR_M = 0x2,
VSC_SATA_INT_PHY_CHANGE = 0x1,
VSC_SATA_INT_ERROR = (VSC_SATA_INT_ERROR_CRC | VSC_SATA_INT_ERROR_T | \
VSC_SATA_INT_ERROR_P | VSC_SATA_INT_ERROR_R | \
VSC_SATA_INT_ERROR_E | VSC_SATA_INT_ERROR_M | \
VSC_SATA_INT_PHY_CHANGE),
};
static int vsc_sata_scr_read(struct ata_link *link,
unsigned int sc_reg, u32 *val)
{
if (sc_reg > SCR_CONTROL)
return -EINVAL;
*val = readl(link->ap->ioaddr.scr_addr + (sc_reg * 4));
return 0;
}
static int vsc_sata_scr_write(struct ata_link *link,
unsigned int sc_reg, u32 val)
{
if (sc_reg > SCR_CONTROL)
return -EINVAL;
writel(val, link->ap->ioaddr.scr_addr + (sc_reg * 4));
return 0;
}
static void vsc_freeze(struct ata_port *ap)
{
void __iomem *mask_addr;
mask_addr = ap->host->iomap[VSC_MMIO_BAR] +
VSC_SATA_INT_MASK_OFFSET + ap->port_no;
writeb(0, mask_addr);
}
static void vsc_thaw(struct ata_port *ap)
{
void __iomem *mask_addr;
mask_addr = ap->host->iomap[VSC_MMIO_BAR] +
VSC_SATA_INT_MASK_OFFSET + ap->port_no;
writeb(0xff, mask_addr);
}
static void vsc_intr_mask_update(struct ata_port *ap, u8 ctl)
{
void __iomem *mask_addr;
u8 mask;
mask_addr = ap->host->iomap[VSC_MMIO_BAR] +
VSC_SATA_INT_MASK_OFFSET + ap->port_no;
mask = readb(mask_addr);
if (ctl & ATA_NIEN)
mask |= 0x80;
else
mask &= 0x7F;
writeb(mask, mask_addr);
}
static void vsc_sata_tf_load(struct ata_port *ap, const struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
/*
* The only thing the ctl register is used for is SRST.
* That is not enabled or disabled via tf_load.
* However, if ATA_NIEN is changed, then we need to change
* the interrupt register.
*/
if ((tf->ctl & ATA_NIEN) != (ap->last_ctl & ATA_NIEN)) {
ap->last_ctl = tf->ctl;
vsc_intr_mask_update(ap, tf->ctl & ATA_NIEN);
}
if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
writew(tf->feature | (((u16)tf->hob_feature) << 8),
ioaddr->feature_addr);
writew(tf->nsect | (((u16)tf->hob_nsect) << 8),
ioaddr->nsect_addr);
writew(tf->lbal | (((u16)tf->hob_lbal) << 8),
ioaddr->lbal_addr);
writew(tf->lbam | (((u16)tf->hob_lbam) << 8),
ioaddr->lbam_addr);
writew(tf->lbah | (((u16)tf->hob_lbah) << 8),
ioaddr->lbah_addr);
} else if (is_addr) {
writew(tf->feature, ioaddr->feature_addr);
writew(tf->nsect, ioaddr->nsect_addr);
writew(tf->lbal, ioaddr->lbal_addr);
writew(tf->lbam, ioaddr->lbam_addr);
writew(tf->lbah, ioaddr->lbah_addr);
}
if (tf->flags & ATA_TFLAG_DEVICE)
writeb(tf->device, ioaddr->device_addr);
ata_wait_idle(ap);
}
static void vsc_sata_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
u16 nsect, lbal, lbam, lbah, feature;
tf->command = ata_sff_check_status(ap);
tf->device = readw(ioaddr->device_addr);
feature = readw(ioaddr->error_addr);
nsect = readw(ioaddr->nsect_addr);
lbal = readw(ioaddr->lbal_addr);
lbam = readw(ioaddr->lbam_addr);
lbah = readw(ioaddr->lbah_addr);
tf->feature = feature;
tf->nsect = nsect;
tf->lbal = lbal;
tf->lbam = lbam;
tf->lbah = lbah;
if (tf->flags & ATA_TFLAG_LBA48) {
tf->hob_feature = feature >> 8;
tf->hob_nsect = nsect >> 8;
tf->hob_lbal = lbal >> 8;
tf->hob_lbam = lbam >> 8;
tf->hob_lbah = lbah >> 8;
}
}
static inline void vsc_error_intr(u8 port_status, struct ata_port *ap)
{
if (port_status & (VSC_SATA_INT_PHY_CHANGE | VSC_SATA_INT_ERROR_M))
ata_port_freeze(ap);
else
ata_port_abort(ap);
}
static void vsc_port_intr(u8 port_status, struct ata_port *ap)
{
struct ata_queued_cmd *qc;
int handled = 0;
if (unlikely(port_status & VSC_SATA_INT_ERROR)) {
vsc_error_intr(port_status, ap);
return;
}
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (qc && likely(!(qc->tf.flags & ATA_TFLAG_POLLING)))
handled = ata_bmdma_port_intr(ap, qc);
/* We received an interrupt during a polled command,
* or some other spurious condition. Interrupt reporting
* with this hardware is fairly reliable so it is safe to
* simply clear the interrupt
*/
if (unlikely(!handled))
ap->ops->sff_check_status(ap);
}
/*
* vsc_sata_interrupt
*
* Read the interrupt register and process for the devices that have
* them pending.
*/
static irqreturn_t vsc_sata_interrupt(int irq, void *dev_instance)
{
struct ata_host *host = dev_instance;
unsigned int i;
unsigned int handled = 0;
u32 status;
status = readl(host->iomap[VSC_MMIO_BAR] + VSC_SATA_INT_STAT_OFFSET);
if (unlikely(status == 0xffffffff || status == 0)) {
if (status)
dev_err(host->dev,
": IRQ status == 0xffffffff, PCI fault or device removal?\n");
goto out;
}
spin_lock(&host->lock);
for (i = 0; i < host->n_ports; i++) {
u8 port_status = (status >> (8 * i)) & 0xff;
if (port_status) {
vsc_port_intr(port_status, host->ports[i]);
handled++;
}
}
spin_unlock(&host->lock);
out:
return IRQ_RETVAL(handled);
}
static struct scsi_host_template vsc_sata_sht = {
ATA_BMDMA_SHT(DRV_NAME),
};
static struct ata_port_operations vsc_sata_ops = {
.inherits = &ata_bmdma_port_ops,
/* The IRQ handling is not quite standard SFF behaviour so we
cannot use the default lost interrupt handler */
.lost_interrupt = ATA_OP_NULL,
.sff_tf_load = vsc_sata_tf_load,
.sff_tf_read = vsc_sata_tf_read,
.freeze = vsc_freeze,
.thaw = vsc_thaw,
.scr_read = vsc_sata_scr_read,
.scr_write = vsc_sata_scr_write,
};
static void __devinit vsc_sata_setup_port(struct ata_ioports *port,
void __iomem *base)
{
port->cmd_addr = base + VSC_SATA_TF_CMD_OFFSET;
port->data_addr = base + VSC_SATA_TF_DATA_OFFSET;
port->error_addr = base + VSC_SATA_TF_ERROR_OFFSET;
port->feature_addr = base + VSC_SATA_TF_FEATURE_OFFSET;
port->nsect_addr = base + VSC_SATA_TF_NSECT_OFFSET;
port->lbal_addr = base + VSC_SATA_TF_LBAL_OFFSET;
port->lbam_addr = base + VSC_SATA_TF_LBAM_OFFSET;
port->lbah_addr = base + VSC_SATA_TF_LBAH_OFFSET;
port->device_addr = base + VSC_SATA_TF_DEVICE_OFFSET;
port->status_addr = base + VSC_SATA_TF_STATUS_OFFSET;
port->command_addr = base + VSC_SATA_TF_COMMAND_OFFSET;
port->altstatus_addr = base + VSC_SATA_TF_ALTSTATUS_OFFSET;
port->ctl_addr = base + VSC_SATA_TF_CTL_OFFSET;
port->bmdma_addr = base + VSC_SATA_DMA_CMD_OFFSET;
port->scr_addr = base + VSC_SATA_SCR_STATUS_OFFSET;
writel(0, base + VSC_SATA_UP_DESCRIPTOR_OFFSET);
writel(0, base + VSC_SATA_UP_DATA_BUFFER_OFFSET);
}
static int __devinit vsc_sata_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static const struct ata_port_info pi = {
.flags = ATA_FLAG_SATA,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA6,
.port_ops = &vsc_sata_ops,
};
const struct ata_port_info *ppi[] = { &pi, NULL };
struct ata_host *host;
void __iomem *mmio_base;
int i, rc;
u8 cls;
ata_print_version_once(&pdev->dev, DRV_VERSION);
/* allocate host */
host = ata_host_alloc_pinfo(&pdev->dev, ppi, 4);
if (!host)
return -ENOMEM;
rc = pcim_enable_device(pdev);
if (rc)
return rc;
/* check if we have needed resource mapped */
if (pci_resource_len(pdev, 0) == 0)
return -ENODEV;
/* map IO regions and initialize host accordingly */
rc = pcim_iomap_regions(pdev, 1 << VSC_MMIO_BAR, DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(pdev);
if (rc)
return rc;
host->iomap = pcim_iomap_table(pdev);
mmio_base = host->iomap[VSC_MMIO_BAR];
for (i = 0; i < host->n_ports; i++) {
struct ata_port *ap = host->ports[i];
unsigned int offset = (i + 1) * VSC_SATA_PORT_OFFSET;
vsc_sata_setup_port(&ap->ioaddr, mmio_base + offset);
ata_port_pbar_desc(ap, VSC_MMIO_BAR, -1, "mmio");
ata_port_pbar_desc(ap, VSC_MMIO_BAR, offset, "port");
}
/*
* Use 32 bit DMA mask, because 64 bit address support is poor.
*/
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc)
return rc;
rc = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc)
return rc;
/*
* Due to a bug in the chip, the default cache line size can't be
* used (unless the default is non-zero).
*/
pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE, &cls);
if (cls == 0x00)
pci_write_config_byte(pdev, PCI_CACHE_LINE_SIZE, 0x80);
if (pci_enable_msi(pdev) == 0)
pci_intx(pdev, 0);
/*
* Config offset 0x98 is "Extended Control and Status Register 0"
* Default value is (1 << 28). All bits except bit 28 are reserved in
* DPA mode. If bit 28 is set, LED 0 reflects all ports' activity.
* If bit 28 is clear, each port has its own LED.
*/
pci_write_config_dword(pdev, 0x98, 0);
pci_set_master(pdev);
return ata_host_activate(host, pdev->irq, vsc_sata_interrupt,
IRQF_SHARED, &vsc_sata_sht);
}
static const struct pci_device_id vsc_sata_pci_tbl[] = {
{ PCI_VENDOR_ID_VITESSE, 0x7174,
PCI_ANY_ID, PCI_ANY_ID, 0x10600, 0xFFFFFF, 0 },
{ PCI_VENDOR_ID_INTEL, 0x3200,
PCI_ANY_ID, PCI_ANY_ID, 0x10600, 0xFFFFFF, 0 },
{ } /* terminate list */
};
static struct pci_driver vsc_sata_pci_driver = {
.name = DRV_NAME,
.id_table = vsc_sata_pci_tbl,
.probe = vsc_sata_init_one,
.remove = ata_pci_remove_one,
};
static int __init vsc_sata_init(void)
{
return pci_register_driver(&vsc_sata_pci_driver);
}
static void __exit vsc_sata_exit(void)
{
pci_unregister_driver(&vsc_sata_pci_driver);
}
MODULE_AUTHOR("Jeremy Higdon");
MODULE_DESCRIPTION("low-level driver for Vitesse VSC7174 SATA controller");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, vsc_sata_pci_tbl);
MODULE_VERSION(DRV_VERSION);
module_init(vsc_sata_init);
module_exit(vsc_sata_exit);
| gpl-2.0 |
fermasia/android_kernel_oneplus_msm8974 | drivers/staging/comedi/drivers/addi-data/hwdrv_apci035.c | 8324 | 26524 | /**
@verbatim
Copyright (C) 2004,2005 ADDI-DATA GmbH for the source code of this module.
ADDI-DATA GmbH
Dieselstrasse 3
D-77833 Ottersweier
Tel: +19(0)7223/9493-0
Fax: +49(0)7223/9493-92
http://www.addi-data.com
info@addi-data.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
You should also find the complete GPL in the COPYING file accompanying this source code.
@endverbatim
*/
/*
+-----------------------------------------------------------------------+
| (C) ADDI-DATA GmbH Dieselstraße 3 D-77833 Ottersweier |
+-----------------------------------------------------------------------+
| Tel : +49 (0) 7223/9493-0 | email : info@addi-data.com |
| Fax : +49 (0) 7223/9493-92 | Internet : http://www.addi-data.com |
+-------------------------------+---------------------------------------+
| Project : APCI-035 | Compiler : GCC |
| Module name : hwdrv_apci035.c | Version : 2.96 |
+-------------------------------+---------------------------------------+
| Project manager: Eric Stolz | Date : 02/12/2002 |
+-------------------------------+---------------------------------------+
| Description : Hardware Layer Access For APCI-035 |
+-----------------------------------------------------------------------+
| UPDATES |
+----------+-----------+------------------------------------------------+
| Date | Author | Description of updates |
+----------+-----------+------------------------------------------------+
| | | |
| | | |
| | | |
+----------+-----------+------------------------------------------------+
*/
/*
+----------------------------------------------------------------------------+
| Included files |
+----------------------------------------------------------------------------+
*/
#include "hwdrv_apci035.h"
static int i_WatchdogNbr = 0;
static int i_Temp = 0;
static int i_Flag = 1;
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI035_ConfigTimerWatchdog |
| (struct comedi_device *dev,struct comedi_subdevice *s, |
| struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Configures The Timer , Counter or Watchdog |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| unsigned int *data : Data Pointer contains |
| configuration parameters as below |
| |
| data[0] : 0 Configure As Timer |
| 1 Configure As Watchdog |
| data[1] : Watchdog number
| data[2] : Time base Unit |
| data[3] : Reload Value |
| data[4] : External Trigger |
| 1:Enable
| 0:Disable
| data[5] :External Trigger Level
| 00 Trigger Disabled
| 01 Trigger Enabled (Low level)
| 10 Trigger Enabled (High Level)
| 11 Trigger Enabled (High/Low level)
| data[6] : External Gate |
| 1:Enable
| 0:Disable
| data[7] : External Gate level
| 00 Gate Disabled
| 01 Gate Enabled (Low level)
| 10 Gate Enabled (High Level)
| data[8] :Warning Relay
| 1: ENABLE
| 0: DISABLE
| data[9] :Warning Delay available
| data[10] :Warning Relay Time unit
| data[11] :Warning Relay Time Reload value
| data[12] :Reset Relay
| 1 : ENABLE
| 0 : DISABLE
| data[13] :Interrupt
| 1 : ENABLE
| 0 : DISABLE
|
|
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
int i_APCI035_ConfigTimerWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int ui_Status = 0;
unsigned int ui_Command = 0;
unsigned int ui_Mode = 0;
i_Temp = 0;
devpriv->tsk_Current = current;
devpriv->b_TimerSelectMode = data[0];
i_WatchdogNbr = data[1];
if (data[0] == 0) {
ui_Mode = 2;
} else {
ui_Mode = 0;
}
/* ui_Command = inl(devpriv->iobase+((i_WatchdogNbr-1)*32)+12); */
ui_Command = 0;
/* ui_Command = ui_Command & 0xFFFFF9FEUL; */
outl(ui_Command, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
ui_Command = 0;
ui_Command = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
/************************/
/* Set the reload value */
/************************/
outl(data[3], devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 4);
/*********************/
/* Set the time unit */
/*********************/
outl(data[2], devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 8);
if (data[0] == ADDIDATA_TIMER) {
/******************************/
/* Set the mode : */
/* - Disable the hardware */
/* - Disable the counter mode */
/* - Disable the warning */
/* - Disable the reset */
/* - Enable the timer mode */
/* - Set the timer mode */
/******************************/
ui_Command =
(ui_Command & 0xFFF719E2UL) | ui_Mode << 13UL | 0x10UL;
} /* if (data[0] == ADDIDATA_TIMER) */
else {
if (data[0] == ADDIDATA_WATCHDOG) {
/******************************/
/* Set the mode : */
/* - Disable the hardware */
/* - Disable the counter mode */
/* - Disable the warning */
/* - Disable the reset */
/* - Disable the timer mode */
/******************************/
ui_Command = ui_Command & 0xFFF819E2UL;
} else {
printk("\n The parameter for Timer/watchdog selection is in error\n");
return -EINVAL;
}
}
outl(ui_Command, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
ui_Command = 0;
ui_Command = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
/********************************/
/* Disable the hardware trigger */
/********************************/
ui_Command = ui_Command & 0xFFFFF89FUL;
if (data[4] == ADDIDATA_ENABLE) {
/**********************************/
/* Set the hardware trigger level */
/**********************************/
ui_Command = ui_Command | (data[5] << 5);
}
outl(ui_Command, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
ui_Command = 0;
ui_Command = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
/*****************************/
/* Disable the hardware gate */
/*****************************/
ui_Command = ui_Command & 0xFFFFF87FUL;
if (data[6] == ADDIDATA_ENABLE) {
/*******************************/
/* Set the hardware gate level */
/*******************************/
ui_Command = ui_Command | (data[7] << 7);
}
outl(ui_Command, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
ui_Command = 0;
ui_Command = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
/*******************************/
/* Disable the hardware output */
/*******************************/
ui_Command = ui_Command & 0xFFFFF9FBUL;
/*********************************/
/* Set the hardware output level */
/*********************************/
ui_Command = ui_Command | (data[8] << 2);
outl(ui_Command, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
if (data[9] == ADDIDATA_ENABLE) {
/************************/
/* Set the reload value */
/************************/
outl(data[11],
devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 24);
/**********************/
/* Set the time unite */
/**********************/
outl(data[10],
devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 28);
}
ui_Command = 0;
ui_Command = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
/*******************************/
/* Disable the hardware output */
/*******************************/
ui_Command = ui_Command & 0xFFFFF9F7UL;
/*********************************/
/* Set the hardware output level */
/*********************************/
ui_Command = ui_Command | (data[12] << 3);
outl(ui_Command, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
/*************************************/
/** Enable the watchdog interrupt **/
/*************************************/
ui_Command = 0;
ui_Command = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
/*******************************/
/* Set the interrupt selection */
/*******************************/
ui_Status = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 16);
ui_Command = (ui_Command & 0xFFFFF9FDUL) | (data[13] << 1);
outl(ui_Command, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI035_StartStopWriteTimerWatchdog |
| (struct comedi_device *dev,struct comedi_subdevice *s, |
| struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Start / Stop The Selected Timer , or Watchdog |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| unsigned int *data : Data Pointer contains |
| configuration parameters as below |
| |
| data[0] : 0 - Stop Selected Timer/Watchdog |
| 1 - Start Selected Timer/Watchdog |
| 2 - Trigger Selected Timer/Watchdog |
| 3 - Stop All Timer/Watchdog |
| 4 - Start All Timer/Watchdog |
| 5 - Trigger All Timer/Watchdog |
| |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
int i_APCI035_StartStopWriteTimerWatchdog(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
unsigned int ui_Command = 0;
int i_Count = 0;
if (data[0] == 1) {
ui_Command =
inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
/**********************/
/* Start the hardware */
/**********************/
ui_Command = (ui_Command & 0xFFFFF9FFUL) | 0x1UL;
outl(ui_Command,
devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
} /* if (data[0]==1) */
if (data[0] == 2) {
ui_Command =
inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
/***************************/
/* Set the trigger command */
/***************************/
ui_Command = (ui_Command & 0xFFFFF9FFUL) | 0x200UL;
outl(ui_Command,
devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
}
if (data[0] == 0) /* Stop The Watchdog */
{
/* Stop The Watchdog */
ui_Command = 0;
/*
* ui_Command = inl(devpriv->iobase+((i_WatchdogNbr-1)*32)+12);
* ui_Command = ui_Command & 0xFFFFF9FEUL;
*/
outl(ui_Command,
devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 12);
} /* if (data[1]==0) */
if (data[0] == 3) /* stop all Watchdogs */
{
ui_Command = 0;
for (i_Count = 1; i_Count <= 4; i_Count++) {
if (devpriv->b_TimerSelectMode == ADDIDATA_WATCHDOG) {
ui_Command = 0x2UL;
} else {
ui_Command = 0x10UL;
}
i_WatchdogNbr = i_Count;
outl(ui_Command,
devpriv->iobase + ((i_WatchdogNbr - 1) * 32) +
0);
}
}
if (data[0] == 4) /* start all Watchdogs */
{
ui_Command = 0;
for (i_Count = 1; i_Count <= 4; i_Count++) {
if (devpriv->b_TimerSelectMode == ADDIDATA_WATCHDOG) {
ui_Command = 0x1UL;
} else {
ui_Command = 0x8UL;
}
i_WatchdogNbr = i_Count;
outl(ui_Command,
devpriv->iobase + ((i_WatchdogNbr - 1) * 32) +
0);
}
}
if (data[0] == 5) /* trigger all Watchdogs */
{
ui_Command = 0;
for (i_Count = 1; i_Count <= 4; i_Count++) {
if (devpriv->b_TimerSelectMode == ADDIDATA_WATCHDOG) {
ui_Command = 0x4UL;
} else {
ui_Command = 0x20UL;
}
i_WatchdogNbr = i_Count;
outl(ui_Command,
devpriv->iobase + ((i_WatchdogNbr - 1) * 32) +
0);
}
i_Temp = 1;
}
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI035_ReadTimerWatchdog |
| (struct comedi_device *dev,struct comedi_subdevice *s, |
| struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Read The Selected Timer , Counter or Watchdog |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| unsigned int *data : Data Pointer contains |
| configuration parameters as below |
| |
| |
+----------------------------------------------------------------------------+
| Output Parameters : data[0] : software trigger status
| data[1] : hardware trigger status
| data[2] : Software clear status
| data[3] : Overflow status
| data[4] : Timer actual value
|
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
int i_APCI035_ReadTimerWatchdog(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int ui_Status = 0; /* Status register */
i_WatchdogNbr = insn->unused[0];
/******************/
/* Get the status */
/******************/
ui_Status = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 16);
/***********************************/
/* Get the software trigger status */
/***********************************/
data[0] = ((ui_Status >> 1) & 1);
/***********************************/
/* Get the hardware trigger status */
/***********************************/
data[1] = ((ui_Status >> 2) & 1);
/*********************************/
/* Get the software clear status */
/*********************************/
data[2] = ((ui_Status >> 3) & 1);
/***************************/
/* Get the overflow status */
/***************************/
data[3] = ((ui_Status >> 0) & 1);
if (devpriv->b_TimerSelectMode == ADDIDATA_TIMER) {
data[4] = inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 0);
} /* if (devpriv->b_TimerSelectMode==ADDIDATA_TIMER) */
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI035_ConfigAnalogInput |
| (struct comedi_device *dev,struct comedi_subdevice *s, |
| struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Configures The Analog Input Subdevice |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| struct comedi_subdevice *s : Subdevice Pointer |
| struct comedi_insn *insn : Insn Structure Pointer |
| unsigned int *data : Data Pointer contains |
| configuration parameters as below |
| data[0] : Warning delay value
| |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
int i_APCI035_ConfigAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
devpriv->tsk_Current = current;
outl(0x200 | 0, devpriv->iobase + 128 + 0x4);
outl(0, devpriv->iobase + 128 + 0);
/********************************/
/* Initialise the warning value */
/********************************/
outl(0x300 | 0, devpriv->iobase + 128 + 0x4);
outl((data[0] << 8), devpriv->iobase + 128 + 0);
outl(0x200000UL, devpriv->iobase + 128 + 12);
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI035_ReadAnalogInput |
| (struct comedi_device *dev,struct comedi_subdevice *s, |
| struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Read value of the selected channel |
+----------------------------------------------------------------------------+
| Input Parameters : struct comedi_device *dev : Driver handle |
| unsigned int ui_NoOfChannels : No Of Channels To read |
| unsigned int *data : Data Pointer to read status |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
| data[0] : Digital Value Of Input |
| |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
int i_APCI035_ReadAnalogInput(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned int ui_CommandRegister = 0;
/******************/
/* Set the start */
/******************/
ui_CommandRegister = 0x80000;
/******************************/
/* Write the command register */
/******************************/
outl(ui_CommandRegister, devpriv->iobase + 128 + 8);
/***************************************/
/* Read the digital value of the input */
/***************************************/
data[0] = inl(devpriv->iobase + 128 + 28);
return insn->n;
}
/*
+----------------------------------------------------------------------------+
| Function Name : int i_APCI035_Reset(struct comedi_device *dev) |
| |
+----------------------------------------------------------------------------+
| Task :Resets the registers of the card |
+----------------------------------------------------------------------------+
| Input Parameters : |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : |
| |
+----------------------------------------------------------------------------+
*/
int i_APCI035_Reset(struct comedi_device *dev)
{
int i_Count = 0;
for (i_Count = 1; i_Count <= 4; i_Count++) {
i_WatchdogNbr = i_Count;
outl(0x0, devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 0); /* stop all timers */
}
outl(0x0, devpriv->iobase + 128 + 12); /* Disable the warning delay */
return 0;
}
/*
+----------------------------------------------------------------------------+
| Function Name : static void v_APCI035_Interrupt |
| (int irq , void *d) |
+----------------------------------------------------------------------------+
| Task : Interrupt processing Routine |
+----------------------------------------------------------------------------+
| Input Parameters : int irq : irq number |
| void *d : void pointer |
+----------------------------------------------------------------------------+
| Output Parameters : -- |
+----------------------------------------------------------------------------+
| Return Value : TRUE : No error occur |
| : FALSE : Error occur. Return the error |
| |
+----------------------------------------------------------------------------+
*/
static void v_APCI035_Interrupt(int irq, void *d)
{
struct comedi_device *dev = d;
unsigned int ui_StatusRegister1 = 0;
unsigned int ui_StatusRegister2 = 0;
unsigned int ui_ReadCommand = 0;
unsigned int ui_ChannelNumber = 0;
unsigned int ui_DigitalTemperature = 0;
if (i_Temp == 1) {
i_WatchdogNbr = i_Flag;
i_Flag = i_Flag + 1;
}
/**************************************/
/* Read the interrupt status register of temperature Warning */
/**************************************/
ui_StatusRegister1 = inl(devpriv->iobase + 128 + 16);
/**************************************/
/* Read the interrupt status register for Watchdog/timer */
/**************************************/
ui_StatusRegister2 =
inl(devpriv->iobase + ((i_WatchdogNbr - 1) * 32) + 20);
if ((((ui_StatusRegister1) & 0x8) == 0x8)) /* Test if warning relay interrupt */
{
/**********************************/
/* Disable the temperature warning */
/**********************************/
ui_ReadCommand = inl(devpriv->iobase + 128 + 12);
ui_ReadCommand = ui_ReadCommand & 0xFFDF0000UL;
outl(ui_ReadCommand, devpriv->iobase + 128 + 12);
/***************************/
/* Read the channel number */
/***************************/
ui_ChannelNumber = inl(devpriv->iobase + 128 + 60);
/**************************************/
/* Read the digital temperature value */
/**************************************/
ui_DigitalTemperature = inl(devpriv->iobase + 128 + 60);
send_sig(SIGIO, devpriv->tsk_Current, 0); /* send signal to the sample */
} /* if (((ui_StatusRegister1 & 0x8) == 0x8)) */
else {
if ((ui_StatusRegister2 & 0x1) == 0x1) {
send_sig(SIGIO, devpriv->tsk_Current, 0); /* send signal to the sample */
}
} /* else if (((ui_StatusRegister1 & 0x8) == 0x8)) */
return;
}
| gpl-2.0 |
ausdim/boeffla-kernel-jb-u8-s3 | drivers/staging/comedi/drivers/addi-data/APCI1710_Pwm.c | 8324 | 110860 | /**
@verbatim
Copyright (C) 2004,2005 ADDI-DATA GmbH for the source code of this module.
ADDI-DATA GmbH
Dieselstrasse 3
D-77833 Ottersweier
Tel: +19(0)7223/9493-0
Fax: +49(0)7223/9493-92
http://www.addi-data.com
info@addi-data.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
You should also find the complete GPL in the COPYING file accompanying this source code.
@endverbatim
*/
/*
+-----------------------------------------------------------------------+
| (C) ADDI-DATA GmbH Dieselstraße 3 D-77833 Ottersweier |
+-----------------------------------------------------------------------+
| Tel : +49 (0) 7223/9493-0 | email : info@addi-data.com |
| Fax : +49 (0) 7223/9493-92 | Internet : http://www.addi-data.com |
+-----------------------------------------------------------------------+
| Project : API APCI1710 | Compiler : gcc |
| Module name : PWM.C | Version : 2.96 |
+-------------------------------+---------------------------------------+
| Project manager: Eric Stolz | Date : 02/12/2002 |
+-----------------------------------------------------------------------+
| Description : APCI-1710 Wulse wide modulation module |
| |
| |
+-----------------------------------------------------------------------+
| UPDATES |
+-----------------------------------------------------------------------+
| Date | Author | Description of updates |
+-----------------------------------------------------------------------+
| 08/05/00 | Guinot C | - 0400/0228 All Function in RING 0 |
| | | available |
+-----------------------------------------------------------------------+
*/
/*
+----------------------------------------------------------------------------+
| Included files |
+----------------------------------------------------------------------------+
*/
#include "APCI1710_Pwm.h"
/*
+----------------------------------------------------------------------------+
| Function Name :INT i_APCI1710_InsnConfigPWM(struct comedi_device *dev,
struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Pwm Init and Get Pwm Initialisation |
+----------------------------------------------------------------------------+
| Input Parameters :
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value :
+----------------------------------------------------------------------------+
*/
int i_APCI1710_InsnConfigPWM(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned char b_ConfigType;
int i_ReturnValue = 0;
b_ConfigType = CR_CHAN(insn->chanspec);
switch (b_ConfigType) {
case APCI1710_PWM_INIT:
i_ReturnValue = i_APCI1710_InitPWM(dev, (unsigned char) CR_AREF(insn->chanspec), /* b_ModulNbr */
(unsigned char) data[0], /* b_PWM */
(unsigned char) data[1], /* b_ClockSelection */
(unsigned char) data[2], /* b_TimingUnit */
(unsigned int) data[3], /* ul_LowTiming */
(unsigned int) data[4], /* ul_HighTiming */
(unsigned int *) &data[0], /* pul_RealLowTiming */
(unsigned int *) &data[1] /* pul_RealHighTiming */
);
break;
case APCI1710_PWM_GETINITDATA:
i_ReturnValue = i_APCI1710_GetPWMInitialisation(dev, (unsigned char) CR_AREF(insn->chanspec), /* b_ModulNbr */
(unsigned char) data[0], /* b_PWM */
(unsigned char *) &data[0], /* pb_TimingUnit */
(unsigned int *) &data[1], /* pul_LowTiming */
(unsigned int *) &data[2], /* pul_HighTiming */
(unsigned char *) &data[3], /* pb_StartLevel */
(unsigned char *) &data[4], /* pb_StopMode */
(unsigned char *) &data[5], /* pb_StopLevel */
(unsigned char *) &data[6], /* pb_ExternGate */
(unsigned char *) &data[7], /* pb_InterruptEnable */
(unsigned char *) &data[8] /* pb_Enable */
);
break;
default:
printk(" Config Parameter Wrong\n");
}
if (i_ReturnValue >= 0)
i_ReturnValue = insn->n;
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : _INT_ i_APCI1710_InitPWM |
| (unsigned char_ b_BoardHandle, |
| unsigned char_ b_ModulNbr, |
| unsigned char_ b_PWM, |
| unsigned char_ b_ClockSelection, |
| unsigned char_ b_TimingUnit, |
| ULONG_ ul_LowTiming, |
| ULONG_ ul_HighTiming, |
| PULONG_ pul_RealLowTiming, |
| PULONG_ pul_RealHighTiming) |
+----------------------------------------------------------------------------+
| Task : Configure the selected PWM (b_PWM) from selected module|
| (b_ModulNbr). The ul_LowTiming, ul_HighTiming and |
| ul_TimingUnit determine the low/high timing base for |
| the period. pul_RealLowTiming, pul_RealHighTiming |
| return the real timing value. |
| You must calling this function be for you call any |
| other function witch access of the PWM. |
+----------------------------------------------------------------------------+
| Input Parameters : unsigned char_ b_BoardHandle : Handle of board APCI-1710 |
| unsigned char_ b_ModulNbr : Module number to configure|
| (0 to 3) |
| unsigned char_ b_PWM : Selected PWM (0 or 1). |
| unsigned char_ b_ClockSelection : Selection from PCI bus |
| clock |
| - APCI1710_30MHZ : |
| The PC have a 30 MHz |
| PCI bus clock |
| - APCI1710_33MHZ : |
| The PC have a 33 MHz |
| PCI bus clock |
| - APCI1710_40MHZ |
| The APCI-1710 have a |
| integrated 40Mhz |
| quartz. |
| unsigned char_ b_TimingUnit : Base timing Unit (0 to 4) |
| 0 : ns |
| 1 : æs |
| 2 : ms |
| 3 : s |
| 4 : mn |
| ULONG_ ul_LowTiming : Low base timing value. |
| ULONG_ ul_HighTiming : High base timing value. |
+----------------------------------------------------------------------------+
| Output Parameters : PULONG_ pul_RealLowTiming : Real low base timing |
| value. |
| PULONG_ pul_RealHighTiming : Real high base timing |
| value. |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: Module selection wrong |
| -3: The module is not a PWM module |
| -4: PWM selection is wrong |
| -5: The selected input clock is wrong |
| -6: Timing Unit selection is wrong |
| -7: Low base timing selection is wrong |
| -8: High base timing selection is wrong |
| -9: You can not used the 40MHz clock selection with |
| this board |
+----------------------------------------------------------------------------+
*/
int i_APCI1710_InitPWM(struct comedi_device *dev,
unsigned char b_ModulNbr,
unsigned char b_PWM,
unsigned char b_ClockSelection,
unsigned char b_TimingUnit,
unsigned int ul_LowTiming,
unsigned int ul_HighTiming,
unsigned int *pul_RealLowTiming, unsigned int *pul_RealHighTiming)
{
int i_ReturnValue = 0;
unsigned int ul_LowTimerValue = 0;
unsigned int ul_HighTimerValue = 0;
unsigned int dw_Command;
double d_RealLowTiming = 0;
double d_RealHighTiming = 0;
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/***************/
/* Test if PWM */
/***************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_PWM) {
/**************************/
/* Test the PWM selection */
/**************************/
if (b_PWM <= 1) {
/******************/
/* Test the clock */
/******************/
if ((b_ClockSelection == APCI1710_30MHZ) ||
(b_ClockSelection == APCI1710_33MHZ) ||
(b_ClockSelection == APCI1710_40MHZ)) {
/************************/
/* Test the timing unit */
/************************/
if (b_TimingUnit <= 4) {
/*********************************/
/* Test the low timing selection */
/*********************************/
if (((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 0)
&& (ul_LowTiming
>= 266)
&& (ul_LowTiming
<=
0xFFFFFFFFUL))
|| ((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 1)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
571230650UL))
|| ((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 2)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
571230UL))
|| ((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 3)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
571UL))
|| ((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 4)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<= 9UL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 0)
&& (ul_LowTiming
>= 242)
&& (ul_LowTiming
<=
0xFFFFFFFFUL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 1)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
519691043UL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 2)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
519691UL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 3)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
520UL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 4)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<= 8UL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 0)
&& (ul_LowTiming
>= 200)
&& (ul_LowTiming
<=
0xFFFFFFFFUL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 1)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
429496729UL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 2)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
429496UL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 3)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
429UL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 4)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
7UL))) {
/**********************************/
/* Test the High timing selection */
/**********************************/
if (((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 266) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571230650UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571230UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 9UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 242) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 519691043UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 519691UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 520UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 8UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 200) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429496729UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429496UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 7UL))) {
/**************************/
/* Test the board version */
/**************************/
if (((b_ClockSelection == APCI1710_40MHZ) && (devpriv->s_BoardInfos.b_BoardVersion > 0)) || (b_ClockSelection != APCI1710_40MHZ)) {
/************************************/
/* Calculate the low division fator */
/************************************/
fpu_begin
();
switch (b_TimingUnit) {
/******/
/* ns */
/******/
case 0:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
(unsigned int)
(ul_LowTiming
*
(0.00025 * b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_LowTiming * (0.00025 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(0.00025 * (double)b_ClockSelection));
d_RealLowTiming
=
(double)
ul_LowTimerValue
/
(0.00025
*
(double)
b_ClockSelection);
if ((double)((double)ul_LowTimerValue / (0.00025 * (double)b_ClockSelection)) >= (double)((double)*pul_RealLowTiming + 0.5)) {
*pul_RealLowTiming
=
*pul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
/******/
/* æs */
/******/
case 1:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
(unsigned int)
(ul_LowTiming
*
(0.25 * b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_LowTiming * (0.25 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(0.25 * (double)b_ClockSelection));
d_RealLowTiming
=
(double)
ul_LowTimerValue
/
(
(double)
0.25
*
(double)
b_ClockSelection);
if ((double)((double)ul_LowTimerValue / (0.25 * (double)b_ClockSelection)) >= (double)((double)*pul_RealLowTiming + 0.5)) {
*pul_RealLowTiming
=
*pul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
/******/
/* ms */
/******/
case 2:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
ul_LowTiming
*
(250.0
*
b_ClockSelection);
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_LowTiming * (250.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(250.0 * (double)b_ClockSelection));
d_RealLowTiming
=
(double)
ul_LowTimerValue
/
(250.0
*
(double)
b_ClockSelection);
if ((double)((double)ul_LowTimerValue / (250.0 * (double)b_ClockSelection)) >= (double)((double)*pul_RealLowTiming + 0.5)) {
*pul_RealLowTiming
=
*pul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
/*****/
/* s */
/*****/
case 3:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
(unsigned int)
(ul_LowTiming
*
(250000.0
*
b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_LowTiming * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(250000.0
*
(double)
b_ClockSelection));
d_RealLowTiming
=
(double)
ul_LowTimerValue
/
(250000.0
*
(double)
b_ClockSelection);
if ((double)((double)ul_LowTimerValue / (250000.0 * (double)b_ClockSelection)) >= (double)((double)*pul_RealLowTiming + 0.5)) {
*pul_RealLowTiming
=
*pul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
/******/
/* mn */
/******/
case 4:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
(unsigned int)
(
(ul_LowTiming
*
60)
*
(250000.0
*
b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)(ul_LowTiming * 60.0) * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(250000.0
*
(double)
b_ClockSelection))
/
60;
d_RealLowTiming
=
(
(double)
ul_LowTimerValue
/
(250000.0
*
(double)
b_ClockSelection))
/
60.0;
if ((double)(((double)ul_LowTimerValue / (250000.0 * (double)b_ClockSelection)) / 60.0) >= (double)((double)*pul_RealLowTiming + 0.5)) {
*pul_RealLowTiming
=
*pul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
}
/*************************************/
/* Calculate the high division fator */
/*************************************/
switch (b_TimingUnit) {
/******/
/* ns */
/******/
case 0:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
(unsigned int)
(ul_HighTiming
*
(0.00025 * b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_HighTiming * (0.00025 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(0.00025 * (double)b_ClockSelection));
d_RealHighTiming
=
(double)
ul_HighTimerValue
/
(0.00025
*
(double)
b_ClockSelection);
if ((double)((double)ul_HighTimerValue / (0.00025 * (double)b_ClockSelection)) >= (double)((double)*pul_RealHighTiming + 0.5)) {
*pul_RealHighTiming
=
*pul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
/******/
/* æs */
/******/
case 1:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
(unsigned int)
(ul_HighTiming
*
(0.25 * b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_HighTiming * (0.25 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(0.25 * (double)b_ClockSelection));
d_RealHighTiming
=
(double)
ul_HighTimerValue
/
(
(double)
0.25
*
(double)
b_ClockSelection);
if ((double)((double)ul_HighTimerValue / (0.25 * (double)b_ClockSelection)) >= (double)((double)*pul_RealHighTiming + 0.5)) {
*pul_RealHighTiming
=
*pul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
/******/
/* ms */
/******/
case 2:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
ul_HighTiming
*
(250.0
*
b_ClockSelection);
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_HighTiming * (250.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(250.0 * (double)b_ClockSelection));
d_RealHighTiming
=
(double)
ul_HighTimerValue
/
(250.0
*
(double)
b_ClockSelection);
if ((double)((double)ul_HighTimerValue / (250.0 * (double)b_ClockSelection)) >= (double)((double)*pul_RealHighTiming + 0.5)) {
*pul_RealHighTiming
=
*pul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
/*****/
/* s */
/*****/
case 3:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
(unsigned int)
(ul_HighTiming
*
(250000.0
*
b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_HighTiming * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(250000.0
*
(double)
b_ClockSelection));
d_RealHighTiming
=
(double)
ul_HighTimerValue
/
(250000.0
*
(double)
b_ClockSelection);
if ((double)((double)ul_HighTimerValue / (250000.0 * (double)b_ClockSelection)) >= (double)((double)*pul_RealHighTiming + 0.5)) {
*pul_RealHighTiming
=
*pul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
/******/
/* mn */
/******/
case 4:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
(unsigned int)
(
(ul_HighTiming
*
60)
*
(250000.0
*
b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)(ul_HighTiming * 60.0) * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
*pul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(250000.0
*
(double)
b_ClockSelection))
/
60;
d_RealHighTiming
=
(
(double)
ul_HighTimerValue
/
(250000.0
*
(double)
b_ClockSelection))
/
60.0;
if ((double)(((double)ul_HighTimerValue / (250000.0 * (double)b_ClockSelection)) / 60.0) >= (double)((double)*pul_RealHighTiming + 0.5)) {
*pul_RealHighTiming
=
*pul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
}
fpu_end();
/****************************/
/* Save the clock selection */
/****************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
b_ClockSelection
=
b_ClockSelection;
/************************/
/* Save the timing unit */
/************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
b_TimingUnit
=
b_TimingUnit;
/****************************/
/* Save the low base timing */
/****************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
d_LowTiming
=
d_RealLowTiming;
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
ul_RealLowTiming
=
*pul_RealLowTiming;
/****************************/
/* Save the high base timing */
/****************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
d_HighTiming
=
d_RealHighTiming;
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
ul_RealHighTiming
=
*pul_RealHighTiming;
/************************/
/* Write the low timing */
/************************/
outl(ul_LowTimerValue, devpriv->s_BoardInfos.ui_Address + 0 + (20 * b_PWM) + (64 * b_ModulNbr));
/*************************/
/* Write the high timing */
/*************************/
outl(ul_HighTimerValue, devpriv->s_BoardInfos.ui_Address + 4 + (20 * b_PWM) + (64 * b_ModulNbr));
/***************************/
/* Set the clock selection */
/***************************/
dw_Command
=
inl
(devpriv->
s_BoardInfos.
ui_Address
+
8
+
(20 * b_PWM) + (64 * b_ModulNbr));
dw_Command
=
dw_Command
&
0x7F;
if (b_ClockSelection == APCI1710_40MHZ) {
dw_Command
=
dw_Command
|
0x80;
}
/***************************/
/* Set the clock selection */
/***************************/
outl(dw_Command, devpriv->s_BoardInfos.ui_Address + 8 + (20 * b_PWM) + (64 * b_ModulNbr));
/*************/
/* PWM init. */
/*************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
b_PWMInit
=
1;
} else {
/***************************************************/
/* You can not used the 40MHz clock selection with */
/* this board */
/***************************************************/
DPRINTK("You can not used the 40MHz clock selection with this board\n");
i_ReturnValue
=
-9;
}
} else {
/***************************************/
/* High base timing selection is wrong */
/***************************************/
DPRINTK("High base timing selection is wrong\n");
i_ReturnValue =
-8;
}
} else {
/**************************************/
/* Low base timing selection is wrong */
/**************************************/
DPRINTK("Low base timing selection is wrong\n");
i_ReturnValue = -7;
}
} /* if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
else {
/**********************************/
/* Timing unit selection is wrong */
/**********************************/
DPRINTK("Timing unit selection is wrong\n");
i_ReturnValue = -6;
} /* if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
} /* if ((b_ClockSelection == APCI1710_30MHZ) || (b_ClockSelection == APCI1710_33MHZ) || (b_ClockSelection == APCI1710_40MHZ)) */
else {
/*******************************/
/* The selected clock is wrong */
/*******************************/
DPRINTK("The selected clock is wrong\n");
i_ReturnValue = -5;
} /* if ((b_ClockSelection == APCI1710_30MHZ) || (b_ClockSelection == APCI1710_33MHZ) || (b_ClockSelection == APCI1710_40MHZ)) */
} /* if (b_PWM >= 0 && b_PWM <= 1) */
else {
/******************************/
/* Tor PWM selection is wrong */
/******************************/
DPRINTK("Tor PWM selection is wrong\n");
i_ReturnValue = -4;
} /* if (b_PWM >= 0 && b_PWM <= 1) */
} else {
/**********************************/
/* The module is not a PWM module */
/**********************************/
DPRINTK("The module is not a PWM module\n");
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
DPRINTK("Module number error\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : _INT_ i_APCI1710_GetPWMInitialisation |
| (unsigned char_ b_BoardHandle, |
| unsigned char_ b_ModulNbr, |
| unsigned char_ b_PWM, |
| unsigned char *_ pb_TimingUnit, |
| PULONG_ pul_LowTiming, |
| PULONG_ pul_HighTiming, |
| unsigned char *_ pb_StartLevel, |
| unsigned char *_ pb_StopMode, |
| unsigned char *_ pb_StopLevel, |
| unsigned char *_ pb_ExternGate, |
| unsigned char *_ pb_InterruptEnable, |
| unsigned char *_ pb_Enable) |
+----------------------------------------------------------------------------+
| Task : Return the PWM (b_PWM) initialisation from selected |
| module (b_ModulNbr). You must calling the |
| "i_APCI1710_InitPWM" function be for you call this |
| function. |
+----------------------------------------------------------------------------+
| Input Parameters : unsigned char_ b_BoardHandle : Handle of board APCI-1710 |
| unsigned char_ b_ModulNbr : Selected module number (0 to 3) |
| unsigned char_ b_PWM : Selected PWM (0 or 1) |
+----------------------------------------------------------------------------+
| Output Parameters : unsigned char *_ pb_TimingUnit : Base timing Unit (0 to 4) |
| 0 : ns |
| 1 : æs |
| 2 : ms |
| 3 : s |
| 4 : mn |
| PULONG_ pul_LowTiming : Low base timing value. |
| PULONG_ pul_HighTiming : High base timing value. |
| unsigned char *_ pb_StartLevel : Start period level |
| selection |
| 0 : The period start |
| with a low level |
| 1 : The period start |
| with a high level|
| unsigned char *_ pb_StopMode : Stop mode selection |
| 0 : The PWM is stopped |
| directly after the |
| "i_APCI1710_DisablePWM"|
| function and break the|
| last period |
| 1 : After the |
| "i_APCI1710_DisablePWM"|
| function the PWM is |
| stopped at the end |
| from last period cycle|
| unsigned char *_ pb_StopLevel : Stop PWM level selection |
| 0 : The output signal |
| keep the level after|
| the |
| "i_APCI1710_DisablePWM"|
| function |
| 1 : The output signal is|
| set to low after the|
| "i_APCI1710_DisablePWM"|
| function |
| 2 : The output signal is|
| set to high after |
| the |
| "i_APCI1710_DisablePWM"|
| function |
| unsigned char *_ pb_ExternGate : Extern gate action |
| selection |
| 0 : Extern gate signal |
| not used. |
| 1 : Extern gate signal |
| used. |
| unsigned char *_ pb_InterruptEnable : Enable or disable the PWM |
| interrupt. |
| - APCI1710_ENABLE : |
| Enable the PWM interrupt|
| A interrupt occur after |
| each period |
| - APCI1710_DISABLE : |
| Disable the PWM |
| interrupt |
| unsigned char *_ pb_Enable : Indicate if the PWM is |
| enabled or no |
| 0 : PWM not enabled |
| 1 : PWM enabled |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: Module selection wrong |
| -3: The module is not a PWM module |
| -4: PWM selection is wrong |
| -5: PWM not initialised see function |
| "i_APCI1710_InitPWM" |
+----------------------------------------------------------------------------+
*/
int i_APCI1710_GetPWMInitialisation(struct comedi_device *dev,
unsigned char b_ModulNbr,
unsigned char b_PWM,
unsigned char *pb_TimingUnit,
unsigned int *pul_LowTiming,
unsigned int *pul_HighTiming,
unsigned char *pb_StartLevel,
unsigned char *pb_StopMode,
unsigned char *pb_StopLevel,
unsigned char *pb_ExternGate, unsigned char *pb_InterruptEnable, unsigned char *pb_Enable)
{
int i_ReturnValue = 0;
unsigned int dw_Status;
unsigned int dw_Command;
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/***************/
/* Test if PWM */
/***************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_PWM) {
/**************************/
/* Test the PWM selection */
/**************************/
if (b_PWM <= 1) {
/***************************/
/* Test if PWM initialised */
/***************************/
dw_Status = inl(devpriv->s_BoardInfos.
ui_Address + 12 + (20 * b_PWM) +
(64 * b_ModulNbr));
if (dw_Status & 0x10) {
/***********************/
/* Read the low timing */
/***********************/
*pul_LowTiming =
inl(devpriv->s_BoardInfos.
ui_Address + 0 + (20 * b_PWM) +
(64 * b_ModulNbr));
/************************/
/* Read the high timing */
/************************/
*pul_HighTiming =
inl(devpriv->s_BoardInfos.
ui_Address + 4 + (20 * b_PWM) +
(64 * b_ModulNbr));
/********************/
/* Read the command */
/********************/
dw_Command = inl(devpriv->s_BoardInfos.
ui_Address + 8 + (20 * b_PWM) +
(64 * b_ModulNbr));
*pb_StartLevel =
(unsigned char) ((dw_Command >> 5) & 1);
*pb_StopMode =
(unsigned char) ((dw_Command >> 0) & 1);
*pb_StopLevel =
(unsigned char) ((dw_Command >> 1) & 1);
*pb_ExternGate =
(unsigned char) ((dw_Command >> 4) & 1);
*pb_InterruptEnable =
(unsigned char) ((dw_Command >> 3) & 1);
if (*pb_StopLevel) {
*pb_StopLevel =
*pb_StopLevel +
(unsigned char) ((dw_Command >>
2) & 1);
}
/********************/
/* Read the command */
/********************/
dw_Command = inl(devpriv->s_BoardInfos.
ui_Address + 8 + (20 * b_PWM) +
(64 * b_ModulNbr));
*pb_Enable =
(unsigned char) ((dw_Command >> 0) & 1);
*pb_TimingUnit = devpriv->
s_ModuleInfo[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo[b_PWM].b_TimingUnit;
} /* if (dw_Status & 0x10) */
else {
/***********************/
/* PWM not initialised */
/***********************/
DPRINTK("PWM not initialised\n");
i_ReturnValue = -5;
} /* if (dw_Status & 0x10) */
} /* if (b_PWM >= 0 && b_PWM <= 1) */
else {
/******************************/
/* Tor PWM selection is wrong */
/******************************/
DPRINTK("Tor PWM selection is wrong\n");
i_ReturnValue = -4;
} /* if (b_PWM >= 0 && b_PWM <= 1) */
} else {
/**********************************/
/* The module is not a PWM module */
/**********************************/
DPRINTK("The module is not a PWM module\n");
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
DPRINTK("Module number error\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name :INT i_APCI1710_InsnWritePWM(struct comedi_device *dev,
struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data) |
+----------------------------------------------------------------------------+
| Task : Pwm Enable Disable and Set New Timing |
+----------------------------------------------------------------------------+
| Input Parameters :
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value :
+----------------------------------------------------------------------------+
*/
int i_APCI1710_InsnWritePWM(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
unsigned char b_WriteType;
int i_ReturnValue = 0;
b_WriteType = CR_CHAN(insn->chanspec);
switch (b_WriteType) {
case APCI1710_PWM_ENABLE:
i_ReturnValue = i_APCI1710_EnablePWM(dev,
(unsigned char) CR_AREF(insn->chanspec),
(unsigned char) data[0],
(unsigned char) data[1],
(unsigned char) data[2],
(unsigned char) data[3], (unsigned char) data[4], (unsigned char) data[5]);
break;
case APCI1710_PWM_DISABLE:
i_ReturnValue = i_APCI1710_DisablePWM(dev,
(unsigned char) CR_AREF(insn->chanspec), (unsigned char) data[0]);
break;
case APCI1710_PWM_NEWTIMING:
i_ReturnValue = i_APCI1710_SetNewPWMTiming(dev,
(unsigned char) CR_AREF(insn->chanspec),
(unsigned char) data[0],
(unsigned char) data[1], (unsigned int) data[2], (unsigned int) data[3]);
break;
default:
printk("Write Config Parameter Wrong\n");
}
if (i_ReturnValue >= 0)
i_ReturnValue = insn->n;
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : _INT_ i_APCI1710_EnablePWM |
| (unsigned char_ b_BoardHandle, |
| unsigned char_ b_ModulNbr, |
| unsigned char_ b_PWM, |
| unsigned char_ b_StartLevel, |
| unsigned char_ b_StopMode, |
| unsigned char_ b_StopLevel, |
| unsigned char_ b_ExternGate, |
| unsigned char_ b_InterruptEnable) |
+----------------------------------------------------------------------------+
| Task : Enable the selected PWM (b_PWM) from selected module |
| (b_ModulNbr). You must calling the "i_APCI1710_InitPWM"|
| function be for you call this function. |
| If you enable the PWM interrupt, the PWM generate a |
| interrupt after each period. |
| See function "i_APCI1710_SetBoardIntRoutineX" and the |
| Interrupt mask description chapter. |
+----------------------------------------------------------------------------+
| Input Parameters : unsigned char_ b_BoardHandle : Handle of board APCI-1710 |
| unsigned char_ b_ModulNbr : Selected module number |
| (0 to 3) |
| unsigned char_ b_PWM : Selected PWM (0 or 1) |
| unsigned char_ b_StartLevel : Start period level selection |
| 0 : The period start with a |
| low level |
| 1 : The period start with a |
| high level |
| unsigned char_ b_StopMode : Stop mode selection |
| 0 : The PWM is stopped |
| directly after the |
| "i_APCI1710_DisablePWM" |
| function and break the |
| last period |
| 1 : After the |
| "i_APCI1710_DisablePWM" |
| function the PWM is |
| stopped at the end from|
| last period cycle. |
| unsigned char_ b_StopLevel : Stop PWM level selection |
| 0 : The output signal keep |
| the level after the |
| "i_APCI1710_DisablePWM" |
| function |
| 1 : The output signal is set|
| to low after the |
| "i_APCI1710_DisablePWM" |
| function |
| 2 : The output signal is set|
| to high after the |
| "i_APCI1710_DisablePWM" |
| function |
| unsigned char_ b_ExternGate : Extern gate action selection |
| 0 : Extern gate signal not |
| used. |
| 1 : Extern gate signal used.|
| unsigned char_ b_InterruptEnable : Enable or disable the PWM |
| interrupt. |
| - APCI1710_ENABLE : |
| Enable the PWM interrupt |
| A interrupt occur after |
| each period |
| - APCI1710_DISABLE : |
| Disable the PWM interrupt |
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: Module selection wrong |
| -3: The module is not a PWM module |
| -4: PWM selection is wrong |
| -5: PWM not initialised see function |
| "i_APCI1710_InitPWM" |
| -6: PWM start level selection is wrong |
| -7: PWM stop mode selection is wrong |
| -8: PWM stop level selection is wrong |
| -9: Extern gate signal selection is wrong |
| -10: Interrupt parameter is wrong |
| -11: Interrupt function not initialised. |
| See function "i_APCI1710_SetBoardIntRoutineX" |
+----------------------------------------------------------------------------+
*/
int i_APCI1710_EnablePWM(struct comedi_device *dev,
unsigned char b_ModulNbr,
unsigned char b_PWM,
unsigned char b_StartLevel,
unsigned char b_StopMode,
unsigned char b_StopLevel, unsigned char b_ExternGate, unsigned char b_InterruptEnable)
{
int i_ReturnValue = 0;
unsigned int dw_Status;
unsigned int dw_Command;
devpriv->tsk_Current = current; /* Save the current process task structure */
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/***************/
/* Test if PWM */
/***************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_PWM) {
/**************************/
/* Test the PWM selection */
/**************************/
if (b_PWM <= 1) {
/***************************/
/* Test if PWM initialised */
/***************************/
dw_Status = inl(devpriv->s_BoardInfos.
ui_Address + 12 + (20 * b_PWM) +
(64 * b_ModulNbr));
if (dw_Status & 0x10) {
/**********************************/
/* Test the start level selection */
/**********************************/
if (b_StartLevel <= 1) {
/**********************/
/* Test the stop mode */
/**********************/
if (b_StopMode <= 1) {
/***********************/
/* Test the stop level */
/***********************/
if (b_StopLevel <= 2) {
/*****************************/
/* Test the extern gate mode */
/*****************************/
if (b_ExternGate
<= 1) {
/*****************************/
/* Test the interrupt action */
/*****************************/
if (b_InterruptEnable == APCI1710_ENABLE || b_InterruptEnable == APCI1710_DISABLE) {
/******************************************/
/* Test if interrupt function initialised */
/******************************************/
/********************/
/* Read the command */
/********************/
dw_Command
=
inl
(devpriv->
s_BoardInfos.
ui_Address
+
8
+
(20 * b_PWM) + (64 * b_ModulNbr));
dw_Command
=
dw_Command
&
0x80;
/********************/
/* Make the command */
/********************/
dw_Command
=
dw_Command
|
b_StopMode
|
(b_InterruptEnable
<<
3)
|
(b_ExternGate
<<
4)
|
(b_StartLevel
<<
5);
if (b_StopLevel & 3) {
dw_Command
=
dw_Command
|
2;
if (b_StopLevel & 2) {
dw_Command
=
dw_Command
|
4;
}
}
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
b_InterruptEnable
=
b_InterruptEnable;
/*******************/
/* Set the command */
/*******************/
outl(dw_Command, devpriv->s_BoardInfos.ui_Address + 8 + (20 * b_PWM) + (64 * b_ModulNbr));
/******************/
/* Enable the PWM */
/******************/
outl(1, devpriv->s_BoardInfos.ui_Address + 12 + (20 * b_PWM) + (64 * b_ModulNbr));
} /* if (b_InterruptEnable == APCI1710_ENABLE || b_InterruptEnable == APCI1710_DISABLE) */
else {
/********************************/
/* Interrupt parameter is wrong */
/********************************/
DPRINTK("Interrupt parameter is wrong\n");
i_ReturnValue
=
-10;
} /* if (b_InterruptEnable == APCI1710_ENABLE || b_InterruptEnable == APCI1710_DISABLE) */
} /* if (b_ExternGate >= 0 && b_ExternGate <= 1) */
else {
/*****************************************/
/* Extern gate signal selection is wrong */
/*****************************************/
DPRINTK("Extern gate signal selection is wrong\n");
i_ReturnValue
=
-9;
} /* if (b_ExternGate >= 0 && b_ExternGate <= 1) */
} /* if (b_StopLevel >= 0 && b_StopLevel <= 2) */
else {
/*************************************/
/* PWM stop level selection is wrong */
/*************************************/
DPRINTK("PWM stop level selection is wrong\n");
i_ReturnValue =
-8;
} /* if (b_StopLevel >= 0 && b_StopLevel <= 2) */
} /* if (b_StopMode >= 0 && b_StopMode <= 1) */
else {
/************************************/
/* PWM stop mode selection is wrong */
/************************************/
DPRINTK("PWM stop mode selection is wrong\n");
i_ReturnValue = -7;
} /* if (b_StopMode >= 0 && b_StopMode <= 1) */
} /* if (b_StartLevel >= 0 && b_StartLevel <= 1) */
else {
/**************************************/
/* PWM start level selection is wrong */
/**************************************/
DPRINTK("PWM start level selection is wrong\n");
i_ReturnValue = -6;
} /* if (b_StartLevel >= 0 && b_StartLevel <= 1) */
} /* if (dw_Status & 0x10) */
else {
/***********************/
/* PWM not initialised */
/***********************/
DPRINTK("PWM not initialised\n");
i_ReturnValue = -5;
} /* if (dw_Status & 0x10) */
} /* if (b_PWM >= 0 && b_PWM <= 1) */
else {
/******************************/
/* Tor PWM selection is wrong */
/******************************/
DPRINTK("Tor PWM selection is wrong\n");
i_ReturnValue = -4;
} /* if (b_PWM >= 0 && b_PWM <= 1) */
} else {
/**********************************/
/* The module is not a PWM module */
/**********************************/
DPRINTK("The module is not a PWM module\n");
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
DPRINTK("Module number error\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : _INT_ i_APCI1710_DisablePWM (unsigned char_ b_BoardHandle, |
| unsigned char_ b_ModulNbr, |
| unsigned char_ b_PWM) |
+----------------------------------------------------------------------------+
| Task : Disable the selected PWM (b_PWM) from selected module |
| (b_ModulNbr). The output signal level depend of the |
| initialisation by the "i_APCI1710_EnablePWM". |
| See the b_StartLevel, b_StopMode and b_StopLevel |
| parameters from this function. |
+----------------------------------------------------------------------------+
| Input Parameters :BYTE_ b_BoardHandle : Handle of board APCI-1710 |
| unsigned char_ b_ModulNbr : Selected module number (0 to 3) |
| unsigned char_ b_PWM : Selected PWM (0 or 1) |
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: Module selection wrong |
| -3: The module is not a PWM module |
| -4: PWM selection is wrong |
| -5: PWM not initialised see function |
| "i_APCI1710_InitPWM" |
| -6: PWM not enabled see function |
| "i_APCI1710_EnablePWM" |
+----------------------------------------------------------------------------+
*/
int i_APCI1710_DisablePWM(struct comedi_device *dev, unsigned char b_ModulNbr, unsigned char b_PWM)
{
int i_ReturnValue = 0;
unsigned int dw_Status;
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/***************/
/* Test if PWM */
/***************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_PWM) {
/**************************/
/* Test the PWM selection */
/**************************/
if (b_PWM <= 1) {
/***************************/
/* Test if PWM initialised */
/***************************/
dw_Status = inl(devpriv->s_BoardInfos.
ui_Address + 12 + (20 * b_PWM) +
(64 * b_ModulNbr));
if (dw_Status & 0x10) {
/***********************/
/* Test if PWM enabled */
/***********************/
if (dw_Status & 0x1) {
/*******************/
/* Disable the PWM */
/*******************/
outl(0, devpriv->s_BoardInfos.
ui_Address + 12 +
(20 * b_PWM) +
(64 * b_ModulNbr));
} /* if (dw_Status & 0x1) */
else {
/*******************/
/* PWM not enabled */
/*******************/
DPRINTK("PWM not enabled\n");
i_ReturnValue = -6;
} /* if (dw_Status & 0x1) */
} /* if (dw_Status & 0x10) */
else {
/***********************/
/* PWM not initialised */
/***********************/
DPRINTK(" PWM not initialised\n");
i_ReturnValue = -5;
} /* if (dw_Status & 0x10) */
} /* if (b_PWM >= 0 && b_PWM <= 1) */
else {
/******************************/
/* Tor PWM selection is wrong */
/******************************/
DPRINTK("Tor PWM selection is wrong\n");
i_ReturnValue = -4;
} /* if (b_PWM >= 0 && b_PWM <= 1) */
} else {
/**********************************/
/* The module is not a PWM module */
/**********************************/
DPRINTK("The module is not a PWM module\n");
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
DPRINTK("Module number error\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : _INT_ i_APCI1710_SetNewPWMTiming |
| (unsigned char_ b_BoardHandle, |
| unsigned char_ b_ModulNbr, |
| unsigned char_ b_PWM, |
| unsigned char_ b_ClockSelection, |
| unsigned char_ b_TimingUnit, |
| ULONG_ ul_LowTiming, |
| ULONG_ ul_HighTiming) |
+----------------------------------------------------------------------------+
| Task : Set a new timing. The ul_LowTiming, ul_HighTiming and |
| ul_TimingUnit determine the low/high timing base for |
| the period. |
+----------------------------------------------------------------------------+
| Input Parameters : unsigned char_ b_BoardHandle : Handle of board APCI-1710 |
| unsigned char_ b_ModulNbr : Module number to configure|
| (0 to 3) |
| unsigned char_ b_PWM : Selected PWM (0 or 1). |
| unsigned char_ b_TimingUnit : Base timing Unit (0 to 4) |
| 0 : ns |
| 1 : æs |
| 2 : ms |
| 3 : s |
| 4 : mn |
| ULONG_ ul_LowTiming : Low base timing value. |
| ULONG_ ul_HighTiming : High base timing value. |
+----------------------------------------------------------------------------+
| Output Parameters : - |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: Module selection wrong |
| -3: The module is not a PWM module |
| -4: PWM selection is wrong |
| -5: PWM not initialised |
| -6: Timing Unit selection is wrong |
| -7: Low base timing selection is wrong |
| -8: High base timing selection is wrong |
+----------------------------------------------------------------------------+
*/
int i_APCI1710_SetNewPWMTiming(struct comedi_device *dev,
unsigned char b_ModulNbr,
unsigned char b_PWM, unsigned char b_TimingUnit, unsigned int ul_LowTiming, unsigned int ul_HighTiming)
{
unsigned char b_ClockSelection;
int i_ReturnValue = 0;
unsigned int ul_LowTimerValue = 0;
unsigned int ul_HighTimerValue = 0;
unsigned int ul_RealLowTiming = 0;
unsigned int ul_RealHighTiming = 0;
unsigned int dw_Status;
unsigned int dw_Command;
double d_RealLowTiming = 0;
double d_RealHighTiming = 0;
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/***************/
/* Test if PWM */
/***************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_PWM) {
/**************************/
/* Test the PWM selection */
/**************************/
if (b_PWM <= 1) {
/***************************/
/* Test if PWM initialised */
/***************************/
dw_Status = inl(devpriv->s_BoardInfos.
ui_Address + 12 + (20 * b_PWM) +
(64 * b_ModulNbr));
if (dw_Status & 0x10) {
b_ClockSelection = devpriv->
s_ModuleInfo[b_ModulNbr].
s_PWMModuleInfo.
b_ClockSelection;
/************************/
/* Test the timing unit */
/************************/
if (b_TimingUnit <= 4) {
/*********************************/
/* Test the low timing selection */
/*********************************/
if (((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 0)
&& (ul_LowTiming
>= 266)
&& (ul_LowTiming
<=
0xFFFFFFFFUL))
|| ((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 1)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
571230650UL))
|| ((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 2)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
571230UL))
|| ((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 3)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
571UL))
|| ((b_ClockSelection ==
APCI1710_30MHZ)
&& (b_TimingUnit
== 4)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<= 9UL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 0)
&& (ul_LowTiming
>= 242)
&& (ul_LowTiming
<=
0xFFFFFFFFUL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 1)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
519691043UL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 2)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
519691UL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 3)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
520UL))
|| ((b_ClockSelection ==
APCI1710_33MHZ)
&& (b_TimingUnit
== 4)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<= 8UL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 0)
&& (ul_LowTiming
>= 200)
&& (ul_LowTiming
<=
0xFFFFFFFFUL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 1)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
429496729UL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 2)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
429496UL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 3)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
429UL))
|| ((b_ClockSelection ==
APCI1710_40MHZ)
&& (b_TimingUnit
== 4)
&& (ul_LowTiming
>= 1)
&& (ul_LowTiming
<=
7UL))) {
/**********************************/
/* Test the High timing selection */
/**********************************/
if (((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 266) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571230650UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571230UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 571UL)) || ((b_ClockSelection == APCI1710_30MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 9UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 242) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 519691043UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 519691UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 520UL)) || ((b_ClockSelection == APCI1710_33MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 8UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 0) && (ul_HighTiming >= 200) && (ul_HighTiming <= 0xFFFFFFFFUL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 1) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429496729UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 2) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429496UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 3) && (ul_HighTiming >= 1) && (ul_HighTiming <= 429UL)) || ((b_ClockSelection == APCI1710_40MHZ) && (b_TimingUnit == 4) && (ul_HighTiming >= 1) && (ul_HighTiming <= 7UL))) {
/************************************/
/* Calculate the low division fator */
/************************************/
fpu_begin();
switch (b_TimingUnit) {
/******/
/* ns */
/******/
case 0:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
(unsigned int)
(ul_LowTiming
*
(0.00025 * b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_LowTiming * (0.00025 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(0.00025 * (double)b_ClockSelection));
d_RealLowTiming
=
(double)
ul_LowTimerValue
/
(0.00025
*
(double)
b_ClockSelection);
if ((double)((double)ul_LowTimerValue / (0.00025 * (double)b_ClockSelection)) >= (double)((double)ul_RealLowTiming + 0.5)) {
ul_RealLowTiming
=
ul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
/******/
/* æs */
/******/
case 1:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
(unsigned int)
(ul_LowTiming
*
(0.25 * b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_LowTiming * (0.25 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(0.25 * (double)b_ClockSelection));
d_RealLowTiming
=
(double)
ul_LowTimerValue
/
(
(double)
0.25
*
(double)
b_ClockSelection);
if ((double)((double)ul_LowTimerValue / (0.25 * (double)b_ClockSelection)) >= (double)((double)ul_RealLowTiming + 0.5)) {
ul_RealLowTiming
=
ul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
/******/
/* ms */
/******/
case 2:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
ul_LowTiming
*
(250.0
*
b_ClockSelection);
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_LowTiming * (250.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(250.0 * (double)b_ClockSelection));
d_RealLowTiming
=
(double)
ul_LowTimerValue
/
(250.0
*
(double)
b_ClockSelection);
if ((double)((double)ul_LowTimerValue / (250.0 * (double)b_ClockSelection)) >= (double)((double)ul_RealLowTiming + 0.5)) {
ul_RealLowTiming
=
ul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
/*****/
/* s */
/*****/
case 3:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
(unsigned int)
(ul_LowTiming
*
(250000.0
*
b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_LowTiming * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(250000.0
*
(double)
b_ClockSelection));
d_RealLowTiming
=
(double)
ul_LowTimerValue
/
(250000.0
*
(double)
b_ClockSelection);
if ((double)((double)ul_LowTimerValue / (250000.0 * (double)b_ClockSelection)) >= (double)((double)ul_RealLowTiming + 0.5)) {
ul_RealLowTiming
=
ul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
/******/
/* mn */
/******/
case 4:
/******************/
/* Timer 0 factor */
/******************/
ul_LowTimerValue
=
(unsigned int)
(
(ul_LowTiming
*
60)
*
(250000.0
*
b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)(ul_LowTiming * 60.0) * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_LowTimerValue + 0.5))) {
ul_LowTimerValue
=
ul_LowTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealLowTiming
=
(unsigned int)
(ul_LowTimerValue
/
(250000.0
*
(double)
b_ClockSelection))
/
60;
d_RealLowTiming
=
(
(double)
ul_LowTimerValue
/
(250000.0
*
(double)
b_ClockSelection))
/
60.0;
if ((double)(((double)ul_LowTimerValue / (250000.0 * (double)b_ClockSelection)) / 60.0) >= (double)((double)ul_RealLowTiming + 0.5)) {
ul_RealLowTiming
=
ul_RealLowTiming
+
1;
}
ul_LowTiming
=
ul_LowTiming
-
1;
ul_LowTimerValue
=
ul_LowTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_LowTimerValue
=
(unsigned int)
(
(double)
(ul_LowTimerValue)
*
1.007752288);
}
break;
}
/*************************************/
/* Calculate the high division fator */
/*************************************/
switch (b_TimingUnit) {
/******/
/* ns */
/******/
case 0:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
(unsigned int)
(ul_HighTiming
*
(0.00025 * b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_HighTiming * (0.00025 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(0.00025 * (double)b_ClockSelection));
d_RealHighTiming
=
(double)
ul_HighTimerValue
/
(0.00025
*
(double)
b_ClockSelection);
if ((double)((double)ul_HighTimerValue / (0.00025 * (double)b_ClockSelection)) >= (double)((double)ul_RealHighTiming + 0.5)) {
ul_RealHighTiming
=
ul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
/******/
/* æs */
/******/
case 1:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
(unsigned int)
(ul_HighTiming
*
(0.25 * b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_HighTiming * (0.25 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(0.25 * (double)b_ClockSelection));
d_RealHighTiming
=
(double)
ul_HighTimerValue
/
(
(double)
0.25
*
(double)
b_ClockSelection);
if ((double)((double)ul_HighTimerValue / (0.25 * (double)b_ClockSelection)) >= (double)((double)ul_RealHighTiming + 0.5)) {
ul_RealHighTiming
=
ul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
/******/
/* ms */
/******/
case 2:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
ul_HighTiming
*
(250.0
*
b_ClockSelection);
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_HighTiming * (250.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(250.0 * (double)b_ClockSelection));
d_RealHighTiming
=
(double)
ul_HighTimerValue
/
(250.0
*
(double)
b_ClockSelection);
if ((double)((double)ul_HighTimerValue / (250.0 * (double)b_ClockSelection)) >= (double)((double)ul_RealHighTiming + 0.5)) {
ul_RealHighTiming
=
ul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
/*****/
/* s */
/*****/
case 3:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
(unsigned int)
(ul_HighTiming
*
(250000.0
*
b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)ul_HighTiming * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(250000.0
*
(double)
b_ClockSelection));
d_RealHighTiming
=
(double)
ul_HighTimerValue
/
(250000.0
*
(double)
b_ClockSelection);
if ((double)((double)ul_HighTimerValue / (250000.0 * (double)b_ClockSelection)) >= (double)((double)ul_RealHighTiming + 0.5)) {
ul_RealHighTiming
=
ul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
/******/
/* mn */
/******/
case 4:
/******************/
/* Timer 0 factor */
/******************/
ul_HighTimerValue
=
(unsigned int)
(
(ul_HighTiming
*
60)
*
(250000.0
*
b_ClockSelection));
/*******************/
/* Round the value */
/*******************/
if ((double)((double)(ul_HighTiming * 60.0) * (250000.0 * (double)b_ClockSelection)) >= ((double)((double)ul_HighTimerValue + 0.5))) {
ul_HighTimerValue
=
ul_HighTimerValue
+
1;
}
/*****************************/
/* Calculate the real timing */
/*****************************/
ul_RealHighTiming
=
(unsigned int)
(ul_HighTimerValue
/
(250000.0
*
(double)
b_ClockSelection))
/
60;
d_RealHighTiming
=
(
(double)
ul_HighTimerValue
/
(250000.0
*
(double)
b_ClockSelection))
/
60.0;
if ((double)(((double)ul_HighTimerValue / (250000.0 * (double)b_ClockSelection)) / 60.0) >= (double)((double)ul_RealHighTiming + 0.5)) {
ul_RealHighTiming
=
ul_RealHighTiming
+
1;
}
ul_HighTiming
=
ul_HighTiming
-
1;
ul_HighTimerValue
=
ul_HighTimerValue
-
2;
if (b_ClockSelection != APCI1710_40MHZ) {
ul_HighTimerValue
=
(unsigned int)
(
(double)
(ul_HighTimerValue)
*
1.007752288);
}
break;
}
fpu_end();
/************************/
/* Save the timing unit */
/************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
b_TimingUnit
=
b_TimingUnit;
/****************************/
/* Save the low base timing */
/****************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
d_LowTiming
=
d_RealLowTiming;
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
ul_RealLowTiming
=
ul_RealLowTiming;
/****************************/
/* Save the high base timing */
/****************************/
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
d_HighTiming
=
d_RealHighTiming;
devpriv->
s_ModuleInfo
[b_ModulNbr].
s_PWMModuleInfo.
s_PWMInfo
[b_PWM].
ul_RealHighTiming
=
ul_RealHighTiming;
/************************/
/* Write the low timing */
/************************/
outl(ul_LowTimerValue, devpriv->s_BoardInfos.ui_Address + 0 + (20 * b_PWM) + (64 * b_ModulNbr));
/*************************/
/* Write the high timing */
/*************************/
outl(ul_HighTimerValue, devpriv->s_BoardInfos.ui_Address + 4 + (20 * b_PWM) + (64 * b_ModulNbr));
/***************************/
/* Set the clock selection */
/***************************/
dw_Command =
inl
(devpriv->
s_BoardInfos.
ui_Address
+ 8 +
(20 * b_PWM) + (64 * b_ModulNbr));
dw_Command =
dw_Command
& 0x7F;
if (b_ClockSelection == APCI1710_40MHZ) {
dw_Command
=
dw_Command
|
0x80;
}
/***************************/
/* Set the clock selection */
/***************************/
outl(dw_Command,
devpriv->
s_BoardInfos.
ui_Address
+ 8 +
(20 * b_PWM) + (64 * b_ModulNbr));
} else {
/***************************************/
/* High base timing selection is wrong */
/***************************************/
DPRINTK("High base timing selection is wrong\n");
i_ReturnValue =
-8;
}
} else {
/**************************************/
/* Low base timing selection is wrong */
/**************************************/
DPRINTK("Low base timing selection is wrong\n");
i_ReturnValue = -7;
}
} /* if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
else {
/**********************************/
/* Timing unit selection is wrong */
/**********************************/
DPRINTK("Timing unit selection is wrong\n");
i_ReturnValue = -6;
} /* if ((b_TimingUnit >= 0) && (b_TimingUnit <= 4)) */
} /* if (dw_Status & 0x10) */
else {
/***********************/
/* PWM not initialised */
/***********************/
DPRINTK("PWM not initialised\n");
i_ReturnValue = -5;
} /* if (dw_Status & 0x10) */
} /* if (b_PWM >= 0 && b_PWM <= 1) */
else {
/******************************/
/* Tor PWM selection is wrong */
/******************************/
DPRINTK("Tor PWM selection is wrong\n");
i_ReturnValue = -4;
} /* if (b_PWM >= 0 && b_PWM <= 1) */
} else {
/**********************************/
/* The module is not a PWM module */
/**********************************/
DPRINTK("The module is not a PWM module\n");
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
DPRINTK("Module number error\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
/*
+----------------------------------------------------------------------------+
| Function Name : _INT_ i_APCI1710_GetPWMStatus |
| (unsigned char_ b_BoardHandle, |
| unsigned char_ b_ModulNbr, |
| unsigned char_ b_PWM, |
| unsigned char *_ pb_PWMOutputStatus, |
| unsigned char *_ pb_ExternGateStatus) |
+----------------------------------------------------------------------------+
| Task : Return the status from selected PWM (b_PWM) from |
| selected module (b_ModulNbr). |
+----------------------------------------------------------------------------+
| Input Parameters : unsigned char_ b_BoardHandle : Handle of board APCI-1710 |
| unsigned char_ b_PWM : Selected PWM (0 or 1) |
| unsigned char_ b_ModulNbr : Selected module number (0 to 3)
b_ModulNbr =(unsigned char) CR_AREF(insn->chanspec);
b_PWM =(unsigned char) data[0];
|
+----------------------------------------------------------------------------+
| Output Parameters : unsigned char *_ pb_PWMOutputStatus : Return the PWM output |
| level status. |
| 0 : The PWM output level|
| is low. |
| 1 : The PWM output level|
| is high. |
| unsigned char *_ pb_ExternGateStatus : Return the extern gate |
| level status. |
| 0 : The extern gate is |
| low. |
| 1 : The extern gate is |
| high.
pb_PWMOutputStatus =(unsigned char *) data[0];
pb_ExternGateStatus =(unsigned char *) data[1]; |
+----------------------------------------------------------------------------+
| Return Value : 0: No error |
| -1: The handle parameter of the board is wrong |
| -2: Module selection wrong |
| -3: The module is not a PWM module |
| -4: PWM selection is wrong |
| -5: PWM not initialised see function |
| "i_APCI1710_InitPWM" |
| -6: PWM not enabled see function "i_APCI1710_EnablePWM"|
+----------------------------------------------------------------------------+
*/
int i_APCI1710_InsnReadGetPWMStatus(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i_ReturnValue = 0;
unsigned int dw_Status;
unsigned char b_ModulNbr;
unsigned char b_PWM;
unsigned char *pb_PWMOutputStatus;
unsigned char *pb_ExternGateStatus;
i_ReturnValue = insn->n;
b_ModulNbr = (unsigned char) CR_AREF(insn->chanspec);
b_PWM = (unsigned char) CR_CHAN(insn->chanspec);
pb_PWMOutputStatus = (unsigned char *) &data[0];
pb_ExternGateStatus = (unsigned char *) &data[1];
/**************************/
/* Test the module number */
/**************************/
if (b_ModulNbr < 4) {
/***************/
/* Test if PWM */
/***************/
if ((devpriv->s_BoardInfos.
dw_MolduleConfiguration[b_ModulNbr] &
0xFFFF0000UL) == APCI1710_PWM) {
/**************************/
/* Test the PWM selection */
/**************************/
if (b_PWM <= 1) {
/***************************/
/* Test if PWM initialised */
/***************************/
dw_Status = inl(devpriv->s_BoardInfos.
ui_Address + 12 + (20 * b_PWM) +
(64 * b_ModulNbr));
if (dw_Status & 0x10) {
/***********************/
/* Test if PWM enabled */
/***********************/
if (dw_Status & 0x1) {
*pb_PWMOutputStatus =
(unsigned char) ((dw_Status >> 7)
& 1);
*pb_ExternGateStatus =
(unsigned char) ((dw_Status >> 6)
& 1);
} /* if (dw_Status & 0x1) */
else {
/*******************/
/* PWM not enabled */
/*******************/
DPRINTK("PWM not enabled \n");
i_ReturnValue = -6;
} /* if (dw_Status & 0x1) */
} /* if (dw_Status & 0x10) */
else {
/***********************/
/* PWM not initialised */
/***********************/
DPRINTK("PWM not initialised\n");
i_ReturnValue = -5;
} /* if (dw_Status & 0x10) */
} /* if (b_PWM >= 0 && b_PWM <= 1) */
else {
/******************************/
/* Tor PWM selection is wrong */
/******************************/
DPRINTK("Tor PWM selection is wrong\n");
i_ReturnValue = -4;
} /* if (b_PWM >= 0 && b_PWM <= 1) */
} else {
/**********************************/
/* The module is not a PWM module */
/**********************************/
DPRINTK("The module is not a PWM module\n");
i_ReturnValue = -3;
}
} else {
/***********************/
/* Module number error */
/***********************/
DPRINTK("Module number error\n");
i_ReturnValue = -2;
}
return i_ReturnValue;
}
int i_APCI1710_InsnBitsReadPWMInterrupt(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data)
{
data[0] = devpriv->s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.ui_Read].b_OldModuleMask;
data[1] = devpriv->s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.ui_Read].ul_OldInterruptMask;
data[2] = devpriv->s_InterruptParameters.
s_FIFOInterruptParameters[devpriv->
s_InterruptParameters.ui_Read].ul_OldCounterLatchValue;
/**************************/
/* Increment the read FIFO */
/***************************/
devpriv->
s_InterruptParameters.
ui_Read = (devpriv->
s_InterruptParameters.ui_Read + 1) % APCI1710_SAVE_INTERRUPT;
return insn->n;
}
| gpl-2.0 |
CyanogenMod/android_kernel_motorola_titan | drivers/rtc/rtc-msm6242.c | 8324 | 7580 | /*
* Oki MSM6242 RTC Driver
*
* Copyright 2009 Geert Uytterhoeven
*
* Based on the A2000 TOD code in arch/m68k/amiga/config.c
* Copyright (C) 1993 Hamish Macdonald
*/
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/rtc.h>
#include <linux/slab.h>
enum {
MSM6242_SECOND1 = 0x0, /* 1-second digit register */
MSM6242_SECOND10 = 0x1, /* 10-second digit register */
MSM6242_MINUTE1 = 0x2, /* 1-minute digit register */
MSM6242_MINUTE10 = 0x3, /* 10-minute digit register */
MSM6242_HOUR1 = 0x4, /* 1-hour digit register */
MSM6242_HOUR10 = 0x5, /* PM/AM, 10-hour digit register */
MSM6242_DAY1 = 0x6, /* 1-day digit register */
MSM6242_DAY10 = 0x7, /* 10-day digit register */
MSM6242_MONTH1 = 0x8, /* 1-month digit register */
MSM6242_MONTH10 = 0x9, /* 10-month digit register */
MSM6242_YEAR1 = 0xa, /* 1-year digit register */
MSM6242_YEAR10 = 0xb, /* 10-year digit register */
MSM6242_WEEK = 0xc, /* Week register */
MSM6242_CD = 0xd, /* Control Register D */
MSM6242_CE = 0xe, /* Control Register E */
MSM6242_CF = 0xf, /* Control Register F */
};
#define MSM6242_HOUR10_AM (0 << 2)
#define MSM6242_HOUR10_PM (1 << 2)
#define MSM6242_HOUR10_HR_MASK (3 << 0)
#define MSM6242_WEEK_SUNDAY 0
#define MSM6242_WEEK_MONDAY 1
#define MSM6242_WEEK_TUESDAY 2
#define MSM6242_WEEK_WEDNESDAY 3
#define MSM6242_WEEK_THURSDAY 4
#define MSM6242_WEEK_FRIDAY 5
#define MSM6242_WEEK_SATURDAY 6
#define MSM6242_CD_30_S_ADJ (1 << 3) /* 30-second adjustment */
#define MSM6242_CD_IRQ_FLAG (1 << 2)
#define MSM6242_CD_BUSY (1 << 1)
#define MSM6242_CD_HOLD (1 << 0)
#define MSM6242_CE_T_MASK (3 << 2)
#define MSM6242_CE_T_64HZ (0 << 2) /* period 1/64 second */
#define MSM6242_CE_T_1HZ (1 << 2) /* period 1 second */
#define MSM6242_CE_T_1MINUTE (2 << 2) /* period 1 minute */
#define MSM6242_CE_T_1HOUR (3 << 2) /* period 1 hour */
#define MSM6242_CE_ITRPT_STND (1 << 1)
#define MSM6242_CE_MASK (1 << 0) /* STD.P output control */
#define MSM6242_CF_TEST (1 << 3)
#define MSM6242_CF_12H (0 << 2)
#define MSM6242_CF_24H (1 << 2)
#define MSM6242_CF_STOP (1 << 1)
#define MSM6242_CF_REST (1 << 0) /* reset */
struct msm6242_priv {
u32 __iomem *regs;
struct rtc_device *rtc;
};
static inline unsigned int msm6242_read(struct msm6242_priv *priv,
unsigned int reg)
{
return __raw_readl(&priv->regs[reg]) & 0xf;
}
static inline void msm6242_write(struct msm6242_priv *priv, unsigned int val,
unsigned int reg)
{
__raw_writel(val, &priv->regs[reg]);
}
static inline void msm6242_set(struct msm6242_priv *priv, unsigned int val,
unsigned int reg)
{
msm6242_write(priv, msm6242_read(priv, reg) | val, reg);
}
static inline void msm6242_clear(struct msm6242_priv *priv, unsigned int val,
unsigned int reg)
{
msm6242_write(priv, msm6242_read(priv, reg) & ~val, reg);
}
static void msm6242_lock(struct msm6242_priv *priv)
{
int cnt = 5;
msm6242_set(priv, MSM6242_CD_HOLD, MSM6242_CD);
while ((msm6242_read(priv, MSM6242_CD) & MSM6242_CD_BUSY) && cnt) {
msm6242_clear(priv, MSM6242_CD_HOLD, MSM6242_CD);
udelay(70);
msm6242_set(priv, MSM6242_CD_HOLD, MSM6242_CD);
cnt--;
}
if (!cnt)
pr_warning("msm6242: timed out waiting for RTC (0x%x)\n",
msm6242_read(priv, MSM6242_CD));
}
static void msm6242_unlock(struct msm6242_priv *priv)
{
msm6242_clear(priv, MSM6242_CD_HOLD, MSM6242_CD);
}
static int msm6242_read_time(struct device *dev, struct rtc_time *tm)
{
struct msm6242_priv *priv = dev_get_drvdata(dev);
msm6242_lock(priv);
tm->tm_sec = msm6242_read(priv, MSM6242_SECOND10) * 10 +
msm6242_read(priv, MSM6242_SECOND1);
tm->tm_min = msm6242_read(priv, MSM6242_MINUTE10) * 10 +
msm6242_read(priv, MSM6242_MINUTE1);
tm->tm_hour = (msm6242_read(priv, MSM6242_HOUR10 & 3)) * 10 +
msm6242_read(priv, MSM6242_HOUR1);
tm->tm_mday = msm6242_read(priv, MSM6242_DAY10) * 10 +
msm6242_read(priv, MSM6242_DAY1);
tm->tm_wday = msm6242_read(priv, MSM6242_WEEK);
tm->tm_mon = msm6242_read(priv, MSM6242_MONTH10) * 10 +
msm6242_read(priv, MSM6242_MONTH1) - 1;
tm->tm_year = msm6242_read(priv, MSM6242_YEAR10) * 10 +
msm6242_read(priv, MSM6242_YEAR1);
if (tm->tm_year <= 69)
tm->tm_year += 100;
if (!(msm6242_read(priv, MSM6242_CF) & MSM6242_CF_24H)) {
unsigned int pm = msm6242_read(priv, MSM6242_HOUR10) &
MSM6242_HOUR10_PM;
if (!pm && tm->tm_hour == 12)
tm->tm_hour = 0;
else if (pm && tm->tm_hour != 12)
tm->tm_hour += 12;
}
msm6242_unlock(priv);
return rtc_valid_tm(tm);
}
static int msm6242_set_time(struct device *dev, struct rtc_time *tm)
{
struct msm6242_priv *priv = dev_get_drvdata(dev);
msm6242_lock(priv);
msm6242_write(priv, tm->tm_sec / 10, MSM6242_SECOND10);
msm6242_write(priv, tm->tm_sec % 10, MSM6242_SECOND1);
msm6242_write(priv, tm->tm_min / 10, MSM6242_MINUTE10);
msm6242_write(priv, tm->tm_min % 10, MSM6242_MINUTE1);
if (msm6242_read(priv, MSM6242_CF) & MSM6242_CF_24H)
msm6242_write(priv, tm->tm_hour / 10, MSM6242_HOUR10);
else if (tm->tm_hour >= 12)
msm6242_write(priv, MSM6242_HOUR10_PM + (tm->tm_hour - 12) / 10,
MSM6242_HOUR10);
else
msm6242_write(priv, tm->tm_hour / 10, MSM6242_HOUR10);
msm6242_write(priv, tm->tm_hour % 10, MSM6242_HOUR1);
msm6242_write(priv, tm->tm_mday / 10, MSM6242_DAY10);
msm6242_write(priv, tm->tm_mday % 10, MSM6242_DAY1);
if (tm->tm_wday != -1)
msm6242_write(priv, tm->tm_wday, MSM6242_WEEK);
msm6242_write(priv, (tm->tm_mon + 1) / 10, MSM6242_MONTH10);
msm6242_write(priv, (tm->tm_mon + 1) % 10, MSM6242_MONTH1);
if (tm->tm_year >= 100)
tm->tm_year -= 100;
msm6242_write(priv, tm->tm_year / 10, MSM6242_YEAR10);
msm6242_write(priv, tm->tm_year % 10, MSM6242_YEAR1);
msm6242_unlock(priv);
return 0;
}
static const struct rtc_class_ops msm6242_rtc_ops = {
.read_time = msm6242_read_time,
.set_time = msm6242_set_time,
};
static int __init msm6242_rtc_probe(struct platform_device *dev)
{
struct resource *res;
struct msm6242_priv *priv;
struct rtc_device *rtc;
int error;
res = platform_get_resource(dev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->regs = ioremap(res->start, resource_size(res));
if (!priv->regs) {
error = -ENOMEM;
goto out_free_priv;
}
platform_set_drvdata(dev, priv);
rtc = rtc_device_register("rtc-msm6242", &dev->dev, &msm6242_rtc_ops,
THIS_MODULE);
if (IS_ERR(rtc)) {
error = PTR_ERR(rtc);
goto out_unmap;
}
priv->rtc = rtc;
return 0;
out_unmap:
platform_set_drvdata(dev, NULL);
iounmap(priv->regs);
out_free_priv:
kfree(priv);
return error;
}
static int __exit msm6242_rtc_remove(struct platform_device *dev)
{
struct msm6242_priv *priv = platform_get_drvdata(dev);
rtc_device_unregister(priv->rtc);
iounmap(priv->regs);
kfree(priv);
return 0;
}
static struct platform_driver msm6242_rtc_driver = {
.driver = {
.name = "rtc-msm6242",
.owner = THIS_MODULE,
},
.remove = __exit_p(msm6242_rtc_remove),
};
static int __init msm6242_rtc_init(void)
{
return platform_driver_probe(&msm6242_rtc_driver, msm6242_rtc_probe);
}
static void __exit msm6242_rtc_fini(void)
{
platform_driver_unregister(&msm6242_rtc_driver);
}
module_init(msm6242_rtc_init);
module_exit(msm6242_rtc_fini);
MODULE_AUTHOR("Geert Uytterhoeven <geert@linux-m68k.org>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Oki MSM6242 RTC driver");
MODULE_ALIAS("platform:rtc-msm6242");
| gpl-2.0 |
jcadduono/nethunter_kernel_kccat6 | sound/pci/asihpi/hpi6205.c | 8324 | 65314 | /******************************************************************************
AudioScience HPI driver
Copyright (C) 1997-2011 AudioScience Inc. <support@audioscience.com>
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation;
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Hardware Programming Interface (HPI) for AudioScience
ASI50xx, AS51xx, ASI6xxx, ASI87xx ASI89xx series adapters.
These PCI and PCIe bus adapters are based on a
TMS320C6205 PCI bus mastering DSP,
and (except ASI50xx) TI TMS320C6xxx floating point DSP
Exported function:
void HPI_6205(struct hpi_message *phm, struct hpi_response *phr)
(C) Copyright AudioScience Inc. 1998-2010
*******************************************************************************/
#define SOURCEFILE_NAME "hpi6205.c"
#include "hpi_internal.h"
#include "hpimsginit.h"
#include "hpidebug.h"
#include "hpi6205.h"
#include "hpidspcd.h"
#include "hpicmn.h"
/*****************************************************************************/
/* HPI6205 specific error codes */
#define HPI6205_ERROR_BASE 1000 /* not actually used anywhere */
/* operational/messaging errors */
#define HPI6205_ERROR_MSG_RESP_IDLE_TIMEOUT 1015
#define HPI6205_ERROR_MSG_RESP_TIMEOUT 1016
/* initialization/bootload errors */
#define HPI6205_ERROR_6205_NO_IRQ 1002
#define HPI6205_ERROR_6205_INIT_FAILED 1003
#define HPI6205_ERROR_6205_REG 1006
#define HPI6205_ERROR_6205_DSPPAGE 1007
#define HPI6205_ERROR_C6713_HPIC 1009
#define HPI6205_ERROR_C6713_HPIA 1010
#define HPI6205_ERROR_C6713_PLL 1011
#define HPI6205_ERROR_DSP_INTMEM 1012
#define HPI6205_ERROR_DSP_EXTMEM 1013
#define HPI6205_ERROR_DSP_PLD 1014
#define HPI6205_ERROR_6205_EEPROM 1017
#define HPI6205_ERROR_DSP_EMIF1 1018
#define HPI6205_ERROR_DSP_EMIF2 1019
#define HPI6205_ERROR_DSP_EMIF3 1020
#define HPI6205_ERROR_DSP_EMIF4 1021
/*****************************************************************************/
/* for C6205 PCI i/f */
/* Host Status Register (HSR) bitfields */
#define C6205_HSR_INTSRC 0x01
#define C6205_HSR_INTAVAL 0x02
#define C6205_HSR_INTAM 0x04
#define C6205_HSR_CFGERR 0x08
#define C6205_HSR_EEREAD 0x10
/* Host-to-DSP Control Register (HDCR) bitfields */
#define C6205_HDCR_WARMRESET 0x01
#define C6205_HDCR_DSPINT 0x02
#define C6205_HDCR_PCIBOOT 0x04
/* DSP Page Register (DSPP) bitfields, */
/* defines 4 Mbyte page that BAR0 points to */
#define C6205_DSPP_MAP1 0x400
/* BAR0 maps to prefetchable 4 Mbyte memory block set by DSPP.
* BAR1 maps to non-prefetchable 8 Mbyte memory block
* of DSP memory mapped registers (starting at 0x01800000).
* 0x01800000 is hardcoded in the PCI i/f, so that only the offset from this
* needs to be added to the BAR1 base address set in the PCI config reg
*/
#define C6205_BAR1_PCI_IO_OFFSET (0x027FFF0L)
#define C6205_BAR1_HSR (C6205_BAR1_PCI_IO_OFFSET)
#define C6205_BAR1_HDCR (C6205_BAR1_PCI_IO_OFFSET+4)
#define C6205_BAR1_DSPP (C6205_BAR1_PCI_IO_OFFSET+8)
/* used to control LED (revA) and reset C6713 (revB) */
#define C6205_BAR0_TIMER1_CTL (0x01980000L)
/* For first 6713 in CE1 space, using DA17,16,2 */
#define HPICL_ADDR 0x01400000L
#define HPICH_ADDR 0x01400004L
#define HPIAL_ADDR 0x01410000L
#define HPIAH_ADDR 0x01410004L
#define HPIDIL_ADDR 0x01420000L
#define HPIDIH_ADDR 0x01420004L
#define HPIDL_ADDR 0x01430000L
#define HPIDH_ADDR 0x01430004L
#define C6713_EMIF_GCTL 0x01800000
#define C6713_EMIF_CE1 0x01800004
#define C6713_EMIF_CE0 0x01800008
#define C6713_EMIF_CE2 0x01800010
#define C6713_EMIF_CE3 0x01800014
#define C6713_EMIF_SDRAMCTL 0x01800018
#define C6713_EMIF_SDRAMTIMING 0x0180001C
#define C6713_EMIF_SDRAMEXT 0x01800020
struct hpi_hw_obj {
/* PCI registers */
__iomem u32 *prHSR;
__iomem u32 *prHDCR;
__iomem u32 *prDSPP;
u32 dsp_page;
struct consistent_dma_area h_locked_mem;
struct bus_master_interface *p_interface_buffer;
u16 flag_outstream_just_reset[HPI_MAX_STREAMS];
/* a non-NULL handle means there is an HPI allocated buffer */
struct consistent_dma_area instream_host_buffers[HPI_MAX_STREAMS];
struct consistent_dma_area outstream_host_buffers[HPI_MAX_STREAMS];
/* non-zero size means a buffer exists, may be external */
u32 instream_host_buffer_size[HPI_MAX_STREAMS];
u32 outstream_host_buffer_size[HPI_MAX_STREAMS];
struct consistent_dma_area h_control_cache;
struct hpi_control_cache *p_cache;
};
/*****************************************************************************/
/* local prototypes */
#define check_before_bbm_copy(status, p_bbm_data, l_first_write, l_second_write)
static int wait_dsp_ack(struct hpi_hw_obj *phw, int state, int timeout_us);
static void send_dsp_command(struct hpi_hw_obj *phw, int cmd);
static u16 adapter_boot_load_dsp(struct hpi_adapter_obj *pao,
u32 *pos_error_code);
static u16 message_response_sequence(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void hw_message(struct hpi_adapter_obj *pao, struct hpi_message *phm,
struct hpi_response *phr);
#define HPI6205_TIMEOUT 1000000
static void subsys_create_adapter(struct hpi_message *phm,
struct hpi_response *phr);
static void adapter_delete(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static u16 create_adapter_obj(struct hpi_adapter_obj *pao,
u32 *pos_error_code);
static void delete_adapter_obj(struct hpi_adapter_obj *pao);
static void outstream_host_buffer_allocate(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void outstream_host_buffer_get_info(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void outstream_host_buffer_free(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void outstream_write(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void outstream_get_info(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void outstream_start(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void outstream_open(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void outstream_reset(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void instream_host_buffer_allocate(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void instream_host_buffer_get_info(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void instream_host_buffer_free(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void instream_read(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void instream_get_info(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static void instream_start(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr);
static u32 boot_loader_read_mem32(struct hpi_adapter_obj *pao, int dsp_index,
u32 address);
static void boot_loader_write_mem32(struct hpi_adapter_obj *pao,
int dsp_index, u32 address, u32 data);
static u16 boot_loader_config_emif(struct hpi_adapter_obj *pao,
int dsp_index);
static u16 boot_loader_test_memory(struct hpi_adapter_obj *pao, int dsp_index,
u32 address, u32 length);
static u16 boot_loader_test_internal_memory(struct hpi_adapter_obj *pao,
int dsp_index);
static u16 boot_loader_test_external_memory(struct hpi_adapter_obj *pao,
int dsp_index);
static u16 boot_loader_test_pld(struct hpi_adapter_obj *pao, int dsp_index);
/*****************************************************************************/
static void subsys_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_SUBSYS_CREATE_ADAPTER:
subsys_create_adapter(phm, phr);
break;
default:
phr->error = HPI_ERROR_INVALID_FUNC;
break;
}
}
static void control_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
u16 pending_cache_error = 0;
switch (phm->function) {
case HPI_CONTROL_GET_STATE:
if (pao->has_control_cache) {
rmb(); /* make sure we see updates DMAed from DSP */
if (hpi_check_control_cache(phw->p_cache, phm, phr)) {
break;
} else if (phm->u.c.attribute == HPI_METER_PEAK) {
pending_cache_error =
HPI_ERROR_CONTROL_CACHING;
}
}
hw_message(pao, phm, phr);
if (pending_cache_error && !phr->error)
phr->error = pending_cache_error;
break;
case HPI_CONTROL_GET_INFO:
hw_message(pao, phm, phr);
break;
case HPI_CONTROL_SET_STATE:
hw_message(pao, phm, phr);
if (pao->has_control_cache)
hpi_cmn_control_cache_sync_to_msg(phw->p_cache, phm,
phr);
break;
default:
phr->error = HPI_ERROR_INVALID_FUNC;
break;
}
}
static void adapter_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
switch (phm->function) {
case HPI_ADAPTER_DELETE:
adapter_delete(pao, phm, phr);
break;
default:
hw_message(pao, phm, phr);
break;
}
}
static void outstream_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
if (phm->obj_index >= HPI_MAX_STREAMS) {
phr->error = HPI_ERROR_INVALID_OBJ_INDEX;
HPI_DEBUG_LOG(WARNING,
"Message referencing invalid stream %d "
"on adapter index %d\n", phm->obj_index,
phm->adapter_index);
return;
}
switch (phm->function) {
case HPI_OSTREAM_WRITE:
outstream_write(pao, phm, phr);
break;
case HPI_OSTREAM_GET_INFO:
outstream_get_info(pao, phm, phr);
break;
case HPI_OSTREAM_HOSTBUFFER_ALLOC:
outstream_host_buffer_allocate(pao, phm, phr);
break;
case HPI_OSTREAM_HOSTBUFFER_GET_INFO:
outstream_host_buffer_get_info(pao, phm, phr);
break;
case HPI_OSTREAM_HOSTBUFFER_FREE:
outstream_host_buffer_free(pao, phm, phr);
break;
case HPI_OSTREAM_START:
outstream_start(pao, phm, phr);
break;
case HPI_OSTREAM_OPEN:
outstream_open(pao, phm, phr);
break;
case HPI_OSTREAM_RESET:
outstream_reset(pao, phm, phr);
break;
default:
hw_message(pao, phm, phr);
break;
}
}
static void instream_message(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
if (phm->obj_index >= HPI_MAX_STREAMS) {
phr->error = HPI_ERROR_INVALID_OBJ_INDEX;
HPI_DEBUG_LOG(WARNING,
"Message referencing invalid stream %d "
"on adapter index %d\n", phm->obj_index,
phm->adapter_index);
return;
}
switch (phm->function) {
case HPI_ISTREAM_READ:
instream_read(pao, phm, phr);
break;
case HPI_ISTREAM_GET_INFO:
instream_get_info(pao, phm, phr);
break;
case HPI_ISTREAM_HOSTBUFFER_ALLOC:
instream_host_buffer_allocate(pao, phm, phr);
break;
case HPI_ISTREAM_HOSTBUFFER_GET_INFO:
instream_host_buffer_get_info(pao, phm, phr);
break;
case HPI_ISTREAM_HOSTBUFFER_FREE:
instream_host_buffer_free(pao, phm, phr);
break;
case HPI_ISTREAM_START:
instream_start(pao, phm, phr);
break;
default:
hw_message(pao, phm, phr);
break;
}
}
/*****************************************************************************/
/** Entry point to this HPI backend
* All calls to the HPI start here
*/
static
void _HPI_6205(struct hpi_adapter_obj *pao, struct hpi_message *phm,
struct hpi_response *phr)
{
if (pao && (pao->dsp_crashed >= 10)
&& (phm->function != HPI_ADAPTER_DEBUG_READ)) {
/* allow last resort debug read even after crash */
hpi_init_response(phr, phm->object, phm->function,
HPI_ERROR_DSP_HARDWARE);
HPI_DEBUG_LOG(WARNING, " %d,%d dsp crashed.\n", phm->object,
phm->function);
return;
}
/* Init default response */
if (phm->function != HPI_SUBSYS_CREATE_ADAPTER)
phr->error = HPI_ERROR_PROCESSING_MESSAGE;
HPI_DEBUG_LOG(VERBOSE, "start of switch\n");
switch (phm->type) {
case HPI_TYPE_REQUEST:
switch (phm->object) {
case HPI_OBJ_SUBSYSTEM:
subsys_message(pao, phm, phr);
break;
case HPI_OBJ_ADAPTER:
adapter_message(pao, phm, phr);
break;
case HPI_OBJ_CONTROL:
control_message(pao, phm, phr);
break;
case HPI_OBJ_OSTREAM:
outstream_message(pao, phm, phr);
break;
case HPI_OBJ_ISTREAM:
instream_message(pao, phm, phr);
break;
default:
hw_message(pao, phm, phr);
break;
}
break;
default:
phr->error = HPI_ERROR_INVALID_TYPE;
break;
}
}
void HPI_6205(struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_adapter_obj *pao = NULL;
if (phm->object != HPI_OBJ_SUBSYSTEM) {
/* normal messages must have valid adapter index */
pao = hpi_find_adapter(phm->adapter_index);
} else {
/* subsys messages don't address an adapter */
_HPI_6205(NULL, phm, phr);
return;
}
if (pao)
_HPI_6205(pao, phm, phr);
else
hpi_init_response(phr, phm->object, phm->function,
HPI_ERROR_BAD_ADAPTER_NUMBER);
}
/*****************************************************************************/
/* SUBSYSTEM */
/** Create an adapter object and initialise it based on resource information
* passed in in the message
* *** NOTE - you cannot use this function AND the FindAdapters function at the
* same time, the application must use only one of them to get the adapters ***
*/
static void subsys_create_adapter(struct hpi_message *phm,
struct hpi_response *phr)
{
/* create temp adapter obj, because we don't know what index yet */
struct hpi_adapter_obj ao;
u32 os_error_code;
u16 err;
HPI_DEBUG_LOG(DEBUG, " subsys_create_adapter\n");
memset(&ao, 0, sizeof(ao));
ao.priv = kzalloc(sizeof(struct hpi_hw_obj), GFP_KERNEL);
if (!ao.priv) {
HPI_DEBUG_LOG(ERROR, "can't get mem for adapter object\n");
phr->error = HPI_ERROR_MEMORY_ALLOC;
return;
}
ao.pci = *phm->u.s.resource.r.pci;
err = create_adapter_obj(&ao, &os_error_code);
if (err) {
delete_adapter_obj(&ao);
if (err >= HPI_ERROR_BACKEND_BASE) {
phr->error = HPI_ERROR_DSP_BOOTLOAD;
phr->specific_error = err;
} else {
phr->error = err;
}
phr->u.s.data = os_error_code;
return;
}
phr->u.s.adapter_type = ao.type;
phr->u.s.adapter_index = ao.index;
phr->error = 0;
}
/** delete an adapter - required by WDM driver */
static void adapter_delete(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw;
if (!pao) {
phr->error = HPI_ERROR_INVALID_OBJ_INDEX;
return;
}
phw = pao->priv;
/* reset adapter h/w */
/* Reset C6713 #1 */
boot_loader_write_mem32(pao, 0, C6205_BAR0_TIMER1_CTL, 0);
/* reset C6205 */
iowrite32(C6205_HDCR_WARMRESET, phw->prHDCR);
delete_adapter_obj(pao);
hpi_delete_adapter(pao);
phr->error = 0;
}
/** Create adapter object
allocate buffers, bootload DSPs, initialise control cache
*/
static u16 create_adapter_obj(struct hpi_adapter_obj *pao,
u32 *pos_error_code)
{
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface;
u32 phys_addr;
int i;
u16 err;
/* init error reporting */
pao->dsp_crashed = 0;
for (i = 0; i < HPI_MAX_STREAMS; i++)
phw->flag_outstream_just_reset[i] = 1;
/* The C6205 memory area 1 is 8Mbyte window into DSP registers */
phw->prHSR =
pao->pci.ap_mem_base[1] +
C6205_BAR1_HSR / sizeof(*pao->pci.ap_mem_base[1]);
phw->prHDCR =
pao->pci.ap_mem_base[1] +
C6205_BAR1_HDCR / sizeof(*pao->pci.ap_mem_base[1]);
phw->prDSPP =
pao->pci.ap_mem_base[1] +
C6205_BAR1_DSPP / sizeof(*pao->pci.ap_mem_base[1]);
pao->has_control_cache = 0;
if (hpios_locked_mem_alloc(&phw->h_locked_mem,
sizeof(struct bus_master_interface),
pao->pci.pci_dev))
phw->p_interface_buffer = NULL;
else if (hpios_locked_mem_get_virt_addr(&phw->h_locked_mem,
(void *)&phw->p_interface_buffer))
phw->p_interface_buffer = NULL;
HPI_DEBUG_LOG(DEBUG, "interface buffer address %p\n",
phw->p_interface_buffer);
if (phw->p_interface_buffer) {
memset((void *)phw->p_interface_buffer, 0,
sizeof(struct bus_master_interface));
phw->p_interface_buffer->dsp_ack = H620_HIF_UNKNOWN;
}
err = adapter_boot_load_dsp(pao, pos_error_code);
if (err) {
HPI_DEBUG_LOG(ERROR, "DSP code load failed\n");
/* no need to clean up as SubSysCreateAdapter */
/* calls DeleteAdapter on error. */
return err;
}
HPI_DEBUG_LOG(INFO, "load DSP code OK\n");
/* allow boot load even if mem alloc wont work */
if (!phw->p_interface_buffer)
return HPI_ERROR_MEMORY_ALLOC;
interface = phw->p_interface_buffer;
/* make sure the DSP has started ok */
if (!wait_dsp_ack(phw, H620_HIF_RESET, HPI6205_TIMEOUT * 10)) {
HPI_DEBUG_LOG(ERROR, "timed out waiting reset state \n");
return HPI6205_ERROR_6205_INIT_FAILED;
}
/* Note that *pao, *phw are zeroed after allocation,
* so pointers and flags are NULL by default.
* Allocate bus mastering control cache buffer and tell the DSP about it
*/
if (interface->control_cache.number_of_controls) {
u8 *p_control_cache_virtual;
err = hpios_locked_mem_alloc(&phw->h_control_cache,
interface->control_cache.size_in_bytes,
pao->pci.pci_dev);
if (!err)
err = hpios_locked_mem_get_virt_addr(&phw->
h_control_cache,
(void *)&p_control_cache_virtual);
if (!err) {
memset(p_control_cache_virtual, 0,
interface->control_cache.size_in_bytes);
phw->p_cache =
hpi_alloc_control_cache(interface->
control_cache.number_of_controls,
interface->control_cache.size_in_bytes,
p_control_cache_virtual);
if (!phw->p_cache)
err = HPI_ERROR_MEMORY_ALLOC;
}
if (!err) {
err = hpios_locked_mem_get_phys_addr(&phw->
h_control_cache, &phys_addr);
interface->control_cache.physical_address32 =
phys_addr;
}
if (!err)
pao->has_control_cache = 1;
else {
if (hpios_locked_mem_valid(&phw->h_control_cache))
hpios_locked_mem_free(&phw->h_control_cache);
pao->has_control_cache = 0;
}
}
send_dsp_command(phw, H620_HIF_IDLE);
{
struct hpi_message hm;
struct hpi_response hr;
u32 max_streams;
HPI_DEBUG_LOG(VERBOSE, "init ADAPTER_GET_INFO\n");
memset(&hm, 0, sizeof(hm));
/* wAdapterIndex == version == 0 */
hm.type = HPI_TYPE_REQUEST;
hm.size = sizeof(hm);
hm.object = HPI_OBJ_ADAPTER;
hm.function = HPI_ADAPTER_GET_INFO;
memset(&hr, 0, sizeof(hr));
hr.size = sizeof(hr);
err = message_response_sequence(pao, &hm, &hr);
if (err) {
HPI_DEBUG_LOG(ERROR, "message transport error %d\n",
err);
return err;
}
if (hr.error)
return hr.error;
pao->type = hr.u.ax.info.adapter_type;
pao->index = hr.u.ax.info.adapter_index;
max_streams =
hr.u.ax.info.num_outstreams +
hr.u.ax.info.num_instreams;
HPI_DEBUG_LOG(VERBOSE,
"got adapter info type %x index %d serial %d\n",
hr.u.ax.info.adapter_type, hr.u.ax.info.adapter_index,
hr.u.ax.info.serial_number);
}
if (phw->p_cache)
phw->p_cache->adap_idx = pao->index;
HPI_DEBUG_LOG(INFO, "bootload DSP OK\n");
return hpi_add_adapter(pao);
}
/** Free memory areas allocated by adapter
* this routine is called from AdapterDelete,
* and SubSysCreateAdapter if duplicate index
*/
static void delete_adapter_obj(struct hpi_adapter_obj *pao)
{
struct hpi_hw_obj *phw = pao->priv;
int i;
if (hpios_locked_mem_valid(&phw->h_control_cache)) {
hpios_locked_mem_free(&phw->h_control_cache);
hpi_free_control_cache(phw->p_cache);
}
if (hpios_locked_mem_valid(&phw->h_locked_mem)) {
hpios_locked_mem_free(&phw->h_locked_mem);
phw->p_interface_buffer = NULL;
}
for (i = 0; i < HPI_MAX_STREAMS; i++)
if (hpios_locked_mem_valid(&phw->instream_host_buffers[i])) {
hpios_locked_mem_free(&phw->instream_host_buffers[i]);
/*?phw->InStreamHostBuffers[i] = NULL; */
phw->instream_host_buffer_size[i] = 0;
}
for (i = 0; i < HPI_MAX_STREAMS; i++)
if (hpios_locked_mem_valid(&phw->outstream_host_buffers[i])) {
hpios_locked_mem_free(&phw->outstream_host_buffers
[i]);
phw->outstream_host_buffer_size[i] = 0;
}
kfree(phw);
}
/*****************************************************************************/
/* Adapter functions */
/*****************************************************************************/
/* OutStream Host buffer functions */
/** Allocate or attach buffer for busmastering
*/
static void outstream_host_buffer_allocate(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
u16 err = 0;
u32 command = phm->u.d.u.buffer.command;
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface = phw->p_interface_buffer;
hpi_init_response(phr, phm->object, phm->function, 0);
if (command == HPI_BUFFER_CMD_EXTERNAL
|| command == HPI_BUFFER_CMD_INTERNAL_ALLOC) {
/* ALLOC phase, allocate a buffer with power of 2 size,
get its bus address for PCI bus mastering
*/
phm->u.d.u.buffer.buffer_size =
roundup_pow_of_two(phm->u.d.u.buffer.buffer_size);
/* return old size and allocated size,
so caller can detect change */
phr->u.d.u.stream_info.data_available =
phw->outstream_host_buffer_size[phm->obj_index];
phr->u.d.u.stream_info.buffer_size =
phm->u.d.u.buffer.buffer_size;
if (phw->outstream_host_buffer_size[phm->obj_index] ==
phm->u.d.u.buffer.buffer_size) {
/* Same size, no action required */
return;
}
if (hpios_locked_mem_valid(&phw->outstream_host_buffers[phm->
obj_index]))
hpios_locked_mem_free(&phw->outstream_host_buffers
[phm->obj_index]);
err = hpios_locked_mem_alloc(&phw->outstream_host_buffers
[phm->obj_index], phm->u.d.u.buffer.buffer_size,
pao->pci.pci_dev);
if (err) {
phr->error = HPI_ERROR_INVALID_DATASIZE;
phw->outstream_host_buffer_size[phm->obj_index] = 0;
return;
}
err = hpios_locked_mem_get_phys_addr
(&phw->outstream_host_buffers[phm->obj_index],
&phm->u.d.u.buffer.pci_address);
/* get the phys addr into msg for single call alloc caller
* needs to do this for split alloc (or use the same message)
* return the phy address for split alloc in the respose too
*/
phr->u.d.u.stream_info.auxiliary_data_available =
phm->u.d.u.buffer.pci_address;
if (err) {
hpios_locked_mem_free(&phw->outstream_host_buffers
[phm->obj_index]);
phw->outstream_host_buffer_size[phm->obj_index] = 0;
phr->error = HPI_ERROR_MEMORY_ALLOC;
return;
}
}
if (command == HPI_BUFFER_CMD_EXTERNAL
|| command == HPI_BUFFER_CMD_INTERNAL_GRANTADAPTER) {
/* GRANT phase. Set up the BBM status, tell the DSP about
the buffer so it can start using BBM.
*/
struct hpi_hostbuffer_status *status;
if (phm->u.d.u.buffer.buffer_size & (phm->u.d.u.buffer.
buffer_size - 1)) {
HPI_DEBUG_LOG(ERROR,
"Buffer size must be 2^N not %d\n",
phm->u.d.u.buffer.buffer_size);
phr->error = HPI_ERROR_INVALID_DATASIZE;
return;
}
phw->outstream_host_buffer_size[phm->obj_index] =
phm->u.d.u.buffer.buffer_size;
status = &interface->outstream_host_buffer_status[phm->
obj_index];
status->samples_processed = 0;
status->stream_state = HPI_STATE_STOPPED;
status->dsp_index = 0;
status->host_index = status->dsp_index;
status->size_in_bytes = phm->u.d.u.buffer.buffer_size;
status->auxiliary_data_available = 0;
hw_message(pao, phm, phr);
if (phr->error
&& hpios_locked_mem_valid(&phw->
outstream_host_buffers[phm->obj_index])) {
hpios_locked_mem_free(&phw->outstream_host_buffers
[phm->obj_index]);
phw->outstream_host_buffer_size[phm->obj_index] = 0;
}
}
}
static void outstream_host_buffer_get_info(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface = phw->p_interface_buffer;
struct hpi_hostbuffer_status *status;
u8 *p_bbm_data;
if (hpios_locked_mem_valid(&phw->outstream_host_buffers[phm->
obj_index])) {
if (hpios_locked_mem_get_virt_addr(&phw->
outstream_host_buffers[phm->obj_index],
(void *)&p_bbm_data)) {
phr->error = HPI_ERROR_INVALID_OPERATION;
return;
}
status = &interface->outstream_host_buffer_status[phm->
obj_index];
hpi_init_response(phr, HPI_OBJ_OSTREAM,
HPI_OSTREAM_HOSTBUFFER_GET_INFO, 0);
phr->u.d.u.hostbuffer_info.p_buffer = p_bbm_data;
phr->u.d.u.hostbuffer_info.p_status = status;
} else {
hpi_init_response(phr, HPI_OBJ_OSTREAM,
HPI_OSTREAM_HOSTBUFFER_GET_INFO,
HPI_ERROR_INVALID_OPERATION);
}
}
static void outstream_host_buffer_free(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
u32 command = phm->u.d.u.buffer.command;
if (phw->outstream_host_buffer_size[phm->obj_index]) {
if (command == HPI_BUFFER_CMD_EXTERNAL
|| command == HPI_BUFFER_CMD_INTERNAL_REVOKEADAPTER) {
phw->outstream_host_buffer_size[phm->obj_index] = 0;
hw_message(pao, phm, phr);
/* Tell adapter to stop using the host buffer. */
}
if (command == HPI_BUFFER_CMD_EXTERNAL
|| command == HPI_BUFFER_CMD_INTERNAL_FREE)
hpios_locked_mem_free(&phw->outstream_host_buffers
[phm->obj_index]);
}
/* Should HPI_ERROR_INVALID_OPERATION be returned
if no host buffer is allocated? */
else
hpi_init_response(phr, HPI_OBJ_OSTREAM,
HPI_OSTREAM_HOSTBUFFER_FREE, 0);
}
static u32 outstream_get_space_available(struct hpi_hostbuffer_status *status)
{
return status->size_in_bytes - (status->host_index -
status->dsp_index);
}
static void outstream_write(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface = phw->p_interface_buffer;
struct hpi_hostbuffer_status *status;
u32 space_available;
if (!phw->outstream_host_buffer_size[phm->obj_index]) {
/* there is no BBM buffer, write via message */
hw_message(pao, phm, phr);
return;
}
hpi_init_response(phr, phm->object, phm->function, 0);
status = &interface->outstream_host_buffer_status[phm->obj_index];
space_available = outstream_get_space_available(status);
if (space_available < phm->u.d.u.data.data_size) {
phr->error = HPI_ERROR_INVALID_DATASIZE;
return;
}
/* HostBuffers is used to indicate host buffer is internally allocated.
otherwise, assumed external, data written externally */
if (phm->u.d.u.data.pb_data
&& hpios_locked_mem_valid(&phw->outstream_host_buffers[phm->
obj_index])) {
u8 *p_bbm_data;
u32 l_first_write;
u8 *p_app_data = (u8 *)phm->u.d.u.data.pb_data;
if (hpios_locked_mem_get_virt_addr(&phw->
outstream_host_buffers[phm->obj_index],
(void *)&p_bbm_data)) {
phr->error = HPI_ERROR_INVALID_OPERATION;
return;
}
/* either all data,
or enough to fit from current to end of BBM buffer */
l_first_write =
min(phm->u.d.u.data.data_size,
status->size_in_bytes -
(status->host_index & (status->size_in_bytes - 1)));
memcpy(p_bbm_data +
(status->host_index & (status->size_in_bytes - 1)),
p_app_data, l_first_write);
/* remaining data if any */
memcpy(p_bbm_data, p_app_data + l_first_write,
phm->u.d.u.data.data_size - l_first_write);
}
/*
* This version relies on the DSP code triggering an OStream buffer
* update immediately following a SET_FORMAT call. The host has
* already written data into the BBM buffer, but the DSP won't know
* about it until dwHostIndex is adjusted.
*/
if (phw->flag_outstream_just_reset[phm->obj_index]) {
/* Format can only change after reset. Must tell DSP. */
u16 function = phm->function;
phw->flag_outstream_just_reset[phm->obj_index] = 0;
phm->function = HPI_OSTREAM_SET_FORMAT;
hw_message(pao, phm, phr); /* send the format to the DSP */
phm->function = function;
if (phr->error)
return;
}
status->host_index += phm->u.d.u.data.data_size;
}
static void outstream_get_info(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface = phw->p_interface_buffer;
struct hpi_hostbuffer_status *status;
if (!phw->outstream_host_buffer_size[phm->obj_index]) {
hw_message(pao, phm, phr);
return;
}
hpi_init_response(phr, phm->object, phm->function, 0);
status = &interface->outstream_host_buffer_status[phm->obj_index];
phr->u.d.u.stream_info.state = (u16)status->stream_state;
phr->u.d.u.stream_info.samples_transferred =
status->samples_processed;
phr->u.d.u.stream_info.buffer_size = status->size_in_bytes;
phr->u.d.u.stream_info.data_available =
status->size_in_bytes - outstream_get_space_available(status);
phr->u.d.u.stream_info.auxiliary_data_available =
status->auxiliary_data_available;
}
static void outstream_start(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
hw_message(pao, phm, phr);
}
static void outstream_reset(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
phw->flag_outstream_just_reset[phm->obj_index] = 1;
hw_message(pao, phm, phr);
}
static void outstream_open(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
outstream_reset(pao, phm, phr);
}
/*****************************************************************************/
/* InStream Host buffer functions */
static void instream_host_buffer_allocate(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
u16 err = 0;
u32 command = phm->u.d.u.buffer.command;
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface = phw->p_interface_buffer;
hpi_init_response(phr, phm->object, phm->function, 0);
if (command == HPI_BUFFER_CMD_EXTERNAL
|| command == HPI_BUFFER_CMD_INTERNAL_ALLOC) {
phm->u.d.u.buffer.buffer_size =
roundup_pow_of_two(phm->u.d.u.buffer.buffer_size);
phr->u.d.u.stream_info.data_available =
phw->instream_host_buffer_size[phm->obj_index];
phr->u.d.u.stream_info.buffer_size =
phm->u.d.u.buffer.buffer_size;
if (phw->instream_host_buffer_size[phm->obj_index] ==
phm->u.d.u.buffer.buffer_size) {
/* Same size, no action required */
return;
}
if (hpios_locked_mem_valid(&phw->instream_host_buffers[phm->
obj_index]))
hpios_locked_mem_free(&phw->instream_host_buffers
[phm->obj_index]);
err = hpios_locked_mem_alloc(&phw->instream_host_buffers[phm->
obj_index], phm->u.d.u.buffer.buffer_size,
pao->pci.pci_dev);
if (err) {
phr->error = HPI_ERROR_INVALID_DATASIZE;
phw->instream_host_buffer_size[phm->obj_index] = 0;
return;
}
err = hpios_locked_mem_get_phys_addr
(&phw->instream_host_buffers[phm->obj_index],
&phm->u.d.u.buffer.pci_address);
/* get the phys addr into msg for single call alloc. Caller
needs to do this for split alloc so return the phy address */
phr->u.d.u.stream_info.auxiliary_data_available =
phm->u.d.u.buffer.pci_address;
if (err) {
hpios_locked_mem_free(&phw->instream_host_buffers
[phm->obj_index]);
phw->instream_host_buffer_size[phm->obj_index] = 0;
phr->error = HPI_ERROR_MEMORY_ALLOC;
return;
}
}
if (command == HPI_BUFFER_CMD_EXTERNAL
|| command == HPI_BUFFER_CMD_INTERNAL_GRANTADAPTER) {
struct hpi_hostbuffer_status *status;
if (phm->u.d.u.buffer.buffer_size & (phm->u.d.u.buffer.
buffer_size - 1)) {
HPI_DEBUG_LOG(ERROR,
"Buffer size must be 2^N not %d\n",
phm->u.d.u.buffer.buffer_size);
phr->error = HPI_ERROR_INVALID_DATASIZE;
return;
}
phw->instream_host_buffer_size[phm->obj_index] =
phm->u.d.u.buffer.buffer_size;
status = &interface->instream_host_buffer_status[phm->
obj_index];
status->samples_processed = 0;
status->stream_state = HPI_STATE_STOPPED;
status->dsp_index = 0;
status->host_index = status->dsp_index;
status->size_in_bytes = phm->u.d.u.buffer.buffer_size;
status->auxiliary_data_available = 0;
hw_message(pao, phm, phr);
if (phr->error
&& hpios_locked_mem_valid(&phw->
instream_host_buffers[phm->obj_index])) {
hpios_locked_mem_free(&phw->instream_host_buffers
[phm->obj_index]);
phw->instream_host_buffer_size[phm->obj_index] = 0;
}
}
}
static void instream_host_buffer_get_info(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface = phw->p_interface_buffer;
struct hpi_hostbuffer_status *status;
u8 *p_bbm_data;
if (hpios_locked_mem_valid(&phw->instream_host_buffers[phm->
obj_index])) {
if (hpios_locked_mem_get_virt_addr(&phw->
instream_host_buffers[phm->obj_index],
(void *)&p_bbm_data)) {
phr->error = HPI_ERROR_INVALID_OPERATION;
return;
}
status = &interface->instream_host_buffer_status[phm->
obj_index];
hpi_init_response(phr, HPI_OBJ_ISTREAM,
HPI_ISTREAM_HOSTBUFFER_GET_INFO, 0);
phr->u.d.u.hostbuffer_info.p_buffer = p_bbm_data;
phr->u.d.u.hostbuffer_info.p_status = status;
} else {
hpi_init_response(phr, HPI_OBJ_ISTREAM,
HPI_ISTREAM_HOSTBUFFER_GET_INFO,
HPI_ERROR_INVALID_OPERATION);
}
}
static void instream_host_buffer_free(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
u32 command = phm->u.d.u.buffer.command;
if (phw->instream_host_buffer_size[phm->obj_index]) {
if (command == HPI_BUFFER_CMD_EXTERNAL
|| command == HPI_BUFFER_CMD_INTERNAL_REVOKEADAPTER) {
phw->instream_host_buffer_size[phm->obj_index] = 0;
hw_message(pao, phm, phr);
}
if (command == HPI_BUFFER_CMD_EXTERNAL
|| command == HPI_BUFFER_CMD_INTERNAL_FREE)
hpios_locked_mem_free(&phw->instream_host_buffers
[phm->obj_index]);
} else {
/* Should HPI_ERROR_INVALID_OPERATION be returned
if no host buffer is allocated? */
hpi_init_response(phr, HPI_OBJ_ISTREAM,
HPI_ISTREAM_HOSTBUFFER_FREE, 0);
}
}
static void instream_start(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
hw_message(pao, phm, phr);
}
static u32 instream_get_bytes_available(struct hpi_hostbuffer_status *status)
{
return status->dsp_index - status->host_index;
}
static void instream_read(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface = phw->p_interface_buffer;
struct hpi_hostbuffer_status *status;
u32 data_available;
u8 *p_bbm_data;
u32 l_first_read;
u8 *p_app_data = (u8 *)phm->u.d.u.data.pb_data;
if (!phw->instream_host_buffer_size[phm->obj_index]) {
hw_message(pao, phm, phr);
return;
}
hpi_init_response(phr, phm->object, phm->function, 0);
status = &interface->instream_host_buffer_status[phm->obj_index];
data_available = instream_get_bytes_available(status);
if (data_available < phm->u.d.u.data.data_size) {
phr->error = HPI_ERROR_INVALID_DATASIZE;
return;
}
if (hpios_locked_mem_valid(&phw->instream_host_buffers[phm->
obj_index])) {
if (hpios_locked_mem_get_virt_addr(&phw->
instream_host_buffers[phm->obj_index],
(void *)&p_bbm_data)) {
phr->error = HPI_ERROR_INVALID_OPERATION;
return;
}
/* either all data,
or enough to fit from current to end of BBM buffer */
l_first_read =
min(phm->u.d.u.data.data_size,
status->size_in_bytes -
(status->host_index & (status->size_in_bytes - 1)));
memcpy(p_app_data,
p_bbm_data +
(status->host_index & (status->size_in_bytes - 1)),
l_first_read);
/* remaining data if any */
memcpy(p_app_data + l_first_read, p_bbm_data,
phm->u.d.u.data.data_size - l_first_read);
}
status->host_index += phm->u.d.u.data.data_size;
}
static void instream_get_info(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface = phw->p_interface_buffer;
struct hpi_hostbuffer_status *status;
if (!phw->instream_host_buffer_size[phm->obj_index]) {
hw_message(pao, phm, phr);
return;
}
status = &interface->instream_host_buffer_status[phm->obj_index];
hpi_init_response(phr, phm->object, phm->function, 0);
phr->u.d.u.stream_info.state = (u16)status->stream_state;
phr->u.d.u.stream_info.samples_transferred =
status->samples_processed;
phr->u.d.u.stream_info.buffer_size = status->size_in_bytes;
phr->u.d.u.stream_info.data_available =
instream_get_bytes_available(status);
phr->u.d.u.stream_info.auxiliary_data_available =
status->auxiliary_data_available;
}
/*****************************************************************************/
/* LOW-LEVEL */
#define HPI6205_MAX_FILES_TO_LOAD 2
static u16 adapter_boot_load_dsp(struct hpi_adapter_obj *pao,
u32 *pos_error_code)
{
struct hpi_hw_obj *phw = pao->priv;
struct dsp_code dsp_code;
u16 boot_code_id[HPI6205_MAX_FILES_TO_LOAD];
u32 temp;
int dsp = 0, i = 0;
u16 err = 0;
boot_code_id[0] = HPI_ADAPTER_ASI(0x6205);
boot_code_id[1] = pao->pci.pci_dev->subsystem_device;
boot_code_id[1] = HPI_ADAPTER_FAMILY_ASI(boot_code_id[1]);
/* fix up cases where bootcode id[1] != subsys id */
switch (boot_code_id[1]) {
case HPI_ADAPTER_FAMILY_ASI(0x5000):
boot_code_id[0] = boot_code_id[1];
boot_code_id[1] = 0;
break;
case HPI_ADAPTER_FAMILY_ASI(0x5300):
case HPI_ADAPTER_FAMILY_ASI(0x5400):
case HPI_ADAPTER_FAMILY_ASI(0x6300):
boot_code_id[1] = HPI_ADAPTER_FAMILY_ASI(0x6400);
break;
case HPI_ADAPTER_FAMILY_ASI(0x5500):
case HPI_ADAPTER_FAMILY_ASI(0x5600):
case HPI_ADAPTER_FAMILY_ASI(0x6500):
boot_code_id[1] = HPI_ADAPTER_FAMILY_ASI(0x6600);
break;
case HPI_ADAPTER_FAMILY_ASI(0x8800):
boot_code_id[1] = HPI_ADAPTER_FAMILY_ASI(0x8900);
break;
default:
break;
}
/* reset DSP by writing a 1 to the WARMRESET bit */
temp = C6205_HDCR_WARMRESET;
iowrite32(temp, phw->prHDCR);
hpios_delay_micro_seconds(1000);
/* check that PCI i/f was configured by EEPROM */
temp = ioread32(phw->prHSR);
if ((temp & (C6205_HSR_CFGERR | C6205_HSR_EEREAD)) !=
C6205_HSR_EEREAD)
return HPI6205_ERROR_6205_EEPROM;
temp |= 0x04;
/* disable PINTA interrupt */
iowrite32(temp, phw->prHSR);
/* check control register reports PCI boot mode */
temp = ioread32(phw->prHDCR);
if (!(temp & C6205_HDCR_PCIBOOT))
return HPI6205_ERROR_6205_REG;
/* try writing a few numbers to the DSP page register */
/* and reading them back. */
temp = 3;
iowrite32(temp, phw->prDSPP);
if ((temp | C6205_DSPP_MAP1) != ioread32(phw->prDSPP))
return HPI6205_ERROR_6205_DSPPAGE;
temp = 2;
iowrite32(temp, phw->prDSPP);
if ((temp | C6205_DSPP_MAP1) != ioread32(phw->prDSPP))
return HPI6205_ERROR_6205_DSPPAGE;
temp = 1;
iowrite32(temp, phw->prDSPP);
if ((temp | C6205_DSPP_MAP1) != ioread32(phw->prDSPP))
return HPI6205_ERROR_6205_DSPPAGE;
/* reset DSP page to the correct number */
temp = 0;
iowrite32(temp, phw->prDSPP);
if ((temp | C6205_DSPP_MAP1) != ioread32(phw->prDSPP))
return HPI6205_ERROR_6205_DSPPAGE;
phw->dsp_page = 0;
/* release 6713 from reset before 6205 is bootloaded.
This ensures that the EMIF is inactive,
and the 6713 HPI gets the correct bootmode etc
*/
if (boot_code_id[1] != 0) {
/* DSP 1 is a C6713 */
/* CLKX0 <- '1' release the C6205 bootmode pulldowns */
boot_loader_write_mem32(pao, 0, (0x018C0024L), 0x00002202);
hpios_delay_micro_seconds(100);
/* Reset the 6713 #1 - revB */
boot_loader_write_mem32(pao, 0, C6205_BAR0_TIMER1_CTL, 0);
/* dummy read every 4 words for 6205 advisory 1.4.4 */
boot_loader_read_mem32(pao, 0, 0);
hpios_delay_micro_seconds(100);
/* Release C6713 from reset - revB */
boot_loader_write_mem32(pao, 0, C6205_BAR0_TIMER1_CTL, 4);
hpios_delay_micro_seconds(100);
}
for (dsp = 0; dsp < HPI6205_MAX_FILES_TO_LOAD; dsp++) {
/* is there a DSP to load? */
if (boot_code_id[dsp] == 0)
continue;
err = boot_loader_config_emif(pao, dsp);
if (err)
return err;
err = boot_loader_test_internal_memory(pao, dsp);
if (err)
return err;
err = boot_loader_test_external_memory(pao, dsp);
if (err)
return err;
err = boot_loader_test_pld(pao, dsp);
if (err)
return err;
/* write the DSP code down into the DSPs memory */
err = hpi_dsp_code_open(boot_code_id[dsp], pao->pci.pci_dev,
&dsp_code, pos_error_code);
if (err)
return err;
while (1) {
u32 length;
u32 address;
u32 type;
u32 *pcode;
err = hpi_dsp_code_read_word(&dsp_code, &length);
if (err)
break;
if (length == 0xFFFFFFFF)
break; /* end of code */
err = hpi_dsp_code_read_word(&dsp_code, &address);
if (err)
break;
err = hpi_dsp_code_read_word(&dsp_code, &type);
if (err)
break;
err = hpi_dsp_code_read_block(length, &dsp_code,
&pcode);
if (err)
break;
for (i = 0; i < (int)length; i++) {
boot_loader_write_mem32(pao, dsp, address,
*pcode);
/* dummy read every 4 words */
/* for 6205 advisory 1.4.4 */
if (i % 4 == 0)
boot_loader_read_mem32(pao, dsp,
address);
pcode++;
address += 4;
}
}
if (err) {
hpi_dsp_code_close(&dsp_code);
return err;
}
/* verify code */
hpi_dsp_code_rewind(&dsp_code);
while (1) {
u32 length = 0;
u32 address = 0;
u32 type = 0;
u32 *pcode = NULL;
u32 data = 0;
hpi_dsp_code_read_word(&dsp_code, &length);
if (length == 0xFFFFFFFF)
break; /* end of code */
hpi_dsp_code_read_word(&dsp_code, &address);
hpi_dsp_code_read_word(&dsp_code, &type);
hpi_dsp_code_read_block(length, &dsp_code, &pcode);
for (i = 0; i < (int)length; i++) {
data = boot_loader_read_mem32(pao, dsp,
address);
if (data != *pcode) {
err = 0;
break;
}
pcode++;
address += 4;
}
if (err)
break;
}
hpi_dsp_code_close(&dsp_code);
if (err)
return err;
}
/* After bootloading all DSPs, start DSP0 running
* The DSP0 code will handle starting and synchronizing with its slaves
*/
if (phw->p_interface_buffer) {
/* we need to tell the card the physical PCI address */
u32 physicalPC_iaddress;
struct bus_master_interface *interface =
phw->p_interface_buffer;
u32 host_mailbox_address_on_dsp;
u32 physicalPC_iaddress_verify = 0;
int time_out = 10;
/* set ack so we know when DSP is ready to go */
/* (dwDspAck will be changed to HIF_RESET) */
interface->dsp_ack = H620_HIF_UNKNOWN;
wmb(); /* ensure ack is written before dsp writes back */
err = hpios_locked_mem_get_phys_addr(&phw->h_locked_mem,
&physicalPC_iaddress);
/* locate the host mailbox on the DSP. */
host_mailbox_address_on_dsp = 0x80000000;
while ((physicalPC_iaddress != physicalPC_iaddress_verify)
&& time_out--) {
boot_loader_write_mem32(pao, 0,
host_mailbox_address_on_dsp,
physicalPC_iaddress);
physicalPC_iaddress_verify =
boot_loader_read_mem32(pao, 0,
host_mailbox_address_on_dsp);
}
}
HPI_DEBUG_LOG(DEBUG, "starting DS_ps running\n");
/* enable interrupts */
temp = ioread32(phw->prHSR);
temp &= ~(u32)C6205_HSR_INTAM;
iowrite32(temp, phw->prHSR);
/* start code running... */
temp = ioread32(phw->prHDCR);
temp |= (u32)C6205_HDCR_DSPINT;
iowrite32(temp, phw->prHDCR);
/* give the DSP 10ms to start up */
hpios_delay_micro_seconds(10000);
return err;
}
/*****************************************************************************/
/* Bootloader utility functions */
static u32 boot_loader_read_mem32(struct hpi_adapter_obj *pao, int dsp_index,
u32 address)
{
struct hpi_hw_obj *phw = pao->priv;
u32 data = 0;
__iomem u32 *p_data;
if (dsp_index == 0) {
/* DSP 0 is always C6205 */
if ((address >= 0x01800000) & (address < 0x02000000)) {
/* BAR1 register access */
p_data = pao->pci.ap_mem_base[1] +
(address & 0x007fffff) /
sizeof(*pao->pci.ap_mem_base[1]);
/* HPI_DEBUG_LOG(WARNING,
"BAR1 access %08x\n", dwAddress); */
} else {
u32 dw4M_page = address >> 22L;
if (dw4M_page != phw->dsp_page) {
phw->dsp_page = dw4M_page;
/* *INDENT OFF* */
iowrite32(phw->dsp_page, phw->prDSPP);
/* *INDENT-ON* */
}
address &= 0x3fffff; /* address within 4M page */
/* BAR0 memory access */
p_data = pao->pci.ap_mem_base[0] +
address / sizeof(u32);
}
data = ioread32(p_data);
} else if (dsp_index == 1) {
/* DSP 1 is a C6713 */
u32 lsb;
boot_loader_write_mem32(pao, 0, HPIAL_ADDR, address);
boot_loader_write_mem32(pao, 0, HPIAH_ADDR, address >> 16);
lsb = boot_loader_read_mem32(pao, 0, HPIDL_ADDR);
data = boot_loader_read_mem32(pao, 0, HPIDH_ADDR);
data = (data << 16) | (lsb & 0xFFFF);
}
return data;
}
static void boot_loader_write_mem32(struct hpi_adapter_obj *pao,
int dsp_index, u32 address, u32 data)
{
struct hpi_hw_obj *phw = pao->priv;
__iomem u32 *p_data;
/* u32 dwVerifyData=0; */
if (dsp_index == 0) {
/* DSP 0 is always C6205 */
if ((address >= 0x01800000) & (address < 0x02000000)) {
/* BAR1 - DSP register access using */
/* Non-prefetchable PCI access */
p_data = pao->pci.ap_mem_base[1] +
(address & 0x007fffff) /
sizeof(*pao->pci.ap_mem_base[1]);
} else {
/* BAR0 access - all of DSP memory using */
/* pre-fetchable PCI access */
u32 dw4M_page = address >> 22L;
if (dw4M_page != phw->dsp_page) {
phw->dsp_page = dw4M_page;
/* *INDENT-OFF* */
iowrite32(phw->dsp_page, phw->prDSPP);
/* *INDENT-ON* */
}
address &= 0x3fffff; /* address within 4M page */
p_data = pao->pci.ap_mem_base[0] +
address / sizeof(u32);
}
iowrite32(data, p_data);
} else if (dsp_index == 1) {
/* DSP 1 is a C6713 */
boot_loader_write_mem32(pao, 0, HPIAL_ADDR, address);
boot_loader_write_mem32(pao, 0, HPIAH_ADDR, address >> 16);
/* dummy read every 4 words for 6205 advisory 1.4.4 */
boot_loader_read_mem32(pao, 0, 0);
boot_loader_write_mem32(pao, 0, HPIDL_ADDR, data);
boot_loader_write_mem32(pao, 0, HPIDH_ADDR, data >> 16);
/* dummy read every 4 words for 6205 advisory 1.4.4 */
boot_loader_read_mem32(pao, 0, 0);
}
}
static u16 boot_loader_config_emif(struct hpi_adapter_obj *pao, int dsp_index)
{
if (dsp_index == 0) {
u32 setting;
/* DSP 0 is always C6205 */
/* Set the EMIF */
/* memory map of C6205 */
/* 00000000-0000FFFF 16Kx32 internal program */
/* 00400000-00BFFFFF CE0 2Mx32 SDRAM running @ 100MHz */
/* EMIF config */
/*------------ */
/* Global EMIF control */
boot_loader_write_mem32(pao, dsp_index, 0x01800000, 0x3779);
#define WS_OFS 28
#define WST_OFS 22
#define WH_OFS 20
#define RS_OFS 16
#define RST_OFS 8
#define MTYPE_OFS 4
#define RH_OFS 0
/* EMIF CE0 setup - 2Mx32 Sync DRAM on ASI5000 cards only */
setting = 0x00000030;
boot_loader_write_mem32(pao, dsp_index, 0x01800008, setting);
if (setting != boot_loader_read_mem32(pao, dsp_index,
0x01800008))
return HPI6205_ERROR_DSP_EMIF1;
/* EMIF CE1 setup - 32 bit async. This is 6713 #1 HPI, */
/* which occupies D15..0. 6713 starts at 27MHz, so need */
/* plenty of wait states. See dsn8701.rtf, and 6713 errata. */
/* WST should be 71, but 63 is max possible */
setting =
(1L << WS_OFS) | (63L << WST_OFS) | (1L << WH_OFS) |
(1L << RS_OFS) | (63L << RST_OFS) | (1L << RH_OFS) |
(2L << MTYPE_OFS);
boot_loader_write_mem32(pao, dsp_index, 0x01800004, setting);
if (setting != boot_loader_read_mem32(pao, dsp_index,
0x01800004))
return HPI6205_ERROR_DSP_EMIF2;
/* EMIF CE2 setup - 32 bit async. This is 6713 #2 HPI, */
/* which occupies D15..0. 6713 starts at 27MHz, so need */
/* plenty of wait states */
setting =
(1L << WS_OFS) | (28L << WST_OFS) | (1L << WH_OFS) |
(1L << RS_OFS) | (63L << RST_OFS) | (1L << RH_OFS) |
(2L << MTYPE_OFS);
boot_loader_write_mem32(pao, dsp_index, 0x01800010, setting);
if (setting != boot_loader_read_mem32(pao, dsp_index,
0x01800010))
return HPI6205_ERROR_DSP_EMIF3;
/* EMIF CE3 setup - 32 bit async. */
/* This is the PLD on the ASI5000 cards only */
setting =
(1L << WS_OFS) | (10L << WST_OFS) | (1L << WH_OFS) |
(1L << RS_OFS) | (10L << RST_OFS) | (1L << RH_OFS) |
(2L << MTYPE_OFS);
boot_loader_write_mem32(pao, dsp_index, 0x01800014, setting);
if (setting != boot_loader_read_mem32(pao, dsp_index,
0x01800014))
return HPI6205_ERROR_DSP_EMIF4;
/* set EMIF SDRAM control for 2Mx32 SDRAM (512x32x4 bank) */
/* need to use this else DSP code crashes? */
boot_loader_write_mem32(pao, dsp_index, 0x01800018,
0x07117000);
/* EMIF SDRAM Refresh Timing */
/* EMIF SDRAM timing (orig = 0x410, emulator = 0x61a) */
boot_loader_write_mem32(pao, dsp_index, 0x0180001C,
0x00000410);
} else if (dsp_index == 1) {
/* test access to the C6713s HPI registers */
u32 write_data = 0, read_data = 0, i = 0;
/* Set up HPIC for little endian, by setiing HPIC:HWOB=1 */
write_data = 1;
boot_loader_write_mem32(pao, 0, HPICL_ADDR, write_data);
boot_loader_write_mem32(pao, 0, HPICH_ADDR, write_data);
/* C67 HPI is on lower 16bits of 32bit EMIF */
read_data =
0xFFF7 & boot_loader_read_mem32(pao, 0, HPICL_ADDR);
if (write_data != read_data) {
HPI_DEBUG_LOG(ERROR, "HPICL %x %x\n", write_data,
read_data);
return HPI6205_ERROR_C6713_HPIC;
}
/* HPIA - walking ones test */
write_data = 1;
for (i = 0; i < 32; i++) {
boot_loader_write_mem32(pao, 0, HPIAL_ADDR,
write_data);
boot_loader_write_mem32(pao, 0, HPIAH_ADDR,
(write_data >> 16));
read_data =
0xFFFF & boot_loader_read_mem32(pao, 0,
HPIAL_ADDR);
read_data =
read_data | ((0xFFFF &
boot_loader_read_mem32(pao, 0,
HPIAH_ADDR))
<< 16);
if (read_data != write_data) {
HPI_DEBUG_LOG(ERROR, "HPIA %x %x\n",
write_data, read_data);
return HPI6205_ERROR_C6713_HPIA;
}
write_data = write_data << 1;
}
/* setup C67x PLL
* ** C6713 datasheet says we cannot program PLL from HPI,
* and indeed if we try to set the PLL multiply from the HPI,
* the PLL does not seem to lock, so we enable the PLL and
* use the default multiply of x 7, which for a 27MHz clock
* gives a DSP speed of 189MHz
*/
/* bypass PLL */
boot_loader_write_mem32(pao, dsp_index, 0x01B7C100, 0x0000);
hpios_delay_micro_seconds(1000);
/* EMIF = 189/3=63MHz */
boot_loader_write_mem32(pao, dsp_index, 0x01B7C120, 0x8002);
/* peri = 189/2 */
boot_loader_write_mem32(pao, dsp_index, 0x01B7C11C, 0x8001);
/* cpu = 189/1 */
boot_loader_write_mem32(pao, dsp_index, 0x01B7C118, 0x8000);
hpios_delay_micro_seconds(1000);
/* ** SGT test to take GPO3 high when we start the PLL */
/* and low when the delay is completed */
/* FSX0 <- '1' (GPO3) */
boot_loader_write_mem32(pao, 0, (0x018C0024L), 0x00002A0A);
/* PLL not bypassed */
boot_loader_write_mem32(pao, dsp_index, 0x01B7C100, 0x0001);
hpios_delay_micro_seconds(1000);
/* FSX0 <- '0' (GPO3) */
boot_loader_write_mem32(pao, 0, (0x018C0024L), 0x00002A02);
/* 6205 EMIF CE1 resetup - 32 bit async. */
/* Now 6713 #1 is running at 189MHz can reduce waitstates */
boot_loader_write_mem32(pao, 0, 0x01800004, /* CE1 */
(1L << WS_OFS) | (8L << WST_OFS) | (1L << WH_OFS) |
(1L << RS_OFS) | (12L << RST_OFS) | (1L << RH_OFS) |
(2L << MTYPE_OFS));
hpios_delay_micro_seconds(1000);
/* check that we can read one of the PLL registers */
/* PLL should not be bypassed! */
if ((boot_loader_read_mem32(pao, dsp_index, 0x01B7C100) & 0xF)
!= 0x0001) {
return HPI6205_ERROR_C6713_PLL;
}
/* setup C67x EMIF (note this is the only use of
BAR1 via BootLoader_WriteMem32) */
boot_loader_write_mem32(pao, dsp_index, C6713_EMIF_GCTL,
0x000034A8);
/* EMIF CE0 setup - 2Mx32 Sync DRAM
31..28 Wr setup
27..22 Wr strobe
21..20 Wr hold
19..16 Rd setup
15..14 -
13..8 Rd strobe
7..4 MTYPE 0011 Sync DRAM 32bits
3 Wr hold MSB
2..0 Rd hold
*/
boot_loader_write_mem32(pao, dsp_index, C6713_EMIF_CE0,
0x00000030);
/* EMIF SDRAM Extension
0x00
31-21 0000b 0000b 000b
20 WR2RD = 2cycles-1 = 1b
19-18 WR2DEAC = 3cycle-1 = 10b
17 WR2WR = 2cycle-1 = 1b
16-15 R2WDQM = 4cycle-1 = 11b
14-12 RD2WR = 6cycles-1 = 101b
11-10 RD2DEAC = 4cycle-1 = 11b
9 RD2RD = 2cycle-1 = 1b
8-7 THZP = 3cycle-1 = 10b
6-5 TWR = 2cycle-1 = 01b (tWR = 17ns)
4 TRRD = 2cycle = 0b (tRRD = 14ns)
3-1 TRAS = 5cycle-1 = 100b (Tras=42ns)
1 CAS latency = 3cyc = 1b
(for Micron 2M32-7 operating at 100MHz)
*/
boot_loader_write_mem32(pao, dsp_index, C6713_EMIF_SDRAMEXT,
0x001BDF29);
/* EMIF SDRAM control - set up for a 2Mx32 SDRAM (512x32x4 bank)
31 - 0b -
30 SDBSZ 1b 4 bank
29..28 SDRSZ 00b 11 row address pins
27..26 SDCSZ 01b 8 column address pins
25 RFEN 1b refersh enabled
24 INIT 1b init SDRAM!
23..20 TRCD 0001b (Trcd/Tcyc)-1 = (20/10)-1 = 1
19..16 TRP 0001b (Trp/Tcyc)-1 = (20/10)-1 = 1
15..12 TRC 0110b (Trc/Tcyc)-1 = (70/10)-1 = 6
11..0 - 0000b 0000b 0000b
*/
boot_loader_write_mem32(pao, dsp_index, C6713_EMIF_SDRAMCTL,
0x47116000);
/* SDRAM refresh timing
Need 4,096 refresh cycles every 64ms = 15.625us = 1562cycles of 100MHz = 0x61A
*/
boot_loader_write_mem32(pao, dsp_index,
C6713_EMIF_SDRAMTIMING, 0x00000410);
hpios_delay_micro_seconds(1000);
} else if (dsp_index == 2) {
/* DSP 2 is a C6713 */
}
return 0;
}
static u16 boot_loader_test_memory(struct hpi_adapter_obj *pao, int dsp_index,
u32 start_address, u32 length)
{
u32 i = 0, j = 0;
u32 test_addr = 0;
u32 test_data = 0, data = 0;
length = 1000;
/* for 1st word, test each bit in the 32bit word, */
/* dwLength specifies number of 32bit words to test */
/*for(i=0; i<dwLength; i++) */
i = 0;
{
test_addr = start_address + i * 4;
test_data = 0x00000001;
for (j = 0; j < 32; j++) {
boot_loader_write_mem32(pao, dsp_index, test_addr,
test_data);
data = boot_loader_read_mem32(pao, dsp_index,
test_addr);
if (data != test_data) {
HPI_DEBUG_LOG(VERBOSE,
"Memtest error details "
"%08x %08x %08x %i\n", test_addr,
test_data, data, dsp_index);
return 1; /* error */
}
test_data = test_data << 1;
} /* for(j) */
} /* for(i) */
/* for the next 100 locations test each location, leaving it as zero */
/* write a zero to the next word in memory before we read */
/* the previous write to make sure every memory location is unique */
for (i = 0; i < 100; i++) {
test_addr = start_address + i * 4;
test_data = 0xA5A55A5A;
boot_loader_write_mem32(pao, dsp_index, test_addr, test_data);
boot_loader_write_mem32(pao, dsp_index, test_addr + 4, 0);
data = boot_loader_read_mem32(pao, dsp_index, test_addr);
if (data != test_data) {
HPI_DEBUG_LOG(VERBOSE,
"Memtest error details "
"%08x %08x %08x %i\n", test_addr, test_data,
data, dsp_index);
return 1; /* error */
}
/* leave location as zero */
boot_loader_write_mem32(pao, dsp_index, test_addr, 0x0);
}
/* zero out entire memory block */
for (i = 0; i < length; i++) {
test_addr = start_address + i * 4;
boot_loader_write_mem32(pao, dsp_index, test_addr, 0x0);
}
return 0;
}
static u16 boot_loader_test_internal_memory(struct hpi_adapter_obj *pao,
int dsp_index)
{
int err = 0;
if (dsp_index == 0) {
/* DSP 0 is a C6205 */
/* 64K prog mem */
err = boot_loader_test_memory(pao, dsp_index, 0x00000000,
0x10000);
if (!err)
/* 64K data mem */
err = boot_loader_test_memory(pao, dsp_index,
0x80000000, 0x10000);
} else if (dsp_index == 1) {
/* DSP 1 is a C6713 */
/* 192K internal mem */
err = boot_loader_test_memory(pao, dsp_index, 0x00000000,
0x30000);
if (!err)
/* 64K internal mem / L2 cache */
err = boot_loader_test_memory(pao, dsp_index,
0x00030000, 0x10000);
}
if (err)
return HPI6205_ERROR_DSP_INTMEM;
else
return 0;
}
static u16 boot_loader_test_external_memory(struct hpi_adapter_obj *pao,
int dsp_index)
{
u32 dRAM_start_address = 0;
u32 dRAM_size = 0;
if (dsp_index == 0) {
/* only test for SDRAM if an ASI5000 card */
if (pao->pci.pci_dev->subsystem_device == 0x5000) {
/* DSP 0 is always C6205 */
dRAM_start_address = 0x00400000;
dRAM_size = 0x200000;
/*dwDRAMinc=1024; */
} else
return 0;
} else if (dsp_index == 1) {
/* DSP 1 is a C6713 */
dRAM_start_address = 0x80000000;
dRAM_size = 0x200000;
/*dwDRAMinc=1024; */
}
if (boot_loader_test_memory(pao, dsp_index, dRAM_start_address,
dRAM_size))
return HPI6205_ERROR_DSP_EXTMEM;
return 0;
}
static u16 boot_loader_test_pld(struct hpi_adapter_obj *pao, int dsp_index)
{
u32 data = 0;
if (dsp_index == 0) {
/* only test for DSP0 PLD on ASI5000 card */
if (pao->pci.pci_dev->subsystem_device == 0x5000) {
/* PLD is located at CE3=0x03000000 */
data = boot_loader_read_mem32(pao, dsp_index,
0x03000008);
if ((data & 0xF) != 0x5)
return HPI6205_ERROR_DSP_PLD;
data = boot_loader_read_mem32(pao, dsp_index,
0x0300000C);
if ((data & 0xF) != 0xA)
return HPI6205_ERROR_DSP_PLD;
}
} else if (dsp_index == 1) {
/* DSP 1 is a C6713 */
if (pao->pci.pci_dev->subsystem_device == 0x8700) {
/* PLD is located at CE1=0x90000000 */
data = boot_loader_read_mem32(pao, dsp_index,
0x90000010);
if ((data & 0xFF) != 0xAA)
return HPI6205_ERROR_DSP_PLD;
/* 8713 - LED on */
boot_loader_write_mem32(pao, dsp_index, 0x90000000,
0x02);
}
}
return 0;
}
/** Transfer data to or from DSP
nOperation = H620_H620_HIF_SEND_DATA or H620_HIF_GET_DATA
*/
static short hpi6205_transfer_data(struct hpi_adapter_obj *pao, u8 *p_data,
u32 data_size, int operation)
{
struct hpi_hw_obj *phw = pao->priv;
u32 data_transferred = 0;
u16 err = 0;
u32 temp2;
struct bus_master_interface *interface = phw->p_interface_buffer;
if (!p_data)
return HPI_ERROR_INVALID_DATA_POINTER;
data_size &= ~3L; /* round data_size down to nearest 4 bytes */
/* make sure state is IDLE */
if (!wait_dsp_ack(phw, H620_HIF_IDLE, HPI6205_TIMEOUT))
return HPI_ERROR_DSP_HARDWARE;
while (data_transferred < data_size) {
u32 this_copy = data_size - data_transferred;
if (this_copy > HPI6205_SIZEOF_DATA)
this_copy = HPI6205_SIZEOF_DATA;
if (operation == H620_HIF_SEND_DATA)
memcpy((void *)&interface->u.b_data[0],
&p_data[data_transferred], this_copy);
interface->transfer_size_in_bytes = this_copy;
/* DSP must change this back to nOperation */
interface->dsp_ack = H620_HIF_IDLE;
send_dsp_command(phw, operation);
temp2 = wait_dsp_ack(phw, operation, HPI6205_TIMEOUT);
HPI_DEBUG_LOG(DEBUG, "spun %d times for data xfer of %d\n",
HPI6205_TIMEOUT - temp2, this_copy);
if (!temp2) {
/* timed out */
HPI_DEBUG_LOG(ERROR,
"Timed out waiting for " "state %d got %d\n",
operation, interface->dsp_ack);
break;
}
if (operation == H620_HIF_GET_DATA)
memcpy(&p_data[data_transferred],
(void *)&interface->u.b_data[0], this_copy);
data_transferred += this_copy;
}
if (interface->dsp_ack != operation)
HPI_DEBUG_LOG(DEBUG, "interface->dsp_ack=%d, expected %d\n",
interface->dsp_ack, operation);
/* err=HPI_ERROR_DSP_HARDWARE; */
send_dsp_command(phw, H620_HIF_IDLE);
return err;
}
/* wait for up to timeout_us microseconds for the DSP
to signal state by DMA into dwDspAck
*/
static int wait_dsp_ack(struct hpi_hw_obj *phw, int state, int timeout_us)
{
struct bus_master_interface *interface = phw->p_interface_buffer;
int t = timeout_us / 4;
rmb(); /* ensure interface->dsp_ack is up to date */
while ((interface->dsp_ack != state) && --t) {
hpios_delay_micro_seconds(4);
rmb(); /* DSP changes dsp_ack by DMA */
}
/*HPI_DEBUG_LOG(VERBOSE, "Spun %d for %d\n", timeout_us/4-t, state); */
return t * 4;
}
/* set the busmaster interface to cmd, then interrupt the DSP */
static void send_dsp_command(struct hpi_hw_obj *phw, int cmd)
{
struct bus_master_interface *interface = phw->p_interface_buffer;
u32 r;
interface->host_cmd = cmd;
wmb(); /* DSP gets state by DMA, make sure it is written to memory */
/* before we interrupt the DSP */
r = ioread32(phw->prHDCR);
r |= (u32)C6205_HDCR_DSPINT;
iowrite32(r, phw->prHDCR);
r &= ~(u32)C6205_HDCR_DSPINT;
iowrite32(r, phw->prHDCR);
}
static unsigned int message_count;
static u16 message_response_sequence(struct hpi_adapter_obj *pao,
struct hpi_message *phm, struct hpi_response *phr)
{
u32 time_out, time_out2;
struct hpi_hw_obj *phw = pao->priv;
struct bus_master_interface *interface = phw->p_interface_buffer;
u16 err = 0;
message_count++;
if (phm->size > sizeof(interface->u.message_buffer)) {
phr->error = HPI_ERROR_MESSAGE_BUFFER_TOO_SMALL;
phr->specific_error = sizeof(interface->u.message_buffer);
phr->size = sizeof(struct hpi_response_header);
HPI_DEBUG_LOG(ERROR,
"message len %d too big for buffer %zd \n", phm->size,
sizeof(interface->u.message_buffer));
return 0;
}
/* Assume buffer of type struct bus_master_interface
is allocated "noncacheable" */
if (!wait_dsp_ack(phw, H620_HIF_IDLE, HPI6205_TIMEOUT)) {
HPI_DEBUG_LOG(DEBUG, "timeout waiting for idle\n");
return HPI6205_ERROR_MSG_RESP_IDLE_TIMEOUT;
}
memcpy(&interface->u.message_buffer, phm, phm->size);
/* signal we want a response */
send_dsp_command(phw, H620_HIF_GET_RESP);
time_out2 = wait_dsp_ack(phw, H620_HIF_GET_RESP, HPI6205_TIMEOUT);
if (!time_out2) {
HPI_DEBUG_LOG(ERROR,
"(%u) Timed out waiting for " "GET_RESP state [%x]\n",
message_count, interface->dsp_ack);
} else {
HPI_DEBUG_LOG(VERBOSE,
"(%u) transition to GET_RESP after %u\n",
message_count, HPI6205_TIMEOUT - time_out2);
}
/* spin waiting on HIF interrupt flag (end of msg process) */
time_out = HPI6205_TIMEOUT;
/* read the result */
if (time_out) {
if (interface->u.response_buffer.response.size <= phr->size)
memcpy(phr, &interface->u.response_buffer,
interface->u.response_buffer.response.size);
else {
HPI_DEBUG_LOG(ERROR,
"response len %d too big for buffer %d\n",
interface->u.response_buffer.response.size,
phr->size);
memcpy(phr, &interface->u.response_buffer,
sizeof(struct hpi_response_header));
phr->error = HPI_ERROR_RESPONSE_BUFFER_TOO_SMALL;
phr->specific_error =
interface->u.response_buffer.response.size;
phr->size = sizeof(struct hpi_response_header);
}
}
/* set interface back to idle */
send_dsp_command(phw, H620_HIF_IDLE);
if (!time_out || !time_out2) {
HPI_DEBUG_LOG(DEBUG, "something timed out!\n");
return HPI6205_ERROR_MSG_RESP_TIMEOUT;
}
/* special case for adapter close - */
/* wait for the DSP to indicate it is idle */
if (phm->function == HPI_ADAPTER_CLOSE) {
if (!wait_dsp_ack(phw, H620_HIF_IDLE, HPI6205_TIMEOUT)) {
HPI_DEBUG_LOG(DEBUG,
"Timeout waiting for idle "
"(on adapter_close)\n");
return HPI6205_ERROR_MSG_RESP_IDLE_TIMEOUT;
}
}
err = hpi_validate_response(phm, phr);
return err;
}
static void hw_message(struct hpi_adapter_obj *pao, struct hpi_message *phm,
struct hpi_response *phr)
{
u16 err = 0;
hpios_dsplock_lock(pao);
err = message_response_sequence(pao, phm, phr);
/* maybe an error response */
if (err) {
/* something failed in the HPI/DSP interface */
if (err >= HPI_ERROR_BACKEND_BASE) {
phr->error = HPI_ERROR_DSP_COMMUNICATION;
phr->specific_error = err;
} else {
phr->error = err;
}
pao->dsp_crashed++;
/* just the header of the response is valid */
phr->size = sizeof(struct hpi_response_header);
goto err;
} else
pao->dsp_crashed = 0;
if (phr->error != 0) /* something failed in the DSP */
goto err;
switch (phm->function) {
case HPI_OSTREAM_WRITE:
case HPI_ISTREAM_ANC_WRITE:
err = hpi6205_transfer_data(pao, phm->u.d.u.data.pb_data,
phm->u.d.u.data.data_size, H620_HIF_SEND_DATA);
break;
case HPI_ISTREAM_READ:
case HPI_OSTREAM_ANC_READ:
err = hpi6205_transfer_data(pao, phm->u.d.u.data.pb_data,
phm->u.d.u.data.data_size, H620_HIF_GET_DATA);
break;
}
phr->error = err;
err:
hpios_dsplock_unlock(pao);
return;
}
| gpl-2.0 |
rukin5197/android_kernel_lge_m3s | sound/pci/ac97/ac97_proc.c | 13956 | 18219 | /*
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
* Universal interface for Audio Codec '97
*
* For more details look to AC '97 component specification revision 2.2
* by Intel Corporation (http://developer.intel.com).
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/mutex.h>
#include <sound/core.h>
#include <sound/ac97_codec.h>
#include <sound/asoundef.h>
#include "ac97_local.h"
#include "ac97_id.h"
/*
* proc interface
*/
static void snd_ac97_proc_read_functions(struct snd_ac97 *ac97, struct snd_info_buffer *buffer)
{
int header = 0, function;
unsigned short info, sense_info;
static const char *function_names[12] = {
"Master Out", "AUX Out", "Center/LFE Out", "SPDIF Out",
"Phone In", "Mic 1", "Mic 2", "Line In", "CD In", "Video In",
"Aux In", "Mono Out"
};
static const char *locations[8] = {
"Rear I/O Panel", "Front Panel", "Motherboard", "Dock/External",
"reserved", "reserved", "reserved", "NC/unused"
};
for (function = 0; function < 12; ++function) {
snd_ac97_write(ac97, AC97_FUNC_SELECT, function << 1);
info = snd_ac97_read(ac97, AC97_FUNC_INFO);
if (!(info & 0x0001))
continue;
if (!header) {
snd_iprintf(buffer, "\n Gain Inverted Buffer delay Location\n");
header = 1;
}
sense_info = snd_ac97_read(ac97, AC97_SENSE_INFO);
snd_iprintf(buffer, "%-17s: %3d.%d dBV %c %2d/fs %s\n",
function_names[function],
(info & 0x8000 ? -1 : 1) * ((info & 0x7000) >> 12) * 3 / 2,
((info & 0x0800) >> 11) * 5,
info & 0x0400 ? 'X' : '-',
(info & 0x03e0) >> 5,
locations[sense_info >> 13]);
}
}
static const char *snd_ac97_stereo_enhancements[] =
{
/* 0 */ "No 3D Stereo Enhancement",
/* 1 */ "Analog Devices Phat Stereo",
/* 2 */ "Creative Stereo Enhancement",
/* 3 */ "National Semi 3D Stereo Enhancement",
/* 4 */ "YAMAHA Ymersion",
/* 5 */ "BBE 3D Stereo Enhancement",
/* 6 */ "Crystal Semi 3D Stereo Enhancement",
/* 7 */ "Qsound QXpander",
/* 8 */ "Spatializer 3D Stereo Enhancement",
/* 9 */ "SRS 3D Stereo Enhancement",
/* 10 */ "Platform Tech 3D Stereo Enhancement",
/* 11 */ "AKM 3D Audio",
/* 12 */ "Aureal Stereo Enhancement",
/* 13 */ "Aztech 3D Enhancement",
/* 14 */ "Binaura 3D Audio Enhancement",
/* 15 */ "ESS Technology Stereo Enhancement",
/* 16 */ "Harman International VMAx",
/* 17 */ "Nvidea/IC Ensemble/KS Waves 3D Stereo Enhancement",
/* 18 */ "Philips Incredible Sound",
/* 19 */ "Texas Instruments 3D Stereo Enhancement",
/* 20 */ "VLSI Technology 3D Stereo Enhancement",
/* 21 */ "TriTech 3D Stereo Enhancement",
/* 22 */ "Realtek 3D Stereo Enhancement",
/* 23 */ "Samsung 3D Stereo Enhancement",
/* 24 */ "Wolfson Microelectronics 3D Enhancement",
/* 25 */ "Delta Integration 3D Enhancement",
/* 26 */ "SigmaTel 3D Enhancement",
/* 27 */ "IC Ensemble/KS Waves",
/* 28 */ "Rockwell 3D Stereo Enhancement",
/* 29 */ "Reserved 29",
/* 30 */ "Reserved 30",
/* 31 */ "Reserved 31"
};
static void snd_ac97_proc_read_main(struct snd_ac97 *ac97, struct snd_info_buffer *buffer, int subidx)
{
char name[64];
unsigned short val, tmp, ext, mext;
static const char *spdif_slots[4] = { " SPDIF=3/4", " SPDIF=7/8", " SPDIF=6/9", " SPDIF=10/11" };
static const char *spdif_rates[4] = { " Rate=44.1kHz", " Rate=res", " Rate=48kHz", " Rate=32kHz" };
static const char *spdif_rates_cs4205[4] = { " Rate=48kHz", " Rate=44.1kHz", " Rate=res", " Rate=res" };
static const char *double_rate_slots[4] = { "10/11", "7/8", "reserved", "reserved" };
snd_ac97_get_name(NULL, ac97->id, name, 0);
snd_iprintf(buffer, "%d-%d/%d: %s\n\n", ac97->addr, ac97->num, subidx, name);
if ((ac97->scaps & AC97_SCAP_AUDIO) == 0)
goto __modem;
snd_iprintf(buffer, "PCI Subsys Vendor: 0x%04x\n",
ac97->subsystem_vendor);
snd_iprintf(buffer, "PCI Subsys Device: 0x%04x\n\n",
ac97->subsystem_device);
snd_iprintf(buffer, "Flags: %x\n", ac97->flags);
if ((ac97->ext_id & AC97_EI_REV_MASK) >= AC97_EI_REV_23) {
val = snd_ac97_read(ac97, AC97_INT_PAGING);
snd_ac97_update_bits(ac97, AC97_INT_PAGING,
AC97_PAGE_MASK, AC97_PAGE_1);
tmp = snd_ac97_read(ac97, AC97_CODEC_CLASS_REV);
snd_iprintf(buffer, "Revision : 0x%02x\n", tmp & 0xff);
snd_iprintf(buffer, "Compat. Class : 0x%02x\n", (tmp >> 8) & 0x1f);
snd_iprintf(buffer, "Subsys. Vendor ID: 0x%04x\n",
snd_ac97_read(ac97, AC97_PCI_SVID));
snd_iprintf(buffer, "Subsys. ID : 0x%04x\n\n",
snd_ac97_read(ac97, AC97_PCI_SID));
snd_ac97_update_bits(ac97, AC97_INT_PAGING,
AC97_PAGE_MASK, val & AC97_PAGE_MASK);
}
// val = snd_ac97_read(ac97, AC97_RESET);
val = ac97->caps;
snd_iprintf(buffer, "Capabilities :%s%s%s%s%s%s\n",
val & AC97_BC_DEDICATED_MIC ? " -dedicated MIC PCM IN channel-" : "",
val & AC97_BC_RESERVED1 ? " -reserved1-" : "",
val & AC97_BC_BASS_TREBLE ? " -bass & treble-" : "",
val & AC97_BC_SIM_STEREO ? " -simulated stereo-" : "",
val & AC97_BC_HEADPHONE ? " -headphone out-" : "",
val & AC97_BC_LOUDNESS ? " -loudness-" : "");
tmp = ac97->caps & AC97_BC_DAC_MASK;
snd_iprintf(buffer, "DAC resolution : %s%s%s%s\n",
tmp == AC97_BC_16BIT_DAC ? "16-bit" : "",
tmp == AC97_BC_18BIT_DAC ? "18-bit" : "",
tmp == AC97_BC_20BIT_DAC ? "20-bit" : "",
tmp == AC97_BC_DAC_MASK ? "???" : "");
tmp = ac97->caps & AC97_BC_ADC_MASK;
snd_iprintf(buffer, "ADC resolution : %s%s%s%s\n",
tmp == AC97_BC_16BIT_ADC ? "16-bit" : "",
tmp == AC97_BC_18BIT_ADC ? "18-bit" : "",
tmp == AC97_BC_20BIT_ADC ? "20-bit" : "",
tmp == AC97_BC_ADC_MASK ? "???" : "");
snd_iprintf(buffer, "3D enhancement : %s\n",
snd_ac97_stereo_enhancements[(val >> 10) & 0x1f]);
snd_iprintf(buffer, "\nCurrent setup\n");
val = snd_ac97_read(ac97, AC97_MIC);
snd_iprintf(buffer, "Mic gain : %s [%s]\n", val & 0x0040 ? "+20dB" : "+0dB", ac97->regs[AC97_MIC] & 0x0040 ? "+20dB" : "+0dB");
val = snd_ac97_read(ac97, AC97_GENERAL_PURPOSE);
snd_iprintf(buffer, "POP path : %s 3D\n"
"Sim. stereo : %s\n"
"3D enhancement : %s\n"
"Loudness : %s\n"
"Mono output : %s\n"
"Mic select : %s\n"
"ADC/DAC loopback : %s\n",
val & 0x8000 ? "post" : "pre",
val & 0x4000 ? "on" : "off",
val & 0x2000 ? "on" : "off",
val & 0x1000 ? "on" : "off",
val & 0x0200 ? "Mic" : "MIX",
val & 0x0100 ? "Mic2" : "Mic1",
val & 0x0080 ? "on" : "off");
if (ac97->ext_id & AC97_EI_DRA)
snd_iprintf(buffer, "Double rate slots: %s\n",
double_rate_slots[(val >> 10) & 3]);
ext = snd_ac97_read(ac97, AC97_EXTENDED_ID);
if (ext == 0)
goto __modem;
snd_iprintf(buffer, "Extended ID : codec=%i rev=%i%s%s%s%s DSA=%i%s%s%s%s\n",
(ext & AC97_EI_ADDR_MASK) >> AC97_EI_ADDR_SHIFT,
(ext & AC97_EI_REV_MASK) >> AC97_EI_REV_SHIFT,
ext & AC97_EI_AMAP ? " AMAP" : "",
ext & AC97_EI_LDAC ? " LDAC" : "",
ext & AC97_EI_SDAC ? " SDAC" : "",
ext & AC97_EI_CDAC ? " CDAC" : "",
(ext & AC97_EI_DACS_SLOT_MASK) >> AC97_EI_DACS_SLOT_SHIFT,
ext & AC97_EI_VRM ? " VRM" : "",
ext & AC97_EI_SPDIF ? " SPDIF" : "",
ext & AC97_EI_DRA ? " DRA" : "",
ext & AC97_EI_VRA ? " VRA" : "");
val = snd_ac97_read(ac97, AC97_EXTENDED_STATUS);
snd_iprintf(buffer, "Extended status :%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
val & AC97_EA_PRL ? " PRL" : "",
val & AC97_EA_PRK ? " PRK" : "",
val & AC97_EA_PRJ ? " PRJ" : "",
val & AC97_EA_PRI ? " PRI" : "",
val & AC97_EA_SPCV ? " SPCV" : "",
val & AC97_EA_MDAC ? " MADC" : "",
val & AC97_EA_LDAC ? " LDAC" : "",
val & AC97_EA_SDAC ? " SDAC" : "",
val & AC97_EA_CDAC ? " CDAC" : "",
ext & AC97_EI_SPDIF ? spdif_slots[(val & AC97_EA_SPSA_SLOT_MASK) >> AC97_EA_SPSA_SLOT_SHIFT] : "",
val & AC97_EA_VRM ? " VRM" : "",
val & AC97_EA_SPDIF ? " SPDIF" : "",
val & AC97_EA_DRA ? " DRA" : "",
val & AC97_EA_VRA ? " VRA" : "");
if (ext & AC97_EI_VRA) { /* VRA */
val = snd_ac97_read(ac97, AC97_PCM_FRONT_DAC_RATE);
snd_iprintf(buffer, "PCM front DAC : %iHz\n", val);
if (ext & AC97_EI_SDAC) {
val = snd_ac97_read(ac97, AC97_PCM_SURR_DAC_RATE);
snd_iprintf(buffer, "PCM Surr DAC : %iHz\n", val);
}
if (ext & AC97_EI_LDAC) {
val = snd_ac97_read(ac97, AC97_PCM_LFE_DAC_RATE);
snd_iprintf(buffer, "PCM LFE DAC : %iHz\n", val);
}
val = snd_ac97_read(ac97, AC97_PCM_LR_ADC_RATE);
snd_iprintf(buffer, "PCM ADC : %iHz\n", val);
}
if (ext & AC97_EI_VRM) {
val = snd_ac97_read(ac97, AC97_PCM_MIC_ADC_RATE);
snd_iprintf(buffer, "PCM MIC ADC : %iHz\n", val);
}
if ((ext & AC97_EI_SPDIF) || (ac97->flags & AC97_CS_SPDIF) ||
(ac97->id == AC97_ID_YMF743)) {
if (ac97->flags & AC97_CS_SPDIF)
val = snd_ac97_read(ac97, AC97_CSR_SPDIF);
else if (ac97->id == AC97_ID_YMF743) {
val = snd_ac97_read(ac97, AC97_YMF7X3_DIT_CTRL);
val = 0x2000 | (val & 0xff00) >> 4 | (val & 0x38) >> 2;
} else
val = snd_ac97_read(ac97, AC97_SPDIF);
snd_iprintf(buffer, "SPDIF Control :%s%s%s%s Category=0x%x Generation=%i%s%s%s\n",
val & AC97_SC_PRO ? " PRO" : " Consumer",
val & AC97_SC_NAUDIO ? " Non-audio" : " PCM",
val & AC97_SC_COPY ? "" : " Copyright",
val & AC97_SC_PRE ? " Preemph50/15" : "",
(val & AC97_SC_CC_MASK) >> AC97_SC_CC_SHIFT,
(val & AC97_SC_L) >> 11,
(ac97->flags & AC97_CS_SPDIF) ?
spdif_rates_cs4205[(val & AC97_SC_SPSR_MASK) >> AC97_SC_SPSR_SHIFT] :
spdif_rates[(val & AC97_SC_SPSR_MASK) >> AC97_SC_SPSR_SHIFT],
(ac97->flags & AC97_CS_SPDIF) ?
(val & AC97_SC_DRS ? " Validity" : "") :
(val & AC97_SC_DRS ? " DRS" : ""),
(ac97->flags & AC97_CS_SPDIF) ?
(val & AC97_SC_V ? " Enabled" : "") :
(val & AC97_SC_V ? " Validity" : ""));
/* ALC650 specific*/
if ((ac97->id & 0xfffffff0) == 0x414c4720 &&
(snd_ac97_read(ac97, AC97_ALC650_CLOCK) & 0x01)) {
val = snd_ac97_read(ac97, AC97_ALC650_SPDIF_INPUT_STATUS2);
if (val & AC97_ALC650_CLOCK_LOCK) {
val = snd_ac97_read(ac97, AC97_ALC650_SPDIF_INPUT_STATUS1);
snd_iprintf(buffer, "SPDIF In Status :%s%s%s%s Category=0x%x Generation=%i",
val & AC97_ALC650_PRO ? " PRO" : " Consumer",
val & AC97_ALC650_NAUDIO ? " Non-audio" : " PCM",
val & AC97_ALC650_COPY ? "" : " Copyright",
val & AC97_ALC650_PRE ? " Preemph50/15" : "",
(val & AC97_ALC650_CC_MASK) >> AC97_ALC650_CC_SHIFT,
(val & AC97_ALC650_L) >> 15);
val = snd_ac97_read(ac97, AC97_ALC650_SPDIF_INPUT_STATUS2);
snd_iprintf(buffer, "%s Accuracy=%i%s%s\n",
spdif_rates[(val & AC97_ALC650_SPSR_MASK) >> AC97_ALC650_SPSR_SHIFT],
(val & AC97_ALC650_CLOCK_ACCURACY) >> AC97_ALC650_CLOCK_SHIFT,
(val & AC97_ALC650_CLOCK_LOCK ? " Locked" : " Unlocked"),
(val & AC97_ALC650_V ? " Validity?" : ""));
} else {
snd_iprintf(buffer, "SPDIF In Status : Not Locked\n");
}
}
}
if ((ac97->ext_id & AC97_EI_REV_MASK) >= AC97_EI_REV_23) {
val = snd_ac97_read(ac97, AC97_INT_PAGING);
snd_ac97_update_bits(ac97, AC97_INT_PAGING,
AC97_PAGE_MASK, AC97_PAGE_1);
snd_ac97_proc_read_functions(ac97, buffer);
snd_ac97_update_bits(ac97, AC97_INT_PAGING,
AC97_PAGE_MASK, val & AC97_PAGE_MASK);
}
__modem:
mext = snd_ac97_read(ac97, AC97_EXTENDED_MID);
if (mext == 0)
return;
snd_iprintf(buffer, "Extended modem ID: codec=%i%s%s%s%s%s\n",
(mext & AC97_MEI_ADDR_MASK) >> AC97_MEI_ADDR_SHIFT,
mext & AC97_MEI_CID2 ? " CID2" : "",
mext & AC97_MEI_CID1 ? " CID1" : "",
mext & AC97_MEI_HANDSET ? " HSET" : "",
mext & AC97_MEI_LINE2 ? " LIN2" : "",
mext & AC97_MEI_LINE1 ? " LIN1" : "");
val = snd_ac97_read(ac97, AC97_EXTENDED_MSTATUS);
snd_iprintf(buffer, "Modem status :%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
val & AC97_MEA_GPIO ? " GPIO" : "",
val & AC97_MEA_MREF ? " MREF" : "",
val & AC97_MEA_ADC1 ? " ADC1" : "",
val & AC97_MEA_DAC1 ? " DAC1" : "",
val & AC97_MEA_ADC2 ? " ADC2" : "",
val & AC97_MEA_DAC2 ? " DAC2" : "",
val & AC97_MEA_HADC ? " HADC" : "",
val & AC97_MEA_HDAC ? " HDAC" : "",
val & AC97_MEA_PRA ? " PRA(GPIO)" : "",
val & AC97_MEA_PRB ? " PRB(res)" : "",
val & AC97_MEA_PRC ? " PRC(ADC1)" : "",
val & AC97_MEA_PRD ? " PRD(DAC1)" : "",
val & AC97_MEA_PRE ? " PRE(ADC2)" : "",
val & AC97_MEA_PRF ? " PRF(DAC2)" : "",
val & AC97_MEA_PRG ? " PRG(HADC)" : "",
val & AC97_MEA_PRH ? " PRH(HDAC)" : "");
if (mext & AC97_MEI_LINE1) {
val = snd_ac97_read(ac97, AC97_LINE1_RATE);
snd_iprintf(buffer, "Line1 rate : %iHz\n", val);
}
if (mext & AC97_MEI_LINE2) {
val = snd_ac97_read(ac97, AC97_LINE2_RATE);
snd_iprintf(buffer, "Line2 rate : %iHz\n", val);
}
if (mext & AC97_MEI_HANDSET) {
val = snd_ac97_read(ac97, AC97_HANDSET_RATE);
snd_iprintf(buffer, "Headset rate : %iHz\n", val);
}
}
static void snd_ac97_proc_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer)
{
struct snd_ac97 *ac97 = entry->private_data;
mutex_lock(&ac97->page_mutex);
if ((ac97->id & 0xffffff40) == AC97_ID_AD1881) { // Analog Devices AD1881/85/86
int idx;
for (idx = 0; idx < 3; idx++)
if (ac97->spec.ad18xx.id[idx]) {
/* select single codec */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000,
ac97->spec.ad18xx.unchained[idx] | ac97->spec.ad18xx.chained[idx]);
snd_ac97_proc_read_main(ac97, buffer, idx);
snd_iprintf(buffer, "\n\n");
}
/* select all codecs */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, 0x7000);
snd_iprintf(buffer, "\nAD18XX configuration\n");
snd_iprintf(buffer, "Unchained : 0x%04x,0x%04x,0x%04x\n",
ac97->spec.ad18xx.unchained[0],
ac97->spec.ad18xx.unchained[1],
ac97->spec.ad18xx.unchained[2]);
snd_iprintf(buffer, "Chained : 0x%04x,0x%04x,0x%04x\n",
ac97->spec.ad18xx.chained[0],
ac97->spec.ad18xx.chained[1],
ac97->spec.ad18xx.chained[2]);
} else {
snd_ac97_proc_read_main(ac97, buffer, 0);
}
mutex_unlock(&ac97->page_mutex);
}
#ifdef CONFIG_SND_DEBUG
/* direct register write for debugging */
static void snd_ac97_proc_regs_write(struct snd_info_entry *entry, struct snd_info_buffer *buffer)
{
struct snd_ac97 *ac97 = entry->private_data;
char line[64];
unsigned int reg, val;
mutex_lock(&ac97->page_mutex);
while (!snd_info_get_line(buffer, line, sizeof(line))) {
if (sscanf(line, "%x %x", ®, &val) != 2)
continue;
/* register must be even */
if (reg < 0x80 && (reg & 1) == 0 && val <= 0xffff)
snd_ac97_write_cache(ac97, reg, val);
}
mutex_unlock(&ac97->page_mutex);
}
#endif
static void snd_ac97_proc_regs_read_main(struct snd_ac97 *ac97, struct snd_info_buffer *buffer, int subidx)
{
int reg, val;
for (reg = 0; reg < 0x80; reg += 2) {
val = snd_ac97_read(ac97, reg);
snd_iprintf(buffer, "%i:%02x = %04x\n", subidx, reg, val);
}
}
static void snd_ac97_proc_regs_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_ac97 *ac97 = entry->private_data;
mutex_lock(&ac97->page_mutex);
if ((ac97->id & 0xffffff40) == AC97_ID_AD1881) { // Analog Devices AD1881/85/86
int idx;
for (idx = 0; idx < 3; idx++)
if (ac97->spec.ad18xx.id[idx]) {
/* select single codec */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000,
ac97->spec.ad18xx.unchained[idx] | ac97->spec.ad18xx.chained[idx]);
snd_ac97_proc_regs_read_main(ac97, buffer, idx);
}
/* select all codecs */
snd_ac97_update_bits(ac97, AC97_AD_SERIAL_CFG, 0x7000, 0x7000);
} else {
snd_ac97_proc_regs_read_main(ac97, buffer, 0);
}
mutex_unlock(&ac97->page_mutex);
}
void snd_ac97_proc_init(struct snd_ac97 * ac97)
{
struct snd_info_entry *entry;
char name[32];
const char *prefix;
if (ac97->bus->proc == NULL)
return;
prefix = ac97_is_audio(ac97) ? "ac97" : "mc97";
sprintf(name, "%s#%d-%d", prefix, ac97->addr, ac97->num);
if ((entry = snd_info_create_card_entry(ac97->bus->card, name, ac97->bus->proc)) != NULL) {
snd_info_set_text_ops(entry, ac97, snd_ac97_proc_read);
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
ac97->proc = entry;
sprintf(name, "%s#%d-%d+regs", prefix, ac97->addr, ac97->num);
if ((entry = snd_info_create_card_entry(ac97->bus->card, name, ac97->bus->proc)) != NULL) {
snd_info_set_text_ops(entry, ac97, snd_ac97_proc_regs_read);
#ifdef CONFIG_SND_DEBUG
entry->mode |= S_IWUSR;
entry->c.text.write = snd_ac97_proc_regs_write;
#endif
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
ac97->proc_regs = entry;
}
void snd_ac97_proc_done(struct snd_ac97 * ac97)
{
snd_info_free_entry(ac97->proc_regs);
ac97->proc_regs = NULL;
snd_info_free_entry(ac97->proc);
ac97->proc = NULL;
}
void snd_ac97_bus_proc_init(struct snd_ac97_bus * bus)
{
struct snd_info_entry *entry;
char name[32];
sprintf(name, "codec97#%d", bus->num);
if ((entry = snd_info_create_card_entry(bus->card, name, bus->card->proc_root)) != NULL) {
entry->mode = S_IFDIR | S_IRUGO | S_IXUGO;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
bus->proc = entry;
}
void snd_ac97_bus_proc_done(struct snd_ac97_bus * bus)
{
snd_info_free_entry(bus->proc);
bus->proc = NULL;
}
| gpl-2.0 |
imrickysu/linux-xlnx | fs/fuse/inode.c | 133 | 31034 | /*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2008 Miklos Szeredi <miklos@szeredi.hu>
This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
*/
#include "fuse_i.h"
#include <linux/pagemap.h>
#include <linux/slab.h>
#include <linux/file.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/parser.h>
#include <linux/statfs.h>
#include <linux/random.h>
#include <linux/sched.h>
#include <linux/exportfs.h>
MODULE_AUTHOR("Miklos Szeredi <miklos@szeredi.hu>");
MODULE_DESCRIPTION("Filesystem in Userspace");
MODULE_LICENSE("GPL");
static struct kmem_cache *fuse_inode_cachep;
struct list_head fuse_conn_list;
DEFINE_MUTEX(fuse_mutex);
static int set_global_limit(const char *val, struct kernel_param *kp);
unsigned max_user_bgreq;
module_param_call(max_user_bgreq, set_global_limit, param_get_uint,
&max_user_bgreq, 0644);
__MODULE_PARM_TYPE(max_user_bgreq, "uint");
MODULE_PARM_DESC(max_user_bgreq,
"Global limit for the maximum number of backgrounded requests an "
"unprivileged user can set");
unsigned max_user_congthresh;
module_param_call(max_user_congthresh, set_global_limit, param_get_uint,
&max_user_congthresh, 0644);
__MODULE_PARM_TYPE(max_user_congthresh, "uint");
MODULE_PARM_DESC(max_user_congthresh,
"Global limit for the maximum congestion threshold an "
"unprivileged user can set");
#define FUSE_SUPER_MAGIC 0x65735546
#define FUSE_DEFAULT_BLKSIZE 512
/** Maximum number of outstanding background requests */
#define FUSE_DEFAULT_MAX_BACKGROUND 12
/** Congestion starts at 75% of maximum */
#define FUSE_DEFAULT_CONGESTION_THRESHOLD (FUSE_DEFAULT_MAX_BACKGROUND * 3 / 4)
struct fuse_mount_data {
int fd;
unsigned rootmode;
kuid_t user_id;
kgid_t group_id;
unsigned fd_present:1;
unsigned rootmode_present:1;
unsigned user_id_present:1;
unsigned group_id_present:1;
unsigned flags;
unsigned max_read;
unsigned blksize;
};
struct fuse_forget_link *fuse_alloc_forget(void)
{
return kzalloc(sizeof(struct fuse_forget_link), GFP_KERNEL);
}
static struct inode *fuse_alloc_inode(struct super_block *sb)
{
struct inode *inode;
struct fuse_inode *fi;
inode = kmem_cache_alloc(fuse_inode_cachep, GFP_KERNEL);
if (!inode)
return NULL;
fi = get_fuse_inode(inode);
fi->i_time = 0;
fi->nodeid = 0;
fi->nlookup = 0;
fi->attr_version = 0;
fi->writectr = 0;
fi->orig_ino = 0;
fi->state = 0;
INIT_LIST_HEAD(&fi->write_files);
INIT_LIST_HEAD(&fi->queued_writes);
INIT_LIST_HEAD(&fi->writepages);
init_waitqueue_head(&fi->page_waitq);
fi->forget = fuse_alloc_forget();
if (!fi->forget) {
kmem_cache_free(fuse_inode_cachep, inode);
return NULL;
}
return inode;
}
static void fuse_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(fuse_inode_cachep, inode);
}
static void fuse_destroy_inode(struct inode *inode)
{
struct fuse_inode *fi = get_fuse_inode(inode);
BUG_ON(!list_empty(&fi->write_files));
BUG_ON(!list_empty(&fi->queued_writes));
kfree(fi->forget);
call_rcu(&inode->i_rcu, fuse_i_callback);
}
static void fuse_evict_inode(struct inode *inode)
{
truncate_inode_pages_final(&inode->i_data);
clear_inode(inode);
if (inode->i_sb->s_flags & MS_ACTIVE) {
struct fuse_conn *fc = get_fuse_conn(inode);
struct fuse_inode *fi = get_fuse_inode(inode);
fuse_queue_forget(fc, fi->forget, fi->nodeid, fi->nlookup);
fi->forget = NULL;
}
}
static int fuse_remount_fs(struct super_block *sb, int *flags, char *data)
{
sync_filesystem(sb);
if (*flags & MS_MANDLOCK)
return -EINVAL;
return 0;
}
/*
* ino_t is 32-bits on 32-bit arch. We have to squash the 64-bit value down
* so that it will fit.
*/
static ino_t fuse_squash_ino(u64 ino64)
{
ino_t ino = (ino_t) ino64;
if (sizeof(ino_t) < sizeof(u64))
ino ^= ino64 >> (sizeof(u64) - sizeof(ino_t)) * 8;
return ino;
}
void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr,
u64 attr_valid)
{
struct fuse_conn *fc = get_fuse_conn(inode);
struct fuse_inode *fi = get_fuse_inode(inode);
fi->attr_version = ++fc->attr_version;
fi->i_time = attr_valid;
inode->i_ino = fuse_squash_ino(attr->ino);
inode->i_mode = (inode->i_mode & S_IFMT) | (attr->mode & 07777);
set_nlink(inode, attr->nlink);
inode->i_uid = make_kuid(&init_user_ns, attr->uid);
inode->i_gid = make_kgid(&init_user_ns, attr->gid);
inode->i_blocks = attr->blocks;
inode->i_atime.tv_sec = attr->atime;
inode->i_atime.tv_nsec = attr->atimensec;
/* mtime from server may be stale due to local buffered write */
if (!fc->writeback_cache || !S_ISREG(inode->i_mode)) {
inode->i_mtime.tv_sec = attr->mtime;
inode->i_mtime.tv_nsec = attr->mtimensec;
inode->i_ctime.tv_sec = attr->ctime;
inode->i_ctime.tv_nsec = attr->ctimensec;
}
if (attr->blksize != 0)
inode->i_blkbits = ilog2(attr->blksize);
else
inode->i_blkbits = inode->i_sb->s_blocksize_bits;
/*
* Don't set the sticky bit in i_mode, unless we want the VFS
* to check permissions. This prevents failures due to the
* check in may_delete().
*/
fi->orig_i_mode = inode->i_mode;
if (!(fc->flags & FUSE_DEFAULT_PERMISSIONS))
inode->i_mode &= ~S_ISVTX;
fi->orig_ino = attr->ino;
}
void fuse_change_attributes(struct inode *inode, struct fuse_attr *attr,
u64 attr_valid, u64 attr_version)
{
struct fuse_conn *fc = get_fuse_conn(inode);
struct fuse_inode *fi = get_fuse_inode(inode);
bool is_wb = fc->writeback_cache;
loff_t oldsize;
struct timespec old_mtime;
spin_lock(&fc->lock);
if ((attr_version != 0 && fi->attr_version > attr_version) ||
test_bit(FUSE_I_SIZE_UNSTABLE, &fi->state)) {
spin_unlock(&fc->lock);
return;
}
old_mtime = inode->i_mtime;
fuse_change_attributes_common(inode, attr, attr_valid);
oldsize = inode->i_size;
/*
* In case of writeback_cache enabled, the cached writes beyond EOF
* extend local i_size without keeping userspace server in sync. So,
* attr->size coming from server can be stale. We cannot trust it.
*/
if (!is_wb || !S_ISREG(inode->i_mode))
i_size_write(inode, attr->size);
spin_unlock(&fc->lock);
if (!is_wb && S_ISREG(inode->i_mode)) {
bool inval = false;
if (oldsize != attr->size) {
truncate_pagecache(inode, attr->size);
inval = true;
} else if (fc->auto_inval_data) {
struct timespec new_mtime = {
.tv_sec = attr->mtime,
.tv_nsec = attr->mtimensec,
};
/*
* Auto inval mode also checks and invalidates if mtime
* has changed.
*/
if (!timespec_equal(&old_mtime, &new_mtime))
inval = true;
}
if (inval)
invalidate_inode_pages2(inode->i_mapping);
}
}
static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr)
{
inode->i_mode = attr->mode & S_IFMT;
inode->i_size = attr->size;
inode->i_mtime.tv_sec = attr->mtime;
inode->i_mtime.tv_nsec = attr->mtimensec;
inode->i_ctime.tv_sec = attr->ctime;
inode->i_ctime.tv_nsec = attr->ctimensec;
if (S_ISREG(inode->i_mode)) {
fuse_init_common(inode);
fuse_init_file_inode(inode);
} else if (S_ISDIR(inode->i_mode))
fuse_init_dir(inode);
else if (S_ISLNK(inode->i_mode))
fuse_init_symlink(inode);
else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
fuse_init_common(inode);
init_special_inode(inode, inode->i_mode,
new_decode_dev(attr->rdev));
} else
BUG();
}
int fuse_inode_eq(struct inode *inode, void *_nodeidp)
{
u64 nodeid = *(u64 *) _nodeidp;
if (get_node_id(inode) == nodeid)
return 1;
else
return 0;
}
static int fuse_inode_set(struct inode *inode, void *_nodeidp)
{
u64 nodeid = *(u64 *) _nodeidp;
get_fuse_inode(inode)->nodeid = nodeid;
return 0;
}
struct inode *fuse_iget(struct super_block *sb, u64 nodeid,
int generation, struct fuse_attr *attr,
u64 attr_valid, u64 attr_version)
{
struct inode *inode;
struct fuse_inode *fi;
struct fuse_conn *fc = get_fuse_conn_super(sb);
retry:
inode = iget5_locked(sb, nodeid, fuse_inode_eq, fuse_inode_set, &nodeid);
if (!inode)
return NULL;
if ((inode->i_state & I_NEW)) {
inode->i_flags |= S_NOATIME;
if (!fc->writeback_cache || !S_ISREG(attr->mode))
inode->i_flags |= S_NOCMTIME;
inode->i_generation = generation;
fuse_init_inode(inode, attr);
unlock_new_inode(inode);
} else if ((inode->i_mode ^ attr->mode) & S_IFMT) {
/* Inode has changed type, any I/O on the old should fail */
make_bad_inode(inode);
iput(inode);
goto retry;
}
fi = get_fuse_inode(inode);
spin_lock(&fc->lock);
fi->nlookup++;
spin_unlock(&fc->lock);
fuse_change_attributes(inode, attr, attr_valid, attr_version);
return inode;
}
int fuse_reverse_inval_inode(struct super_block *sb, u64 nodeid,
loff_t offset, loff_t len)
{
struct inode *inode;
pgoff_t pg_start;
pgoff_t pg_end;
inode = ilookup5(sb, nodeid, fuse_inode_eq, &nodeid);
if (!inode)
return -ENOENT;
fuse_invalidate_attr(inode);
if (offset >= 0) {
pg_start = offset >> PAGE_CACHE_SHIFT;
if (len <= 0)
pg_end = -1;
else
pg_end = (offset + len - 1) >> PAGE_CACHE_SHIFT;
invalidate_inode_pages2_range(inode->i_mapping,
pg_start, pg_end);
}
iput(inode);
return 0;
}
static void fuse_umount_begin(struct super_block *sb)
{
fuse_abort_conn(get_fuse_conn_super(sb));
}
static void fuse_send_destroy(struct fuse_conn *fc)
{
struct fuse_req *req = fc->destroy_req;
if (req && fc->conn_init) {
fc->destroy_req = NULL;
req->in.h.opcode = FUSE_DESTROY;
req->force = 1;
req->background = 0;
fuse_request_send(fc, req);
fuse_put_request(fc, req);
}
}
static void fuse_bdi_destroy(struct fuse_conn *fc)
{
if (fc->bdi_initialized)
bdi_destroy(&fc->bdi);
}
static void fuse_put_super(struct super_block *sb)
{
struct fuse_conn *fc = get_fuse_conn_super(sb);
fuse_send_destroy(fc);
fuse_abort_conn(fc);
mutex_lock(&fuse_mutex);
list_del(&fc->entry);
fuse_ctl_remove_conn(fc);
mutex_unlock(&fuse_mutex);
fuse_bdi_destroy(fc);
fuse_conn_put(fc);
}
static void convert_fuse_statfs(struct kstatfs *stbuf, struct fuse_kstatfs *attr)
{
stbuf->f_type = FUSE_SUPER_MAGIC;
stbuf->f_bsize = attr->bsize;
stbuf->f_frsize = attr->frsize;
stbuf->f_blocks = attr->blocks;
stbuf->f_bfree = attr->bfree;
stbuf->f_bavail = attr->bavail;
stbuf->f_files = attr->files;
stbuf->f_ffree = attr->ffree;
stbuf->f_namelen = attr->namelen;
/* fsid is left zero */
}
static int fuse_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct fuse_conn *fc = get_fuse_conn_super(sb);
FUSE_ARGS(args);
struct fuse_statfs_out outarg;
int err;
if (!fuse_allow_current_process(fc)) {
buf->f_type = FUSE_SUPER_MAGIC;
return 0;
}
memset(&outarg, 0, sizeof(outarg));
args.in.numargs = 0;
args.in.h.opcode = FUSE_STATFS;
args.in.h.nodeid = get_node_id(dentry->d_inode);
args.out.numargs = 1;
args.out.args[0].size = sizeof(outarg);
args.out.args[0].value = &outarg;
err = fuse_simple_request(fc, &args);
if (!err)
convert_fuse_statfs(buf, &outarg.st);
return err;
}
enum {
OPT_FD,
OPT_ROOTMODE,
OPT_USER_ID,
OPT_GROUP_ID,
OPT_DEFAULT_PERMISSIONS,
OPT_ALLOW_OTHER,
OPT_MAX_READ,
OPT_BLKSIZE,
OPT_ERR
};
static const match_table_t tokens = {
{OPT_FD, "fd=%u"},
{OPT_ROOTMODE, "rootmode=%o"},
{OPT_USER_ID, "user_id=%u"},
{OPT_GROUP_ID, "group_id=%u"},
{OPT_DEFAULT_PERMISSIONS, "default_permissions"},
{OPT_ALLOW_OTHER, "allow_other"},
{OPT_MAX_READ, "max_read=%u"},
{OPT_BLKSIZE, "blksize=%u"},
{OPT_ERR, NULL}
};
static int fuse_match_uint(substring_t *s, unsigned int *res)
{
int err = -ENOMEM;
char *buf = match_strdup(s);
if (buf) {
err = kstrtouint(buf, 10, res);
kfree(buf);
}
return err;
}
static int parse_fuse_opt(char *opt, struct fuse_mount_data *d, int is_bdev)
{
char *p;
memset(d, 0, sizeof(struct fuse_mount_data));
d->max_read = ~0;
d->blksize = FUSE_DEFAULT_BLKSIZE;
while ((p = strsep(&opt, ",")) != NULL) {
int token;
int value;
unsigned uv;
substring_t args[MAX_OPT_ARGS];
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case OPT_FD:
if (match_int(&args[0], &value))
return 0;
d->fd = value;
d->fd_present = 1;
break;
case OPT_ROOTMODE:
if (match_octal(&args[0], &value))
return 0;
if (!fuse_valid_type(value))
return 0;
d->rootmode = value;
d->rootmode_present = 1;
break;
case OPT_USER_ID:
if (fuse_match_uint(&args[0], &uv))
return 0;
d->user_id = make_kuid(current_user_ns(), uv);
if (!uid_valid(d->user_id))
return 0;
d->user_id_present = 1;
break;
case OPT_GROUP_ID:
if (fuse_match_uint(&args[0], &uv))
return 0;
d->group_id = make_kgid(current_user_ns(), uv);
if (!gid_valid(d->group_id))
return 0;
d->group_id_present = 1;
break;
case OPT_DEFAULT_PERMISSIONS:
d->flags |= FUSE_DEFAULT_PERMISSIONS;
break;
case OPT_ALLOW_OTHER:
d->flags |= FUSE_ALLOW_OTHER;
break;
case OPT_MAX_READ:
if (match_int(&args[0], &value))
return 0;
d->max_read = value;
break;
case OPT_BLKSIZE:
if (!is_bdev || match_int(&args[0], &value))
return 0;
d->blksize = value;
break;
default:
return 0;
}
}
if (!d->fd_present || !d->rootmode_present ||
!d->user_id_present || !d->group_id_present)
return 0;
return 1;
}
static int fuse_show_options(struct seq_file *m, struct dentry *root)
{
struct super_block *sb = root->d_sb;
struct fuse_conn *fc = get_fuse_conn_super(sb);
seq_printf(m, ",user_id=%u", from_kuid_munged(&init_user_ns, fc->user_id));
seq_printf(m, ",group_id=%u", from_kgid_munged(&init_user_ns, fc->group_id));
if (fc->flags & FUSE_DEFAULT_PERMISSIONS)
seq_puts(m, ",default_permissions");
if (fc->flags & FUSE_ALLOW_OTHER)
seq_puts(m, ",allow_other");
if (fc->max_read != ~0)
seq_printf(m, ",max_read=%u", fc->max_read);
if (sb->s_bdev && sb->s_blocksize != FUSE_DEFAULT_BLKSIZE)
seq_printf(m, ",blksize=%lu", sb->s_blocksize);
return 0;
}
void fuse_conn_init(struct fuse_conn *fc)
{
memset(fc, 0, sizeof(*fc));
spin_lock_init(&fc->lock);
init_rwsem(&fc->killsb);
atomic_set(&fc->count, 1);
init_waitqueue_head(&fc->waitq);
init_waitqueue_head(&fc->blocked_waitq);
init_waitqueue_head(&fc->reserved_req_waitq);
INIT_LIST_HEAD(&fc->pending);
INIT_LIST_HEAD(&fc->processing);
INIT_LIST_HEAD(&fc->io);
INIT_LIST_HEAD(&fc->interrupts);
INIT_LIST_HEAD(&fc->bg_queue);
INIT_LIST_HEAD(&fc->entry);
fc->forget_list_tail = &fc->forget_list_head;
atomic_set(&fc->num_waiting, 0);
fc->max_background = FUSE_DEFAULT_MAX_BACKGROUND;
fc->congestion_threshold = FUSE_DEFAULT_CONGESTION_THRESHOLD;
fc->khctr = 0;
fc->polled_files = RB_ROOT;
fc->reqctr = 0;
fc->blocked = 0;
fc->initialized = 0;
fc->attr_version = 1;
get_random_bytes(&fc->scramble_key, sizeof(fc->scramble_key));
}
EXPORT_SYMBOL_GPL(fuse_conn_init);
void fuse_conn_put(struct fuse_conn *fc)
{
if (atomic_dec_and_test(&fc->count)) {
if (fc->destroy_req)
fuse_request_free(fc->destroy_req);
fc->release(fc);
}
}
EXPORT_SYMBOL_GPL(fuse_conn_put);
struct fuse_conn *fuse_conn_get(struct fuse_conn *fc)
{
atomic_inc(&fc->count);
return fc;
}
EXPORT_SYMBOL_GPL(fuse_conn_get);
static struct inode *fuse_get_root_inode(struct super_block *sb, unsigned mode)
{
struct fuse_attr attr;
memset(&attr, 0, sizeof(attr));
attr.mode = mode;
attr.ino = FUSE_ROOT_ID;
attr.nlink = 1;
return fuse_iget(sb, 1, 0, &attr, 0, 0);
}
struct fuse_inode_handle {
u64 nodeid;
u32 generation;
};
static struct dentry *fuse_get_dentry(struct super_block *sb,
struct fuse_inode_handle *handle)
{
struct fuse_conn *fc = get_fuse_conn_super(sb);
struct inode *inode;
struct dentry *entry;
int err = -ESTALE;
if (handle->nodeid == 0)
goto out_err;
inode = ilookup5(sb, handle->nodeid, fuse_inode_eq, &handle->nodeid);
if (!inode) {
struct fuse_entry_out outarg;
struct qstr name;
if (!fc->export_support)
goto out_err;
name.len = 1;
name.name = ".";
err = fuse_lookup_name(sb, handle->nodeid, &name, &outarg,
&inode);
if (err && err != -ENOENT)
goto out_err;
if (err || !inode) {
err = -ESTALE;
goto out_err;
}
err = -EIO;
if (get_node_id(inode) != handle->nodeid)
goto out_iput;
}
err = -ESTALE;
if (inode->i_generation != handle->generation)
goto out_iput;
entry = d_obtain_alias(inode);
if (!IS_ERR(entry) && get_node_id(inode) != FUSE_ROOT_ID)
fuse_invalidate_entry_cache(entry);
return entry;
out_iput:
iput(inode);
out_err:
return ERR_PTR(err);
}
static int fuse_encode_fh(struct inode *inode, u32 *fh, int *max_len,
struct inode *parent)
{
int len = parent ? 6 : 3;
u64 nodeid;
u32 generation;
if (*max_len < len) {
*max_len = len;
return FILEID_INVALID;
}
nodeid = get_fuse_inode(inode)->nodeid;
generation = inode->i_generation;
fh[0] = (u32)(nodeid >> 32);
fh[1] = (u32)(nodeid & 0xffffffff);
fh[2] = generation;
if (parent) {
nodeid = get_fuse_inode(parent)->nodeid;
generation = parent->i_generation;
fh[3] = (u32)(nodeid >> 32);
fh[4] = (u32)(nodeid & 0xffffffff);
fh[5] = generation;
}
*max_len = len;
return parent ? 0x82 : 0x81;
}
static struct dentry *fuse_fh_to_dentry(struct super_block *sb,
struct fid *fid, int fh_len, int fh_type)
{
struct fuse_inode_handle handle;
if ((fh_type != 0x81 && fh_type != 0x82) || fh_len < 3)
return NULL;
handle.nodeid = (u64) fid->raw[0] << 32;
handle.nodeid |= (u64) fid->raw[1];
handle.generation = fid->raw[2];
return fuse_get_dentry(sb, &handle);
}
static struct dentry *fuse_fh_to_parent(struct super_block *sb,
struct fid *fid, int fh_len, int fh_type)
{
struct fuse_inode_handle parent;
if (fh_type != 0x82 || fh_len < 6)
return NULL;
parent.nodeid = (u64) fid->raw[3] << 32;
parent.nodeid |= (u64) fid->raw[4];
parent.generation = fid->raw[5];
return fuse_get_dentry(sb, &parent);
}
static struct dentry *fuse_get_parent(struct dentry *child)
{
struct inode *child_inode = child->d_inode;
struct fuse_conn *fc = get_fuse_conn(child_inode);
struct inode *inode;
struct dentry *parent;
struct fuse_entry_out outarg;
struct qstr name;
int err;
if (!fc->export_support)
return ERR_PTR(-ESTALE);
name.len = 2;
name.name = "..";
err = fuse_lookup_name(child_inode->i_sb, get_node_id(child_inode),
&name, &outarg, &inode);
if (err) {
if (err == -ENOENT)
return ERR_PTR(-ESTALE);
return ERR_PTR(err);
}
parent = d_obtain_alias(inode);
if (!IS_ERR(parent) && get_node_id(inode) != FUSE_ROOT_ID)
fuse_invalidate_entry_cache(parent);
return parent;
}
static const struct export_operations fuse_export_operations = {
.fh_to_dentry = fuse_fh_to_dentry,
.fh_to_parent = fuse_fh_to_parent,
.encode_fh = fuse_encode_fh,
.get_parent = fuse_get_parent,
};
static const struct super_operations fuse_super_operations = {
.alloc_inode = fuse_alloc_inode,
.destroy_inode = fuse_destroy_inode,
.evict_inode = fuse_evict_inode,
.write_inode = fuse_write_inode,
.drop_inode = generic_delete_inode,
.remount_fs = fuse_remount_fs,
.put_super = fuse_put_super,
.umount_begin = fuse_umount_begin,
.statfs = fuse_statfs,
.show_options = fuse_show_options,
};
static void sanitize_global_limit(unsigned *limit)
{
if (*limit == 0)
*limit = ((totalram_pages << PAGE_SHIFT) >> 13) /
sizeof(struct fuse_req);
if (*limit >= 1 << 16)
*limit = (1 << 16) - 1;
}
static int set_global_limit(const char *val, struct kernel_param *kp)
{
int rv;
rv = param_set_uint(val, kp);
if (rv)
return rv;
sanitize_global_limit((unsigned *)kp->arg);
return 0;
}
static void process_init_limits(struct fuse_conn *fc, struct fuse_init_out *arg)
{
int cap_sys_admin = capable(CAP_SYS_ADMIN);
if (arg->minor < 13)
return;
sanitize_global_limit(&max_user_bgreq);
sanitize_global_limit(&max_user_congthresh);
if (arg->max_background) {
fc->max_background = arg->max_background;
if (!cap_sys_admin && fc->max_background > max_user_bgreq)
fc->max_background = max_user_bgreq;
}
if (arg->congestion_threshold) {
fc->congestion_threshold = arg->congestion_threshold;
if (!cap_sys_admin &&
fc->congestion_threshold > max_user_congthresh)
fc->congestion_threshold = max_user_congthresh;
}
}
static void process_init_reply(struct fuse_conn *fc, struct fuse_req *req)
{
struct fuse_init_out *arg = &req->misc.init_out;
if (req->out.h.error || arg->major != FUSE_KERNEL_VERSION)
fc->conn_error = 1;
else {
unsigned long ra_pages;
process_init_limits(fc, arg);
if (arg->minor >= 6) {
ra_pages = arg->max_readahead / PAGE_CACHE_SIZE;
if (arg->flags & FUSE_ASYNC_READ)
fc->async_read = 1;
if (!(arg->flags & FUSE_POSIX_LOCKS))
fc->no_lock = 1;
if (arg->minor >= 17) {
if (!(arg->flags & FUSE_FLOCK_LOCKS))
fc->no_flock = 1;
} else {
if (!(arg->flags & FUSE_POSIX_LOCKS))
fc->no_flock = 1;
}
if (arg->flags & FUSE_ATOMIC_O_TRUNC)
fc->atomic_o_trunc = 1;
if (arg->minor >= 9) {
/* LOOKUP has dependency on proto version */
if (arg->flags & FUSE_EXPORT_SUPPORT)
fc->export_support = 1;
}
if (arg->flags & FUSE_BIG_WRITES)
fc->big_writes = 1;
if (arg->flags & FUSE_DONT_MASK)
fc->dont_mask = 1;
if (arg->flags & FUSE_AUTO_INVAL_DATA)
fc->auto_inval_data = 1;
if (arg->flags & FUSE_DO_READDIRPLUS) {
fc->do_readdirplus = 1;
if (arg->flags & FUSE_READDIRPLUS_AUTO)
fc->readdirplus_auto = 1;
}
if (arg->flags & FUSE_ASYNC_DIO)
fc->async_dio = 1;
if (arg->flags & FUSE_WRITEBACK_CACHE)
fc->writeback_cache = 1;
if (arg->time_gran && arg->time_gran <= 1000000000)
fc->sb->s_time_gran = arg->time_gran;
} else {
ra_pages = fc->max_read / PAGE_CACHE_SIZE;
fc->no_lock = 1;
fc->no_flock = 1;
}
fc->bdi.ra_pages = min(fc->bdi.ra_pages, ra_pages);
fc->minor = arg->minor;
fc->max_write = arg->minor < 5 ? 4096 : arg->max_write;
fc->max_write = max_t(unsigned, 4096, fc->max_write);
fc->conn_init = 1;
}
fuse_set_initialized(fc);
wake_up_all(&fc->blocked_waitq);
}
static void fuse_send_init(struct fuse_conn *fc, struct fuse_req *req)
{
struct fuse_init_in *arg = &req->misc.init_in;
arg->major = FUSE_KERNEL_VERSION;
arg->minor = FUSE_KERNEL_MINOR_VERSION;
arg->max_readahead = fc->bdi.ra_pages * PAGE_CACHE_SIZE;
arg->flags |= FUSE_ASYNC_READ | FUSE_POSIX_LOCKS | FUSE_ATOMIC_O_TRUNC |
FUSE_EXPORT_SUPPORT | FUSE_BIG_WRITES | FUSE_DONT_MASK |
FUSE_SPLICE_WRITE | FUSE_SPLICE_MOVE | FUSE_SPLICE_READ |
FUSE_FLOCK_LOCKS | FUSE_IOCTL_DIR | FUSE_AUTO_INVAL_DATA |
FUSE_DO_READDIRPLUS | FUSE_READDIRPLUS_AUTO | FUSE_ASYNC_DIO |
FUSE_WRITEBACK_CACHE | FUSE_NO_OPEN_SUPPORT;
req->in.h.opcode = FUSE_INIT;
req->in.numargs = 1;
req->in.args[0].size = sizeof(*arg);
req->in.args[0].value = arg;
req->out.numargs = 1;
/* Variable length argument used for backward compatibility
with interface version < 7.5. Rest of init_out is zeroed
by do_get_request(), so a short reply is not a problem */
req->out.argvar = 1;
req->out.args[0].size = sizeof(struct fuse_init_out);
req->out.args[0].value = &req->misc.init_out;
req->end = process_init_reply;
fuse_request_send_background(fc, req);
}
static void fuse_free_conn(struct fuse_conn *fc)
{
kfree_rcu(fc, rcu);
}
static int fuse_bdi_init(struct fuse_conn *fc, struct super_block *sb)
{
int err;
fc->bdi.name = "fuse";
fc->bdi.ra_pages = (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
/* fuse does it's own writeback accounting */
fc->bdi.capabilities = BDI_CAP_NO_ACCT_WB | BDI_CAP_STRICTLIMIT;
err = bdi_init(&fc->bdi);
if (err)
return err;
fc->bdi_initialized = 1;
if (sb->s_bdev) {
err = bdi_register(&fc->bdi, NULL, "%u:%u-fuseblk",
MAJOR(fc->dev), MINOR(fc->dev));
} else {
err = bdi_register_dev(&fc->bdi, fc->dev);
}
if (err)
return err;
/*
* For a single fuse filesystem use max 1% of dirty +
* writeback threshold.
*
* This gives about 1M of write buffer for memory maps on a
* machine with 1G and 10% dirty_ratio, which should be more
* than enough.
*
* Privileged users can raise it by writing to
*
* /sys/class/bdi/<bdi>/max_ratio
*/
bdi_set_max_ratio(&fc->bdi, 1);
return 0;
}
static int fuse_fill_super(struct super_block *sb, void *data, int silent)
{
struct fuse_conn *fc;
struct inode *root;
struct fuse_mount_data d;
struct file *file;
struct dentry *root_dentry;
struct fuse_req *init_req;
int err;
int is_bdev = sb->s_bdev != NULL;
err = -EINVAL;
if (sb->s_flags & MS_MANDLOCK)
goto err;
sb->s_flags &= ~(MS_NOSEC | MS_I_VERSION);
if (!parse_fuse_opt(data, &d, is_bdev))
goto err;
if (is_bdev) {
#ifdef CONFIG_BLOCK
err = -EINVAL;
if (!sb_set_blocksize(sb, d.blksize))
goto err;
#endif
} else {
sb->s_blocksize = PAGE_CACHE_SIZE;
sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
}
sb->s_magic = FUSE_SUPER_MAGIC;
sb->s_op = &fuse_super_operations;
sb->s_maxbytes = MAX_LFS_FILESIZE;
sb->s_time_gran = 1;
sb->s_export_op = &fuse_export_operations;
file = fget(d.fd);
err = -EINVAL;
if (!file)
goto err;
if ((file->f_op != &fuse_dev_operations) ||
(file->f_cred->user_ns != &init_user_ns))
goto err_fput;
fc = kmalloc(sizeof(*fc), GFP_KERNEL);
err = -ENOMEM;
if (!fc)
goto err_fput;
fuse_conn_init(fc);
fc->dev = sb->s_dev;
fc->sb = sb;
err = fuse_bdi_init(fc, sb);
if (err)
goto err_put_conn;
sb->s_bdi = &fc->bdi;
/* Handle umasking inside the fuse code */
if (sb->s_flags & MS_POSIXACL)
fc->dont_mask = 1;
sb->s_flags |= MS_POSIXACL;
fc->release = fuse_free_conn;
fc->flags = d.flags;
fc->user_id = d.user_id;
fc->group_id = d.group_id;
fc->max_read = max_t(unsigned, 4096, d.max_read);
/* Used by get_root_inode() */
sb->s_fs_info = fc;
err = -ENOMEM;
root = fuse_get_root_inode(sb, d.rootmode);
root_dentry = d_make_root(root);
if (!root_dentry)
goto err_put_conn;
/* only now - we want root dentry with NULL ->d_op */
sb->s_d_op = &fuse_dentry_operations;
init_req = fuse_request_alloc(0);
if (!init_req)
goto err_put_root;
init_req->background = 1;
if (is_bdev) {
fc->destroy_req = fuse_request_alloc(0);
if (!fc->destroy_req)
goto err_free_init_req;
}
mutex_lock(&fuse_mutex);
err = -EINVAL;
if (file->private_data)
goto err_unlock;
err = fuse_ctl_add_conn(fc);
if (err)
goto err_unlock;
list_add_tail(&fc->entry, &fuse_conn_list);
sb->s_root = root_dentry;
fc->connected = 1;
file->private_data = fuse_conn_get(fc);
mutex_unlock(&fuse_mutex);
/*
* atomic_dec_and_test() in fput() provides the necessary
* memory barrier for file->private_data to be visible on all
* CPUs after this
*/
fput(file);
fuse_send_init(fc, init_req);
return 0;
err_unlock:
mutex_unlock(&fuse_mutex);
err_free_init_req:
fuse_request_free(init_req);
err_put_root:
dput(root_dentry);
err_put_conn:
fuse_bdi_destroy(fc);
fuse_conn_put(fc);
err_fput:
fput(file);
err:
return err;
}
static struct dentry *fuse_mount(struct file_system_type *fs_type,
int flags, const char *dev_name,
void *raw_data)
{
return mount_nodev(fs_type, flags, raw_data, fuse_fill_super);
}
static void fuse_kill_sb_anon(struct super_block *sb)
{
struct fuse_conn *fc = get_fuse_conn_super(sb);
if (fc) {
down_write(&fc->killsb);
fc->sb = NULL;
up_write(&fc->killsb);
}
kill_anon_super(sb);
}
static struct file_system_type fuse_fs_type = {
.owner = THIS_MODULE,
.name = "fuse",
.fs_flags = FS_HAS_SUBTYPE,
.mount = fuse_mount,
.kill_sb = fuse_kill_sb_anon,
};
MODULE_ALIAS_FS("fuse");
#ifdef CONFIG_BLOCK
static struct dentry *fuse_mount_blk(struct file_system_type *fs_type,
int flags, const char *dev_name,
void *raw_data)
{
return mount_bdev(fs_type, flags, dev_name, raw_data, fuse_fill_super);
}
static void fuse_kill_sb_blk(struct super_block *sb)
{
struct fuse_conn *fc = get_fuse_conn_super(sb);
if (fc) {
down_write(&fc->killsb);
fc->sb = NULL;
up_write(&fc->killsb);
}
kill_block_super(sb);
}
static struct file_system_type fuseblk_fs_type = {
.owner = THIS_MODULE,
.name = "fuseblk",
.mount = fuse_mount_blk,
.kill_sb = fuse_kill_sb_blk,
.fs_flags = FS_REQUIRES_DEV | FS_HAS_SUBTYPE,
};
MODULE_ALIAS_FS("fuseblk");
static inline int register_fuseblk(void)
{
return register_filesystem(&fuseblk_fs_type);
}
static inline void unregister_fuseblk(void)
{
unregister_filesystem(&fuseblk_fs_type);
}
#else
static inline int register_fuseblk(void)
{
return 0;
}
static inline void unregister_fuseblk(void)
{
}
#endif
static void fuse_inode_init_once(void *foo)
{
struct inode *inode = foo;
inode_init_once(inode);
}
static int __init fuse_fs_init(void)
{
int err;
fuse_inode_cachep = kmem_cache_create("fuse_inode",
sizeof(struct fuse_inode),
0, SLAB_HWCACHE_ALIGN,
fuse_inode_init_once);
err = -ENOMEM;
if (!fuse_inode_cachep)
goto out;
err = register_fuseblk();
if (err)
goto out2;
err = register_filesystem(&fuse_fs_type);
if (err)
goto out3;
return 0;
out3:
unregister_fuseblk();
out2:
kmem_cache_destroy(fuse_inode_cachep);
out:
return err;
}
static void fuse_fs_cleanup(void)
{
unregister_filesystem(&fuse_fs_type);
unregister_fuseblk();
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(fuse_inode_cachep);
}
static struct kobject *fuse_kobj;
static struct kobject *connections_kobj;
static int fuse_sysfs_init(void)
{
int err;
fuse_kobj = kobject_create_and_add("fuse", fs_kobj);
if (!fuse_kobj) {
err = -ENOMEM;
goto out_err;
}
connections_kobj = kobject_create_and_add("connections", fuse_kobj);
if (!connections_kobj) {
err = -ENOMEM;
goto out_fuse_unregister;
}
return 0;
out_fuse_unregister:
kobject_put(fuse_kobj);
out_err:
return err;
}
static void fuse_sysfs_cleanup(void)
{
kobject_put(connections_kobj);
kobject_put(fuse_kobj);
}
static int __init fuse_init(void)
{
int res;
printk(KERN_INFO "fuse init (API version %i.%i)\n",
FUSE_KERNEL_VERSION, FUSE_KERNEL_MINOR_VERSION);
INIT_LIST_HEAD(&fuse_conn_list);
res = fuse_fs_init();
if (res)
goto err;
res = fuse_dev_init();
if (res)
goto err_fs_cleanup;
res = fuse_sysfs_init();
if (res)
goto err_dev_cleanup;
res = fuse_ctl_init();
if (res)
goto err_sysfs_cleanup;
sanitize_global_limit(&max_user_bgreq);
sanitize_global_limit(&max_user_congthresh);
return 0;
err_sysfs_cleanup:
fuse_sysfs_cleanup();
err_dev_cleanup:
fuse_dev_cleanup();
err_fs_cleanup:
fuse_fs_cleanup();
err:
return res;
}
static void __exit fuse_exit(void)
{
printk(KERN_DEBUG "fuse exit\n");
fuse_ctl_cleanup();
fuse_sysfs_cleanup();
fuse_fs_cleanup();
fuse_dev_cleanup();
}
module_init(fuse_init);
module_exit(fuse_exit);
| gpl-2.0 |
xcstacy/mako-deprecated | drivers/media/video/vcap_vc.c | 1157 | 12098 | /* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <mach/camera.h>
#include <linux/io.h>
#include <linux/regulator/consumer.h>
#include <mach/clk.h>
#include <linux/clk.h>
#include <media/v4l2-event.h>
#include <media/vcap_v4l2.h>
#include <media/vcap_fmt.h>
#include "vcap_vc.h"
static unsigned debug;
#define dprintk(level, fmt, arg...) \
do { \
if (debug >= level) \
printk(KERN_DEBUG "VC: " fmt, ## arg); \
} while (0)
void config_buffer(struct vcap_client_data *c_data,
struct vcap_buffer *buf,
void __iomem *y_addr,
void __iomem *c_addr)
{
if (c_data->vc_format.color_space == HAL_VCAP_RGB) {
writel_relaxed(buf->paddr, y_addr);
} else {
int size = ((c_data->vc_format.hactive_end -
c_data->vc_format.hactive_start) *
(c_data->vc_format.vactive_end -
c_data->vc_format.vactive_start));
writel_relaxed(buf->paddr, y_addr);
writel_relaxed(buf->paddr + size, c_addr);
}
}
static void mov_buf_to_vp(struct work_struct *work)
{
struct vp_work_t *vp_work = container_of(work, struct vp_work_t, work);
struct v4l2_buffer p;
struct vb2_buffer *vb_vc;
struct vcap_buffer *buf_vc;
struct vb2_buffer *vb_vp;
struct vcap_buffer *buf_vp;
int rc;
p.memory = V4L2_MEMORY_USERPTR;
while (1) {
p.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (!vp_work->cd->streaming)
return;
rc = vcvp_dqbuf(&vp_work->cd->vc_vidq, &p);
if (rc < 0)
return;
vb_vc = vp_work->cd->vc_vidq.bufs[p.index];
if (NULL == vb_vc) {
dprintk(1, "%s: buffer is NULL\n", __func__);
vcvp_qbuf(&vp_work->cd->vc_vidq, &p);
return;
}
buf_vc = container_of(vb_vc, struct vcap_buffer, vb);
vb_vp = vp_work->cd->vp_in_vidq.bufs[p.index];
if (NULL == vb_vp) {
dprintk(1, "%s: buffer is NULL\n", __func__);
vcvp_qbuf(&vp_work->cd->vc_vidq, &p);
return;
}
buf_vp = container_of(vb_vp, struct vcap_buffer, vb);
buf_vp->ion_handle = buf_vc->ion_handle;
buf_vp->paddr = buf_vc->paddr;
buf_vc->ion_handle = NULL;
buf_vc->paddr = 0;
p.type = V4L2_BUF_TYPE_INTERLACED_IN_DECODER;
/* This call should not fail */
rc = vcvp_qbuf(&vp_work->cd->vp_in_vidq, &p);
if (rc < 0) {
pr_err("%s: qbuf to vp_in failed\n", __func__);
buf_vc->ion_handle = buf_vp->ion_handle;
buf_vc->paddr = buf_vp->paddr;
buf_vp->ion_handle = NULL;
buf_vp->paddr = 0;
p.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
vcvp_qbuf(&vp_work->cd->vc_vidq, &p);
}
}
}
irqreturn_t vc_handler(struct vcap_dev *dev)
{
uint32_t irq, timestamp;
enum rdy_buf vc_buf_status, buf_ind;
struct vcap_buffer *buf;
struct vb2_buffer *vb = NULL;
struct vcap_client_data *c_data;
struct v4l2_event v4l2_evt;
irq = readl_relaxed(VCAP_VC_INT_STATUS);
dprintk(1, "%s: irq=0x%08x\n", __func__, irq);
v4l2_evt.id = 0;
if (irq & 0x8000200) {
v4l2_evt.type = V4L2_EVENT_PRIVATE_START +
VCAP_VC_PIX_ERR_EVENT;
v4l2_event_queue(dev->vfd, &v4l2_evt);
}
if (irq & 0x40000200) {
v4l2_evt.type = V4L2_EVENT_PRIVATE_START +
VCAP_VC_LINE_ERR_EVENT;
v4l2_event_queue(dev->vfd, &v4l2_evt);
}
if (irq & 0x20000200) {
v4l2_evt.type = V4L2_EVENT_PRIVATE_START +
VCAP_VC_VSYNC_ERR_EVENT;
v4l2_event_queue(dev->vfd, &v4l2_evt);
}
if (irq & 0x00000800) {
v4l2_evt.type = V4L2_EVENT_PRIVATE_START +
VCAP_VC_NPL_OFLOW_ERR_EVENT;
v4l2_event_queue(dev->vfd, &v4l2_evt);
}
if (irq & 0x00000400) {
v4l2_evt.type = V4L2_EVENT_PRIVATE_START +
VCAP_VC_LBUF_OFLOW_ERR_EVENT;
v4l2_event_queue(dev->vfd, &v4l2_evt);
}
vc_buf_status = irq & VC_BUFFER_WRITTEN;
dprintk(1, "Done buf status = %d\n", vc_buf_status);
if (vc_buf_status == VC_NO_BUF) {
writel_relaxed(irq, VCAP_VC_INT_CLEAR);
pr_err("VC IRQ shows some error\n");
return IRQ_HANDLED;
}
if (dev->vc_client == NULL) {
writel_relaxed(irq, VCAP_VC_INT_CLEAR);
pr_err("VC: There is no active vc client\n");
return IRQ_HANDLED;
}
c_data = dev->vc_client;
spin_lock(&dev->vc_client->cap_slock);
if (list_empty(&dev->vc_client->vid_vc_action.active)) {
/* Just leave we have no new queued buffers */
spin_unlock(&dev->vc_client->cap_slock);
writel_relaxed(irq, VCAP_VC_INT_CLEAR);
v4l2_evt.type = V4L2_EVENT_PRIVATE_START +
VCAP_VC_BUF_OVERWRITE_EVENT;
v4l2_event_queue(dev->vfd, &v4l2_evt);
dprintk(1, "We have no more avilable buffers\n");
return IRQ_HANDLED;
}
spin_unlock(&dev->vc_client->cap_slock);
timestamp = readl_relaxed(VCAP_VC_TIMESTAMP);
buf_ind = dev->vc_client->vid_vc_action.buf_ind;
if (vc_buf_status == VC_BUF1N2) {
/* There are 2 buffer ready */
writel_relaxed(irq, VCAP_VC_INT_CLEAR);
return IRQ_HANDLED;
} else if (buf_ind != vc_buf_status) {
/* buffer is out of sync */
writel_relaxed(irq, VCAP_VC_INT_CLEAR);
return IRQ_HANDLED;
}
if (buf_ind == VC_BUF1) {
dprintk(1, "Got BUF1\n");
vb = &dev->vc_client->vid_vc_action.buf1->vb;
spin_lock(&dev->vc_client->cap_slock);
if (list_empty(&dev->vc_client->vid_vc_action.active)) {
spin_unlock(&dev->vc_client->cap_slock);
v4l2_evt.type = V4L2_EVENT_PRIVATE_START +
VCAP_VC_BUF_OVERWRITE_EVENT;
v4l2_event_queue(dev->vfd, &v4l2_evt);
writel_relaxed(irq, VCAP_VC_INT_CLEAR);
return IRQ_HANDLED;
}
buf = list_entry(dev->vc_client->vid_vc_action.active.next,
struct vcap_buffer, list);
list_del(&buf->list);
spin_unlock(&dev->vc_client->cap_slock);
/* Config vc with this new buffer */
config_buffer(c_data, buf, VCAP_VC_Y_ADDR_1,
VCAP_VC_C_ADDR_1);
vb->v4l2_buf.timestamp.tv_usec = timestamp;
vb2_buffer_done(vb, VB2_BUF_STATE_DONE);
dev->vc_client->vid_vc_action.buf1 = buf;
dev->vc_client->vid_vc_action.buf_ind = VC_BUF2;
irq = VC_BUF1;
} else {
dprintk(1, "Got BUF2\n");
spin_lock(&dev->vc_client->cap_slock);
vb = &dev->vc_client->vid_vc_action.buf2->vb;
if (list_empty(&dev->vc_client->vid_vc_action.active)) {
spin_unlock(&dev->vc_client->cap_slock);
writel_relaxed(irq, VCAP_VC_INT_CLEAR);
v4l2_evt.type = V4L2_EVENT_PRIVATE_START +
VCAP_VC_BUF_OVERWRITE_EVENT;
v4l2_event_queue(dev->vfd, &v4l2_evt);
return IRQ_HANDLED;
}
buf = list_entry(dev->vc_client->vid_vc_action.active.next,
struct vcap_buffer, list);
list_del(&buf->list);
spin_unlock(&dev->vc_client->cap_slock);
/* Config vc with this new buffer */
config_buffer(c_data, buf, VCAP_VC_Y_ADDR_2,
VCAP_VC_C_ADDR_2);
vb->v4l2_buf.timestamp.tv_usec = timestamp;
vb2_buffer_done(vb, VB2_BUF_STATE_DONE);
dev->vc_client->vid_vc_action.buf2 = buf;
dev->vc_client->vid_vc_action.buf_ind = VC_BUF1;
irq = VC_BUF2;
}
if (c_data->op_mode == VC_AND_VP_VCAP_OP)
queue_work(dev->vcap_wq, &dev->vc_to_vp_work.work);
writel_relaxed(irq, VCAP_VC_INT_CLEAR);
return IRQ_HANDLED;
}
int vc_start_capture(struct vcap_client_data *c_data)
{
return 0;
}
int vc_hw_kick_off(struct vcap_client_data *c_data)
{
struct vcap_action *vid_vc_action = &c_data->vid_vc_action;
struct vcap_dev *dev;
unsigned long flags = 0;
int rc, counter = 0;
struct vcap_buffer *buf;
dev = c_data->dev;
vid_vc_action->buf_ind = VC_BUF1;
dprintk(2, "Start Kickoff\n");
if (dev->vc_client == NULL) {
pr_err("No active vc client\n");
return -ENODEV;
}
spin_lock_irqsave(&dev->vc_client->cap_slock, flags);
if (list_empty(&dev->vc_client->vid_vc_action.active)) {
spin_unlock_irqrestore(&dev->vc_client->cap_slock, flags);
pr_err("%s: VC We have no more avilable buffers\n",
__func__);
return -EINVAL;
}
list_for_each_entry(buf, &vid_vc_action->active, list)
counter++;
if (counter < 2) {
/* not enough buffers have been queued */
spin_unlock_irqrestore(&dev->vc_client->cap_slock, flags);
return -EINVAL;
}
vid_vc_action->buf1 = list_entry(vid_vc_action->active.next,
struct vcap_buffer, list);
list_del(&vid_vc_action->buf1->list);
vid_vc_action->buf2 = list_entry(vid_vc_action->active.next,
struct vcap_buffer, list);
list_del(&vid_vc_action->buf2->list);
spin_unlock_irqrestore(&dev->vc_client->cap_slock, flags);
config_buffer(c_data, vid_vc_action->buf1, VCAP_VC_Y_ADDR_1,
VCAP_VC_C_ADDR_1);
config_buffer(c_data, vid_vc_action->buf2, VCAP_VC_Y_ADDR_2,
VCAP_VC_C_ADDR_2);
rc = readl_relaxed(VCAP_VC_CTRL);
writel_iowmb(rc | 0x1, VCAP_VC_CTRL);
writel_relaxed(0x6, VCAP_VC_INT_MASK);
enable_irq(dev->vcirq->start);
return 0;
}
void vc_stop_capture(struct vcap_client_data *c_data)
{
struct vcap_dev *dev = c_data->dev;
int rc;
rc = readl_relaxed(VCAP_VC_CTRL);
writel_iowmb(rc & ~(0x1), VCAP_VC_CTRL);
if (atomic_read(&dev->vc_enabled) == 1)
disable_irq(dev->vcirq->start);
flush_workqueue(dev->vcap_wq);
}
int config_vc_format(struct vcap_client_data *c_data)
{
struct vcap_dev *dev;
unsigned int rc;
int timeout;
struct v4l2_format_vc_ext *vc_format = &c_data->vc_format;
dev = c_data->dev;
/* restart VC */
writel_relaxed(0x00000001, VCAP_SW_RESET_REQ);
timeout = 10000;
while (1) {
rc = (readl_relaxed(VCAP_SW_RESET_STATUS) & 0x1);
if (!rc)
break;
timeout--;
if (timeout == 0) {
pr_err("VC is not resetting properly\n");
return -EINVAL;
}
}
writel_relaxed(0x00000000, VCAP_SW_RESET_REQ);
writel_iowmb(0x00000102, VCAP_VC_NPL_CTRL);
rc = readl_relaxed(VCAP_VC_NPL_CTRL);
rc = readl_relaxed(VCAP_VC_NPL_CTRL);
writel_iowmb(0x00000002, VCAP_VC_NPL_CTRL);
dprintk(2, "%s: Starting VC configuration\n", __func__);
writel_iowmb(0x00000002, VCAP_VC_NPL_CTRL);
writel_iowmb(0x00000004 | vc_format->color_space << 1 |
vc_format->mode << 3 |
vc_format->mode << 10, VCAP_VC_CTRL);
writel_relaxed(vc_format->h_polar << 4 |
vc_format->v_polar << 0, VCAP_VC_POLARITY);
writel_relaxed(vc_format->h_polar << 4 |
vc_format->v_polar << 0, VCAP_VC_POLARITY);
writel_relaxed(((vc_format->htotal << 16) | vc_format->vtotal),
VCAP_VC_V_H_TOTAL);
writel_relaxed(((vc_format->hactive_end << 16) |
vc_format->hactive_start), VCAP_VC_H_ACTIVE);
writel_relaxed(((vc_format->vactive_end << 16) |
vc_format->vactive_start), VCAP_VC_V_ACTIVE);
writel_relaxed(((vc_format->f2_vactive_end << 16) |
vc_format->f2_vactive_start), VCAP_VC_V_ACTIVE_F2);
writel_relaxed(((vc_format->vsync_end << 16) | vc_format->vsync_start),
VCAP_VC_VSYNC_VPOS);
writel_relaxed(((vc_format->f2_vsync_v_end << 16) |
vc_format->f2_vsync_v_start), VCAP_VC_VSYNC_F2_VPOS);
writel_relaxed(((vc_format->hsync_end << 16) |
vc_format->hsync_start), VCAP_VC_HSYNC_HPOS);
writel_relaxed(((vc_format->f2_vsync_h_end << 16) |
vc_format->f2_vsync_h_start), VCAP_VC_VSYNC_F2_HPOS);
writel_iowmb(0x000033FF, VCAP_VC_BUF_CTRL);
rc = vc_format->hactive_end - vc_format->hactive_start;
if (vc_format->color_space)
rc *= 3;
writel_relaxed(rc, VCAP_VC_Y_STRIDE);
writel_relaxed(rc, VCAP_VC_C_STRIDE);
writel_relaxed(0x00010033 , VCAP_OFFSET(0x0898));
writel_relaxed(0x00010fff , VCAP_OFFSET(0x089c));
writel_relaxed(0x0a418820, VCAP_VC_IN_CTRL1);
writel_relaxed(0x16a4a0e6, VCAP_VC_IN_CTRL2);
writel_relaxed(0x2307b9ac, VCAP_VC_IN_CTRL3);
writel_relaxed(0x2f6ad272, VCAP_VC_IN_CTRL4);
writel_relaxed(0x00006b38, VCAP_VC_IN_CTRL5);
writel_iowmb(0x00000001 , VCAP_OFFSET(0x0d00));
dprintk(2, "%s: Done VC configuration\n", __func__);
return 0;
}
int detect_vc(struct vcap_dev *dev)
{
int result;
result = readl_relaxed(VCAP_HARDWARE_VERSION_REG);
dprintk(1, "Hardware version: %08x\n", result);
if (result != VCAP_HARDWARE_VERSION)
return -ENODEV;
INIT_WORK(&dev->vc_to_vp_work.work, mov_buf_to_vp);
return 0;
}
int deinit_vc(void)
{
return 0;
}
| gpl-2.0 |
jooojub/SPC | drivers/net/wireless/ath/wil6210/ioctl.c | 1157 | 4455 | /*
* Copyright (c) 2014 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <linux/uaccess.h>
#include "wil6210.h"
#include <uapi/linux/wil6210_uapi.h>
#define wil_hex_dump_ioctl(prefix_str, buf, len) \
print_hex_dump_debug("DBG[IOC ]" prefix_str, \
DUMP_PREFIX_OFFSET, 16, 1, buf, len, true)
#define wil_dbg_ioctl(wil, fmt, arg...) wil_dbg(wil, "DBG[IOC ]" fmt, ##arg)
static void __iomem *wil_ioc_addr(struct wil6210_priv *wil, uint32_t addr,
uint32_t size, enum wil_memio_op op)
{
void __iomem *a;
u32 off;
switch (op & wil_mmio_addr_mask) {
case wil_mmio_addr_linker:
a = wmi_buffer(wil, cpu_to_le32(addr));
break;
case wil_mmio_addr_ahb:
a = wmi_addr(wil, addr);
break;
case wil_mmio_addr_bar:
a = wmi_addr(wil, addr + WIL6210_FW_HOST_OFF);
break;
default:
wil_err(wil, "Unsupported address mode, op = 0x%08x\n", op);
return NULL;
}
off = a - wil->csr;
if (size >= WIL6210_MEM_SIZE - off) {
wil_err(wil, "Requested block does not fit into memory: "
"off = 0x%08x size = 0x%08x\n", off, size);
return NULL;
}
return a;
}
static int wil_ioc_memio_dword(struct wil6210_priv *wil, void __user *data)
{
struct wil_memio io;
void __iomem *a;
bool need_copy = false;
if (copy_from_user(&io, data, sizeof(io)))
return -EFAULT;
wil_dbg_ioctl(wil, "IO: addr = 0x%08x val = 0x%08x op = 0x%08x\n",
io.addr, io.val, io.op);
a = wil_ioc_addr(wil, io.addr, sizeof(u32), io.op);
if (!a) {
wil_err(wil, "invalid address 0x%08x, op = 0x%08x\n", io.addr,
io.op);
return -EINVAL;
}
/* operation */
switch (io.op & wil_mmio_op_mask) {
case wil_mmio_read:
io.val = ioread32(a);
need_copy = true;
break;
case wil_mmio_write:
iowrite32(io.val, a);
wmb(); /* make sure write propagated to HW */
break;
default:
wil_err(wil, "Unsupported operation, op = 0x%08x\n", io.op);
return -EINVAL;
}
if (need_copy) {
wil_dbg_ioctl(wil, "IO done: addr = 0x%08x"
" val = 0x%08x op = 0x%08x\n",
io.addr, io.val, io.op);
if (copy_to_user(data, &io, sizeof(io)))
return -EFAULT;
}
return 0;
}
static int wil_ioc_memio_block(struct wil6210_priv *wil, void __user *data)
{
struct wil_memio_block io;
void *block;
void __iomem *a;
int rc = 0;
if (copy_from_user(&io, data, sizeof(io)))
return -EFAULT;
wil_dbg_ioctl(wil, "IO: addr = 0x%08x size = 0x%08x op = 0x%08x\n",
io.addr, io.size, io.op);
/* size */
if (io.size % 4) {
wil_err(wil, "size is not multiple of 4: 0x%08x\n", io.size);
return -EINVAL;
}
a = wil_ioc_addr(wil, io.addr, io.size, io.op);
if (!a) {
wil_err(wil, "invalid address 0x%08x, op = 0x%08x\n", io.addr,
io.op);
return -EINVAL;
}
block = kmalloc(io.size, GFP_USER);
if (!block)
return -ENOMEM;
/* operation */
switch (io.op & wil_mmio_op_mask) {
case wil_mmio_read:
wil_memcpy_fromio_32(block, a, io.size);
wil_hex_dump_ioctl("Read ", block, io.size);
if (copy_to_user(io.block, block, io.size)) {
rc = -EFAULT;
goto out_free;
}
break;
case wil_mmio_write:
if (copy_from_user(block, io.block, io.size)) {
rc = -EFAULT;
goto out_free;
}
wil_memcpy_toio_32(a, block, io.size);
wmb(); /* make sure write propagated to HW */
wil_hex_dump_ioctl("Write ", block, io.size);
break;
default:
wil_err(wil, "Unsupported operation, op = 0x%08x\n", io.op);
rc = -EINVAL;
break;
}
out_free:
kfree(block);
return rc;
}
int wil_ioctl(struct wil6210_priv *wil, void __user *data, int cmd)
{
switch (cmd) {
case WIL_IOCTL_MEMIO:
return wil_ioc_memio_dword(wil, data);
case WIL_IOCTL_MEMIO_BLOCK:
return wil_ioc_memio_block(wil, data);
default:
wil_dbg_ioctl(wil, "Unsupported IOCTL 0x%04x\n", cmd);
return -ENOIOCTLCMD;
}
}
| gpl-2.0 |
Jarbu12/Mini-NovaXM4.3 | fs/exofs/ore.c | 2949 | 29704 | /*
* Copyright (C) 2005, 2006
* Avishay Traeger (avishay@gmail.com)
* Copyright (C) 2008, 2009
* Boaz Harrosh <bharrosh@panasas.com>
*
* This file is part of exofs.
*
* exofs 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. Since it is based on ext2, and the only
* valid version of GPL for the Linux kernel is version 2, the only valid
* version of GPL for exofs is version 2.
*
* exofs 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 exofs; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <asm/div64.h>
#include <linux/lcm.h>
#include "ore_raid.h"
MODULE_AUTHOR("Boaz Harrosh <bharrosh@panasas.com>");
MODULE_DESCRIPTION("Objects Raid Engine ore.ko");
MODULE_LICENSE("GPL");
/* ore_verify_layout does a couple of things:
* 1. Given a minimum number of needed parameters fixes up the rest of the
* members to be operatonals for the ore. The needed parameters are those
* that are defined by the pnfs-objects layout STD.
* 2. Check to see if the current ore code actually supports these parameters
* for example stripe_unit must be a multple of the system PAGE_SIZE,
* and etc...
* 3. Cache some havily used calculations that will be needed by users.
*/
enum { BIO_MAX_PAGES_KMALLOC =
(PAGE_SIZE - sizeof(struct bio)) / sizeof(struct bio_vec),};
int ore_verify_layout(unsigned total_comps, struct ore_layout *layout)
{
u64 stripe_length;
switch (layout->raid_algorithm) {
case PNFS_OSD_RAID_0:
layout->parity = 0;
break;
case PNFS_OSD_RAID_5:
layout->parity = 1;
break;
case PNFS_OSD_RAID_PQ:
case PNFS_OSD_RAID_4:
default:
ORE_ERR("Only RAID_0/5 for now\n");
return -EINVAL;
}
if (0 != (layout->stripe_unit & ~PAGE_MASK)) {
ORE_ERR("Stripe Unit(0x%llx)"
" must be Multples of PAGE_SIZE(0x%lx)\n",
_LLU(layout->stripe_unit), PAGE_SIZE);
return -EINVAL;
}
if (layout->group_width) {
if (!layout->group_depth) {
ORE_ERR("group_depth == 0 && group_width != 0\n");
return -EINVAL;
}
if (total_comps < (layout->group_width * layout->mirrors_p1)) {
ORE_ERR("Data Map wrong, "
"numdevs=%d < group_width=%d * mirrors=%d\n",
total_comps, layout->group_width,
layout->mirrors_p1);
return -EINVAL;
}
layout->group_count = total_comps / layout->mirrors_p1 /
layout->group_width;
} else {
if (layout->group_depth) {
printk(KERN_NOTICE "Warning: group_depth ignored "
"group_width == 0 && group_depth == %lld\n",
_LLU(layout->group_depth));
}
layout->group_width = total_comps / layout->mirrors_p1;
layout->group_depth = -1;
layout->group_count = 1;
}
stripe_length = (u64)layout->group_width * layout->stripe_unit;
if (stripe_length >= (1ULL << 32)) {
ORE_ERR("Stripe_length(0x%llx) >= 32bit is not supported\n",
_LLU(stripe_length));
return -EINVAL;
}
layout->max_io_length =
(BIO_MAX_PAGES_KMALLOC * PAGE_SIZE - layout->stripe_unit) *
layout->group_width;
if (layout->parity) {
unsigned stripe_length =
(layout->group_width - layout->parity) *
layout->stripe_unit;
layout->max_io_length /= stripe_length;
layout->max_io_length *= stripe_length;
}
return 0;
}
EXPORT_SYMBOL(ore_verify_layout);
static u8 *_ios_cred(struct ore_io_state *ios, unsigned index)
{
return ios->oc->comps[index & ios->oc->single_comp].cred;
}
static struct osd_obj_id *_ios_obj(struct ore_io_state *ios, unsigned index)
{
return &ios->oc->comps[index & ios->oc->single_comp].obj;
}
static struct osd_dev *_ios_od(struct ore_io_state *ios, unsigned index)
{
ORE_DBGMSG2("oc->first_dev=%d oc->numdevs=%d i=%d oc->ods=%p\n",
ios->oc->first_dev, ios->oc->numdevs, index,
ios->oc->ods);
return ore_comp_dev(ios->oc, index);
}
int _ore_get_io_state(struct ore_layout *layout,
struct ore_components *oc, unsigned numdevs,
unsigned sgs_per_dev, unsigned num_par_pages,
struct ore_io_state **pios)
{
struct ore_io_state *ios;
struct page **pages;
struct osd_sg_entry *sgilist;
struct __alloc_all_io_state {
struct ore_io_state ios;
struct ore_per_dev_state per_dev[numdevs];
union {
struct osd_sg_entry sglist[sgs_per_dev * numdevs];
struct page *pages[num_par_pages];
};
} *_aios;
if (likely(sizeof(*_aios) <= PAGE_SIZE)) {
_aios = kzalloc(sizeof(*_aios), GFP_KERNEL);
if (unlikely(!_aios)) {
ORE_DBGMSG("Failed kzalloc bytes=%zd\n",
sizeof(*_aios));
*pios = NULL;
return -ENOMEM;
}
pages = num_par_pages ? _aios->pages : NULL;
sgilist = sgs_per_dev ? _aios->sglist : NULL;
ios = &_aios->ios;
} else {
struct __alloc_small_io_state {
struct ore_io_state ios;
struct ore_per_dev_state per_dev[numdevs];
} *_aio_small;
union __extra_part {
struct osd_sg_entry sglist[sgs_per_dev * numdevs];
struct page *pages[num_par_pages];
} *extra_part;
_aio_small = kzalloc(sizeof(*_aio_small), GFP_KERNEL);
if (unlikely(!_aio_small)) {
ORE_DBGMSG("Failed alloc first part bytes=%zd\n",
sizeof(*_aio_small));
*pios = NULL;
return -ENOMEM;
}
extra_part = kzalloc(sizeof(*extra_part), GFP_KERNEL);
if (unlikely(!extra_part)) {
ORE_DBGMSG("Failed alloc second part bytes=%zd\n",
sizeof(*extra_part));
kfree(_aio_small);
*pios = NULL;
return -ENOMEM;
}
pages = num_par_pages ? extra_part->pages : NULL;
sgilist = sgs_per_dev ? extra_part->sglist : NULL;
/* In this case the per_dev[0].sgilist holds the pointer to
* be freed
*/
ios = &_aio_small->ios;
ios->extra_part_alloc = true;
}
if (pages) {
ios->parity_pages = pages;
ios->max_par_pages = num_par_pages;
}
if (sgilist) {
unsigned d;
for (d = 0; d < numdevs; ++d) {
ios->per_dev[d].sglist = sgilist;
sgilist += sgs_per_dev;
}
ios->sgs_per_dev = sgs_per_dev;
}
ios->layout = layout;
ios->oc = oc;
*pios = ios;
return 0;
}
/* Allocate an io_state for only a single group of devices
*
* If a user needs to call ore_read/write() this version must be used becase it
* allocates extra stuff for striping and raid.
* The ore might decide to only IO less then @length bytes do to alignmets
* and constrains as follows:
* - The IO cannot cross group boundary.
* - In raid5/6 The end of the IO must align at end of a stripe eg.
* (@offset + @length) % strip_size == 0. Or the complete range is within a
* single stripe.
* - Memory condition only permitted a shorter IO. (A user can use @length=~0
* And check the returned ios->length for max_io_size.)
*
* The caller must check returned ios->length (and/or ios->nr_pages) and
* re-issue these pages that fall outside of ios->length
*/
int ore_get_rw_state(struct ore_layout *layout, struct ore_components *oc,
bool is_reading, u64 offset, u64 length,
struct ore_io_state **pios)
{
struct ore_io_state *ios;
unsigned numdevs = layout->group_width * layout->mirrors_p1;
unsigned sgs_per_dev = 0, max_par_pages = 0;
int ret;
if (layout->parity && length) {
unsigned data_devs = layout->group_width - layout->parity;
unsigned stripe_size = layout->stripe_unit * data_devs;
unsigned pages_in_unit = layout->stripe_unit / PAGE_SIZE;
u32 remainder;
u64 num_stripes;
u64 num_raid_units;
num_stripes = div_u64_rem(length, stripe_size, &remainder);
if (remainder)
++num_stripes;
num_raid_units = num_stripes * layout->parity;
if (is_reading) {
/* For reads add per_dev sglist array */
/* TODO: Raid 6 we need twice more. Actually:
* num_stripes / LCMdP(W,P);
* if (W%P != 0) num_stripes *= parity;
*/
/* first/last seg is split */
num_raid_units += layout->group_width;
sgs_per_dev = div_u64(num_raid_units, data_devs) + 2;
} else {
/* For Writes add parity pages array. */
max_par_pages = num_raid_units * pages_in_unit *
sizeof(struct page *);
}
}
ret = _ore_get_io_state(layout, oc, numdevs, sgs_per_dev, max_par_pages,
pios);
if (unlikely(ret))
return ret;
ios = *pios;
ios->reading = is_reading;
ios->offset = offset;
if (length) {
ore_calc_stripe_info(layout, offset, length, &ios->si);
ios->length = ios->si.length;
ios->nr_pages = (ios->length + PAGE_SIZE - 1) / PAGE_SIZE;
if (layout->parity)
_ore_post_alloc_raid_stuff(ios);
}
return 0;
}
EXPORT_SYMBOL(ore_get_rw_state);
/* Allocate an io_state for all the devices in the comps array
*
* This version of io_state allocation is used mostly by create/remove
* and trunc where we currently need all the devices. The only wastful
* bit is the read/write_attributes with no IO. Those sites should
* be converted to use ore_get_rw_state() with length=0
*/
int ore_get_io_state(struct ore_layout *layout, struct ore_components *oc,
struct ore_io_state **pios)
{
return _ore_get_io_state(layout, oc, oc->numdevs, 0, 0, pios);
}
EXPORT_SYMBOL(ore_get_io_state);
void ore_put_io_state(struct ore_io_state *ios)
{
if (ios) {
unsigned i;
for (i = 0; i < ios->numdevs; i++) {
struct ore_per_dev_state *per_dev = &ios->per_dev[i];
if (per_dev->or)
osd_end_request(per_dev->or);
if (per_dev->bio)
bio_put(per_dev->bio);
}
_ore_free_raid_stuff(ios);
kfree(ios);
}
}
EXPORT_SYMBOL(ore_put_io_state);
static void _sync_done(struct ore_io_state *ios, void *p)
{
struct completion *waiting = p;
complete(waiting);
}
static void _last_io(struct kref *kref)
{
struct ore_io_state *ios = container_of(
kref, struct ore_io_state, kref);
ios->done(ios, ios->private);
}
static void _done_io(struct osd_request *or, void *p)
{
struct ore_io_state *ios = p;
kref_put(&ios->kref, _last_io);
}
int ore_io_execute(struct ore_io_state *ios)
{
DECLARE_COMPLETION_ONSTACK(wait);
bool sync = (ios->done == NULL);
int i, ret;
if (sync) {
ios->done = _sync_done;
ios->private = &wait;
}
for (i = 0; i < ios->numdevs; i++) {
struct osd_request *or = ios->per_dev[i].or;
if (unlikely(!or))
continue;
ret = osd_finalize_request(or, 0, _ios_cred(ios, i), NULL);
if (unlikely(ret)) {
ORE_DBGMSG("Failed to osd_finalize_request() => %d\n",
ret);
return ret;
}
}
kref_init(&ios->kref);
for (i = 0; i < ios->numdevs; i++) {
struct osd_request *or = ios->per_dev[i].or;
if (unlikely(!or))
continue;
kref_get(&ios->kref);
osd_execute_request_async(or, _done_io, ios);
}
kref_put(&ios->kref, _last_io);
ret = 0;
if (sync) {
wait_for_completion(&wait);
ret = ore_check_io(ios, NULL);
}
return ret;
}
static void _clear_bio(struct bio *bio)
{
struct bio_vec *bv;
unsigned i;
__bio_for_each_segment(bv, bio, i, 0) {
unsigned this_count = bv->bv_len;
if (likely(PAGE_SIZE == this_count))
clear_highpage(bv->bv_page);
else
zero_user(bv->bv_page, bv->bv_offset, this_count);
}
}
int ore_check_io(struct ore_io_state *ios, ore_on_dev_error on_dev_error)
{
enum osd_err_priority acumulated_osd_err = 0;
int acumulated_lin_err = 0;
int i;
for (i = 0; i < ios->numdevs; i++) {
struct osd_sense_info osi;
struct ore_per_dev_state *per_dev = &ios->per_dev[i];
struct osd_request *or = per_dev->or;
int ret;
if (unlikely(!or))
continue;
ret = osd_req_decode_sense(or, &osi);
if (likely(!ret))
continue;
if (OSD_ERR_PRI_CLEAR_PAGES == osi.osd_err_pri) {
/* start read offset passed endof file */
_clear_bio(per_dev->bio);
ORE_DBGMSG("start read offset passed end of file "
"offset=0x%llx, length=0x%llx\n",
_LLU(per_dev->offset),
_LLU(per_dev->length));
continue; /* we recovered */
}
if (on_dev_error) {
u64 residual = ios->reading ?
or->in.residual : or->out.residual;
u64 offset = (ios->offset + ios->length) - residual;
unsigned dev = per_dev->dev - ios->oc->first_dev;
struct ore_dev *od = ios->oc->ods[dev];
on_dev_error(ios, od, dev, osi.osd_err_pri,
offset, residual);
}
if (osi.osd_err_pri >= acumulated_osd_err) {
acumulated_osd_err = osi.osd_err_pri;
acumulated_lin_err = ret;
}
}
return acumulated_lin_err;
}
EXPORT_SYMBOL(ore_check_io);
/*
* L - logical offset into the file
*
* D - number of Data devices
* D = group_width - parity
*
* U - The number of bytes in a stripe within a group
* U = stripe_unit * D
*
* T - The number of bytes striped within a group of component objects
* (before advancing to the next group)
* T = U * group_depth
*
* S - The number of bytes striped across all component objects
* before the pattern repeats
* S = T * group_count
*
* M - The "major" (i.e., across all components) cycle number
* M = L / S
*
* G - Counts the groups from the beginning of the major cycle
* G = (L - (M * S)) / T [or (L % S) / T]
*
* H - The byte offset within the group
* H = (L - (M * S)) % T [or (L % S) % T]
*
* N - The "minor" (i.e., across the group) stripe number
* N = H / U
*
* C - The component index coresponding to L
*
* C = (H - (N * U)) / stripe_unit + G * D
* [or (L % U) / stripe_unit + G * D]
*
* O - The component offset coresponding to L
* O = L % stripe_unit + N * stripe_unit + M * group_depth * stripe_unit
*
* LCMdP – Parity cycle: Lowest Common Multiple of group_width, parity
* divide by parity
* LCMdP = lcm(group_width, parity) / parity
*
* R - The parity Rotation stripe
* (Note parity cycle always starts at a group's boundary)
* R = N % LCMdP
*
* I = the first parity device index
* I = (group_width + group_width - R*parity - parity) % group_width
*
* Craid - The component index Rotated
* Craid = (group_width + C - R*parity) % group_width
* (We add the group_width to avoid negative numbers modulo math)
*/
void ore_calc_stripe_info(struct ore_layout *layout, u64 file_offset,
u64 length, struct ore_striping_info *si)
{
u32 stripe_unit = layout->stripe_unit;
u32 group_width = layout->group_width;
u64 group_depth = layout->group_depth;
u32 parity = layout->parity;
u32 D = group_width - parity;
u32 U = D * stripe_unit;
u64 T = U * group_depth;
u64 S = T * layout->group_count;
u64 M = div64_u64(file_offset, S);
/*
G = (L - (M * S)) / T
H = (L - (M * S)) % T
*/
u64 LmodS = file_offset - M * S;
u32 G = div64_u64(LmodS, T);
u64 H = LmodS - G * T;
u32 N = div_u64(H, U);
/* "H - (N * U)" is just "H % U" so it's bound to u32 */
u32 C = (u32)(H - (N * U)) / stripe_unit + G * group_width;
div_u64_rem(file_offset, stripe_unit, &si->unit_off);
si->obj_offset = si->unit_off + (N * stripe_unit) +
(M * group_depth * stripe_unit);
if (parity) {
u32 LCMdP = lcm(group_width, parity) / parity;
/* R = N % LCMdP; */
u32 RxP = (N % LCMdP) * parity;
u32 first_dev = C - C % group_width;
si->par_dev = (group_width + group_width - parity - RxP) %
group_width + first_dev;
si->dev = (group_width + C - RxP) % group_width + first_dev;
si->bytes_in_stripe = U;
si->first_stripe_start = M * S + G * T + N * U;
} else {
/* Make the math correct see _prepare_one_group */
si->par_dev = group_width;
si->dev = C;
}
si->dev *= layout->mirrors_p1;
si->par_dev *= layout->mirrors_p1;
si->offset = file_offset;
si->length = T - H;
if (si->length > length)
si->length = length;
si->M = M;
}
EXPORT_SYMBOL(ore_calc_stripe_info);
int _ore_add_stripe_unit(struct ore_io_state *ios, unsigned *cur_pg,
unsigned pgbase, struct page **pages,
struct ore_per_dev_state *per_dev, int cur_len)
{
unsigned pg = *cur_pg;
struct request_queue *q =
osd_request_queue(_ios_od(ios, per_dev->dev));
unsigned len = cur_len;
int ret;
if (per_dev->bio == NULL) {
unsigned pages_in_stripe = ios->layout->group_width *
(ios->layout->stripe_unit / PAGE_SIZE);
unsigned nr_pages = ios->nr_pages * ios->layout->group_width /
(ios->layout->group_width -
ios->layout->parity);
unsigned bio_size = (nr_pages + pages_in_stripe) /
ios->layout->group_width;
per_dev->bio = bio_kmalloc(GFP_KERNEL, bio_size);
if (unlikely(!per_dev->bio)) {
ORE_DBGMSG("Failed to allocate BIO size=%u\n",
bio_size);
ret = -ENOMEM;
goto out;
}
}
while (cur_len > 0) {
unsigned pglen = min_t(unsigned, PAGE_SIZE - pgbase, cur_len);
unsigned added_len;
cur_len -= pglen;
added_len = bio_add_pc_page(q, per_dev->bio, pages[pg],
pglen, pgbase);
if (unlikely(pglen != added_len)) {
ORE_DBGMSG("Failed bio_add_pc_page bi_vcnt=%u\n",
per_dev->bio->bi_vcnt);
ret = -ENOMEM;
goto out;
}
_add_stripe_page(ios->sp2d, &ios->si, pages[pg]);
pgbase = 0;
++pg;
}
BUG_ON(cur_len);
per_dev->length += len;
*cur_pg = pg;
ret = 0;
out: /* we fail the complete unit on an error eg don't advance
* per_dev->length and cur_pg. This means that we might have a bigger
* bio than the CDB requested length (per_dev->length). That's fine
* only the oposite is fatal.
*/
return ret;
}
static int _prepare_for_striping(struct ore_io_state *ios)
{
struct ore_striping_info *si = &ios->si;
unsigned stripe_unit = ios->layout->stripe_unit;
unsigned mirrors_p1 = ios->layout->mirrors_p1;
unsigned group_width = ios->layout->group_width;
unsigned devs_in_group = group_width * mirrors_p1;
unsigned dev = si->dev;
unsigned first_dev = dev - (dev % devs_in_group);
unsigned dev_order;
unsigned cur_pg = ios->pages_consumed;
u64 length = ios->length;
int ret = 0;
if (!ios->pages) {
ios->numdevs = ios->layout->mirrors_p1;
return 0;
}
BUG_ON(length > si->length);
dev_order = _dev_order(devs_in_group, mirrors_p1, si->par_dev, dev);
si->cur_comp = dev_order;
si->cur_pg = si->unit_off / PAGE_SIZE;
while (length) {
unsigned comp = dev - first_dev;
struct ore_per_dev_state *per_dev = &ios->per_dev[comp];
unsigned cur_len, page_off = 0;
if (!per_dev->length) {
per_dev->dev = dev;
if (dev == si->dev) {
WARN_ON(dev == si->par_dev);
per_dev->offset = si->obj_offset;
cur_len = stripe_unit - si->unit_off;
page_off = si->unit_off & ~PAGE_MASK;
BUG_ON(page_off && (page_off != ios->pgbase));
} else {
if (si->cur_comp > dev_order)
per_dev->offset =
si->obj_offset - si->unit_off;
else /* si->cur_comp < dev_order */
per_dev->offset =
si->obj_offset + stripe_unit -
si->unit_off;
cur_len = stripe_unit;
}
} else {
cur_len = stripe_unit;
}
if (cur_len >= length)
cur_len = length;
ret = _ore_add_stripe_unit(ios, &cur_pg, page_off, ios->pages,
per_dev, cur_len);
if (unlikely(ret))
goto out;
dev += mirrors_p1;
dev = (dev % devs_in_group) + first_dev;
length -= cur_len;
si->cur_comp = (si->cur_comp + 1) % group_width;
if (unlikely((dev == si->par_dev) || (!length && ios->sp2d))) {
if (!length && ios->sp2d) {
/* If we are writing and this is the very last
* stripe. then operate on parity dev.
*/
dev = si->par_dev;
}
if (ios->sp2d)
/* In writes cur_len just means if it's the
* last one. See _ore_add_parity_unit.
*/
cur_len = length;
per_dev = &ios->per_dev[dev - first_dev];
if (!per_dev->length) {
/* Only/always the parity unit of the first
* stripe will be empty. So this is a chance to
* initialize the per_dev info.
*/
per_dev->dev = dev;
per_dev->offset = si->obj_offset - si->unit_off;
}
ret = _ore_add_parity_unit(ios, si, per_dev, cur_len);
if (unlikely(ret))
goto out;
/* Rotate next par_dev backwards with wraping */
si->par_dev = (devs_in_group + si->par_dev -
ios->layout->parity * mirrors_p1) %
devs_in_group + first_dev;
/* Next stripe, start fresh */
si->cur_comp = 0;
si->cur_pg = 0;
}
}
out:
ios->numdevs = devs_in_group;
ios->pages_consumed = cur_pg;
if (unlikely(ret)) {
if (length == ios->length)
return ret;
else
ios->length -= length;
}
return 0;
}
int ore_create(struct ore_io_state *ios)
{
int i, ret;
for (i = 0; i < ios->oc->numdevs; i++) {
struct osd_request *or;
or = osd_start_request(_ios_od(ios, i), GFP_KERNEL);
if (unlikely(!or)) {
ORE_ERR("%s: osd_start_request failed\n", __func__);
ret = -ENOMEM;
goto out;
}
ios->per_dev[i].or = or;
ios->numdevs++;
osd_req_create_object(or, _ios_obj(ios, i));
}
ret = ore_io_execute(ios);
out:
return ret;
}
EXPORT_SYMBOL(ore_create);
int ore_remove(struct ore_io_state *ios)
{
int i, ret;
for (i = 0; i < ios->oc->numdevs; i++) {
struct osd_request *or;
or = osd_start_request(_ios_od(ios, i), GFP_KERNEL);
if (unlikely(!or)) {
ORE_ERR("%s: osd_start_request failed\n", __func__);
ret = -ENOMEM;
goto out;
}
ios->per_dev[i].or = or;
ios->numdevs++;
osd_req_remove_object(or, _ios_obj(ios, i));
}
ret = ore_io_execute(ios);
out:
return ret;
}
EXPORT_SYMBOL(ore_remove);
static int _write_mirror(struct ore_io_state *ios, int cur_comp)
{
struct ore_per_dev_state *master_dev = &ios->per_dev[cur_comp];
unsigned dev = ios->per_dev[cur_comp].dev;
unsigned last_comp = cur_comp + ios->layout->mirrors_p1;
int ret = 0;
if (ios->pages && !master_dev->length)
return 0; /* Just an empty slot */
for (; cur_comp < last_comp; ++cur_comp, ++dev) {
struct ore_per_dev_state *per_dev = &ios->per_dev[cur_comp];
struct osd_request *or;
or = osd_start_request(_ios_od(ios, dev), GFP_KERNEL);
if (unlikely(!or)) {
ORE_ERR("%s: osd_start_request failed\n", __func__);
ret = -ENOMEM;
goto out;
}
per_dev->or = or;
if (ios->pages) {
struct bio *bio;
if (per_dev != master_dev) {
bio = bio_kmalloc(GFP_KERNEL,
master_dev->bio->bi_max_vecs);
if (unlikely(!bio)) {
ORE_DBGMSG(
"Failed to allocate BIO size=%u\n",
master_dev->bio->bi_max_vecs);
ret = -ENOMEM;
goto out;
}
__bio_clone(bio, master_dev->bio);
bio->bi_bdev = NULL;
bio->bi_next = NULL;
per_dev->offset = master_dev->offset;
per_dev->length = master_dev->length;
per_dev->bio = bio;
per_dev->dev = dev;
} else {
bio = master_dev->bio;
/* FIXME: bio_set_dir() */
bio->bi_rw |= REQ_WRITE;
}
osd_req_write(or, _ios_obj(ios, dev), per_dev->offset,
bio, per_dev->length);
ORE_DBGMSG("write(0x%llx) offset=0x%llx "
"length=0x%llx dev=%d\n",
_LLU(_ios_obj(ios, dev)->id),
_LLU(per_dev->offset),
_LLU(per_dev->length), dev);
} else if (ios->kern_buff) {
per_dev->offset = ios->si.obj_offset;
per_dev->dev = ios->si.dev + dev;
/* no cross device without page array */
BUG_ON((ios->layout->group_width > 1) &&
(ios->si.unit_off + ios->length >
ios->layout->stripe_unit));
ret = osd_req_write_kern(or, _ios_obj(ios, per_dev->dev),
per_dev->offset,
ios->kern_buff, ios->length);
if (unlikely(ret))
goto out;
ORE_DBGMSG2("write_kern(0x%llx) offset=0x%llx "
"length=0x%llx dev=%d\n",
_LLU(_ios_obj(ios, dev)->id),
_LLU(per_dev->offset),
_LLU(ios->length), per_dev->dev);
} else {
osd_req_set_attributes(or, _ios_obj(ios, dev));
ORE_DBGMSG2("obj(0x%llx) set_attributes=%d dev=%d\n",
_LLU(_ios_obj(ios, dev)->id),
ios->out_attr_len, dev);
}
if (ios->out_attr)
osd_req_add_set_attr_list(or, ios->out_attr,
ios->out_attr_len);
if (ios->in_attr)
osd_req_add_get_attr_list(or, ios->in_attr,
ios->in_attr_len);
}
out:
return ret;
}
int ore_write(struct ore_io_state *ios)
{
int i;
int ret;
if (unlikely(ios->sp2d && !ios->r4w)) {
/* A library is attempting a RAID-write without providing
* a pages lock interface.
*/
WARN_ON_ONCE(1);
return -ENOTSUPP;
}
ret = _prepare_for_striping(ios);
if (unlikely(ret))
return ret;
for (i = 0; i < ios->numdevs; i += ios->layout->mirrors_p1) {
ret = _write_mirror(ios, i);
if (unlikely(ret))
return ret;
}
ret = ore_io_execute(ios);
return ret;
}
EXPORT_SYMBOL(ore_write);
int _ore_read_mirror(struct ore_io_state *ios, unsigned cur_comp)
{
struct osd_request *or;
struct ore_per_dev_state *per_dev = &ios->per_dev[cur_comp];
struct osd_obj_id *obj = _ios_obj(ios, cur_comp);
unsigned first_dev = (unsigned)obj->id;
if (ios->pages && !per_dev->length)
return 0; /* Just an empty slot */
first_dev = per_dev->dev + first_dev % ios->layout->mirrors_p1;
or = osd_start_request(_ios_od(ios, first_dev), GFP_KERNEL);
if (unlikely(!or)) {
ORE_ERR("%s: osd_start_request failed\n", __func__);
return -ENOMEM;
}
per_dev->or = or;
if (ios->pages) {
if (per_dev->cur_sg) {
/* finalize the last sg_entry */
_ore_add_sg_seg(per_dev, 0, false);
if (unlikely(!per_dev->cur_sg))
return 0; /* Skip parity only device */
osd_req_read_sg(or, obj, per_dev->bio,
per_dev->sglist, per_dev->cur_sg);
} else {
/* The no raid case */
osd_req_read(or, obj, per_dev->offset,
per_dev->bio, per_dev->length);
}
ORE_DBGMSG("read(0x%llx) offset=0x%llx length=0x%llx"
" dev=%d sg_len=%d\n", _LLU(obj->id),
_LLU(per_dev->offset), _LLU(per_dev->length),
first_dev, per_dev->cur_sg);
} else {
BUG_ON(ios->kern_buff);
osd_req_get_attributes(or, obj);
ORE_DBGMSG2("obj(0x%llx) get_attributes=%d dev=%d\n",
_LLU(obj->id),
ios->in_attr_len, first_dev);
}
if (ios->out_attr)
osd_req_add_set_attr_list(or, ios->out_attr, ios->out_attr_len);
if (ios->in_attr)
osd_req_add_get_attr_list(or, ios->in_attr, ios->in_attr_len);
return 0;
}
int ore_read(struct ore_io_state *ios)
{
int i;
int ret;
ret = _prepare_for_striping(ios);
if (unlikely(ret))
return ret;
for (i = 0; i < ios->numdevs; i += ios->layout->mirrors_p1) {
ret = _ore_read_mirror(ios, i);
if (unlikely(ret))
return ret;
}
ret = ore_io_execute(ios);
return ret;
}
EXPORT_SYMBOL(ore_read);
int extract_attr_from_ios(struct ore_io_state *ios, struct osd_attr *attr)
{
struct osd_attr cur_attr = {.attr_page = 0}; /* start with zeros */
void *iter = NULL;
int nelem;
do {
nelem = 1;
osd_req_decode_get_attr_list(ios->per_dev[0].or,
&cur_attr, &nelem, &iter);
if ((cur_attr.attr_page == attr->attr_page) &&
(cur_attr.attr_id == attr->attr_id)) {
attr->len = cur_attr.len;
attr->val_ptr = cur_attr.val_ptr;
return 0;
}
} while (iter);
return -EIO;
}
EXPORT_SYMBOL(extract_attr_from_ios);
static int _truncate_mirrors(struct ore_io_state *ios, unsigned cur_comp,
struct osd_attr *attr)
{
int last_comp = cur_comp + ios->layout->mirrors_p1;
for (; cur_comp < last_comp; ++cur_comp) {
struct ore_per_dev_state *per_dev = &ios->per_dev[cur_comp];
struct osd_request *or;
or = osd_start_request(_ios_od(ios, cur_comp), GFP_KERNEL);
if (unlikely(!or)) {
ORE_ERR("%s: osd_start_request failed\n", __func__);
return -ENOMEM;
}
per_dev->or = or;
osd_req_set_attributes(or, _ios_obj(ios, cur_comp));
osd_req_add_set_attr_list(or, attr, 1);
}
return 0;
}
struct _trunc_info {
struct ore_striping_info si;
u64 prev_group_obj_off;
u64 next_group_obj_off;
unsigned first_group_dev;
unsigned nex_group_dev;
};
static void _calc_trunk_info(struct ore_layout *layout, u64 file_offset,
struct _trunc_info *ti)
{
unsigned stripe_unit = layout->stripe_unit;
ore_calc_stripe_info(layout, file_offset, 0, &ti->si);
ti->prev_group_obj_off = ti->si.M * stripe_unit;
ti->next_group_obj_off = ti->si.M ? (ti->si.M - 1) * stripe_unit : 0;
ti->first_group_dev = ti->si.dev - (ti->si.dev % layout->group_width);
ti->nex_group_dev = ti->first_group_dev + layout->group_width;
}
int ore_truncate(struct ore_layout *layout, struct ore_components *oc,
u64 size)
{
struct ore_io_state *ios;
struct exofs_trunc_attr {
struct osd_attr attr;
__be64 newsize;
} *size_attrs;
struct _trunc_info ti;
int i, ret;
ret = ore_get_io_state(layout, oc, &ios);
if (unlikely(ret))
return ret;
_calc_trunk_info(ios->layout, size, &ti);
size_attrs = kcalloc(ios->oc->numdevs, sizeof(*size_attrs),
GFP_KERNEL);
if (unlikely(!size_attrs)) {
ret = -ENOMEM;
goto out;
}
ios->numdevs = ios->oc->numdevs;
for (i = 0; i < ios->numdevs; ++i) {
struct exofs_trunc_attr *size_attr = &size_attrs[i];
u64 obj_size;
if (i < ti.first_group_dev)
obj_size = ti.prev_group_obj_off;
else if (i >= ti.nex_group_dev)
obj_size = ti.next_group_obj_off;
else if (i < ti.si.dev) /* dev within this group */
obj_size = ti.si.obj_offset +
ios->layout->stripe_unit - ti.si.unit_off;
else if (i == ti.si.dev)
obj_size = ti.si.obj_offset;
else /* i > ti.dev */
obj_size = ti.si.obj_offset - ti.si.unit_off;
size_attr->newsize = cpu_to_be64(obj_size);
size_attr->attr = g_attr_logical_length;
size_attr->attr.val_ptr = &size_attr->newsize;
ORE_DBGMSG("trunc(0x%llx) obj_offset=0x%llx dev=%d\n",
_LLU(oc->comps->obj.id), _LLU(obj_size), i);
ret = _truncate_mirrors(ios, i * ios->layout->mirrors_p1,
&size_attr->attr);
if (unlikely(ret))
goto out;
}
ret = ore_io_execute(ios);
out:
kfree(size_attrs);
ore_put_io_state(ios);
return ret;
}
EXPORT_SYMBOL(ore_truncate);
const struct osd_attr g_attr_logical_length = ATTR_DEF(
OSD_APAGE_OBJECT_INFORMATION, OSD_ATTR_OI_LOGICAL_LENGTH, 8);
EXPORT_SYMBOL(g_attr_logical_length);
| gpl-2.0 |
mcgi5sr2/kernel_samsung_smdk4412 | scripts/dtc/srcpos.c | 3205 | 5440 | /*
* Copyright 2007 Jon Loeliger, Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#define _GNU_SOURCE
#include <stdio.h>
#include "dtc.h"
#include "srcpos.h"
static char *dirname(const char *path)
{
const char *slash = strrchr(path, '/');
if (slash) {
int len = slash - path;
char *dir = xmalloc(len + 1);
memcpy(dir, path, len);
dir[len] = '\0';
return dir;
}
return NULL;
}
struct srcfile_state *current_srcfile; /* = NULL */
/* Detect infinite include recursion. */
#define MAX_SRCFILE_DEPTH (100)
static int srcfile_depth; /* = 0 */
FILE *srcfile_relative_open(const char *fname, char **fullnamep)
{
FILE *f;
char *fullname;
if (streq(fname, "-")) {
f = stdin;
fullname = xstrdup("<stdin>");
} else {
if (!current_srcfile || !current_srcfile->dir
|| (fname[0] == '/'))
fullname = xstrdup(fname);
else
fullname = join_path(current_srcfile->dir, fname);
f = fopen(fullname, "r");
if (!f)
die("Couldn't open \"%s\": %s\n", fname,
strerror(errno));
}
if (fullnamep)
*fullnamep = fullname;
else
free(fullname);
return f;
}
void srcfile_push(const char *fname)
{
struct srcfile_state *srcfile;
if (srcfile_depth++ >= MAX_SRCFILE_DEPTH)
die("Includes nested too deeply");
srcfile = xmalloc(sizeof(*srcfile));
srcfile->f = srcfile_relative_open(fname, &srcfile->name);
srcfile->dir = dirname(srcfile->name);
srcfile->prev = current_srcfile;
srcfile->lineno = 1;
srcfile->colno = 1;
current_srcfile = srcfile;
}
int srcfile_pop(void)
{
struct srcfile_state *srcfile = current_srcfile;
assert(srcfile);
current_srcfile = srcfile->prev;
if (fclose(srcfile->f))
die("Error closing \"%s\": %s\n", srcfile->name,
strerror(errno));
/* FIXME: We allow the srcfile_state structure to leak,
* because it could still be referenced from a location
* variable being carried through the parser somewhere. To
* fix this we could either allocate all the files from a
* table, or use a pool allocator. */
return current_srcfile ? 1 : 0;
}
/*
* The empty source position.
*/
struct srcpos srcpos_empty = {
.first_line = 0,
.first_column = 0,
.last_line = 0,
.last_column = 0,
.file = NULL,
};
#define TAB_SIZE 8
void srcpos_update(struct srcpos *pos, const char *text, int len)
{
int i;
pos->file = current_srcfile;
pos->first_line = current_srcfile->lineno;
pos->first_column = current_srcfile->colno;
for (i = 0; i < len; i++)
if (text[i] == '\n') {
current_srcfile->lineno++;
current_srcfile->colno = 1;
} else if (text[i] == '\t') {
current_srcfile->colno =
ALIGN(current_srcfile->colno, TAB_SIZE);
} else {
current_srcfile->colno++;
}
pos->last_line = current_srcfile->lineno;
pos->last_column = current_srcfile->colno;
}
struct srcpos *
srcpos_copy(struct srcpos *pos)
{
struct srcpos *pos_new;
pos_new = xmalloc(sizeof(struct srcpos));
memcpy(pos_new, pos, sizeof(struct srcpos));
return pos_new;
}
void
srcpos_dump(struct srcpos *pos)
{
printf("file : \"%s\"\n",
pos->file ? (char *) pos->file : "<no file>");
printf("first_line : %d\n", pos->first_line);
printf("first_column: %d\n", pos->first_column);
printf("last_line : %d\n", pos->last_line);
printf("last_column : %d\n", pos->last_column);
printf("file : %s\n", pos->file->name);
}
char *
srcpos_string(struct srcpos *pos)
{
const char *fname = "<no-file>";
char *pos_str;
int rc;
if (pos)
fname = pos->file->name;
if (pos->first_line != pos->last_line)
rc = asprintf(&pos_str, "%s:%d.%d-%d.%d", fname,
pos->first_line, pos->first_column,
pos->last_line, pos->last_column);
else if (pos->first_column != pos->last_column)
rc = asprintf(&pos_str, "%s:%d.%d-%d", fname,
pos->first_line, pos->first_column,
pos->last_column);
else
rc = asprintf(&pos_str, "%s:%d.%d", fname,
pos->first_line, pos->first_column);
if (rc == -1)
die("Couldn't allocate in srcpos string");
return pos_str;
}
void
srcpos_verror(struct srcpos *pos, char const *fmt, va_list va)
{
const char *srcstr;
srcstr = srcpos_string(pos);
fprintf(stdout, "Error: %s ", srcstr);
vfprintf(stdout, fmt, va);
fprintf(stdout, "\n");
}
void
srcpos_error(struct srcpos *pos, char const *fmt, ...)
{
va_list va;
va_start(va, fmt);
srcpos_verror(pos, fmt, va);
va_end(va);
}
void
srcpos_warn(struct srcpos *pos, char const *fmt, ...)
{
const char *srcstr;
va_list va;
va_start(va, fmt);
srcstr = srcpos_string(pos);
fprintf(stderr, "Warning: %s ", srcstr);
vfprintf(stderr, fmt, va);
fprintf(stderr, "\n");
va_end(va);
}
| gpl-2.0 |
skelton/amlogic_common_3050 | sound/isa/sb/sb16.c | 3973 | 20372 | /*
* Driver for SoundBlaster 16/AWE32/AWE64 soundcards
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* 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 <asm/dma.h>
#include <linux/init.h>
#include <linux/pnp.h>
#include <linux/err.h>
#include <linux/isa.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/sb.h>
#include <sound/sb16_csp.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#include <sound/emu8000.h>
#include <sound/seq_device.h>
#define SNDRV_LEGACY_FIND_FREE_IRQ
#define SNDRV_LEGACY_FIND_FREE_DMA
#include <sound/initval.h>
#ifdef SNDRV_SBAWE
#define PFX "sbawe: "
#else
#define PFX "sb16: "
#endif
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_LICENSE("GPL");
#ifndef SNDRV_SBAWE
MODULE_DESCRIPTION("Sound Blaster 16");
MODULE_SUPPORTED_DEVICE("{{Creative Labs,SB 16},"
"{Creative Labs,SB Vibra16S},"
"{Creative Labs,SB Vibra16C},"
"{Creative Labs,SB Vibra16CL},"
"{Creative Labs,SB Vibra16X}}");
#else
MODULE_DESCRIPTION("Sound Blaster AWE");
MODULE_SUPPORTED_DEVICE("{{Creative Labs,SB AWE 32},"
"{Creative Labs,SB AWE 64},"
"{Creative Labs,SB AWE 64 Gold}}");
#endif
#if 0
#define SNDRV_DEBUG_IRQ
#endif
#if defined(SNDRV_SBAWE) && (defined(CONFIG_SND_SEQUENCER) || (defined(MODULE) && defined(CONFIG_SND_SEQUENCER_MODULE)))
#define SNDRV_SBAWE_EMU8000
#endif
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_ISAPNP; /* Enable this card */
#ifdef CONFIG_PNP
static int isapnp[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
#endif
static long port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x220,0x240,0x260,0x280 */
static long mpu_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT; /* 0x330,0x300 */
static long fm_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT;
#ifdef SNDRV_SBAWE_EMU8000
static long awe_port[SNDRV_CARDS] = SNDRV_DEFAULT_PORT;
#endif
static int irq[SNDRV_CARDS] = SNDRV_DEFAULT_IRQ; /* 5,7,9,10 */
static int dma8[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 0,1,3 */
static int dma16[SNDRV_CARDS] = SNDRV_DEFAULT_DMA; /* 5,6,7 */
static int mic_agc[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 1};
#ifdef CONFIG_SND_SB16_CSP
static int csp[SNDRV_CARDS];
#endif
#ifdef SNDRV_SBAWE_EMU8000
static int seq_ports[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 4};
#endif
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for SoundBlaster 16 soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for SoundBlaster 16 soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable SoundBlaster 16 soundcard.");
#ifdef CONFIG_PNP
module_param_array(isapnp, bool, NULL, 0444);
MODULE_PARM_DESC(isapnp, "PnP detection for specified soundcard.");
#endif
module_param_array(port, long, NULL, 0444);
MODULE_PARM_DESC(port, "Port # for SB16 driver.");
module_param_array(mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(mpu_port, "MPU-401 port # for SB16 driver.");
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM port # for SB16 PnP driver.");
#ifdef SNDRV_SBAWE_EMU8000
module_param_array(awe_port, long, NULL, 0444);
MODULE_PARM_DESC(awe_port, "AWE port # for SB16 PnP driver.");
#endif
module_param_array(irq, int, NULL, 0444);
MODULE_PARM_DESC(irq, "IRQ # for SB16 driver.");
module_param_array(dma8, int, NULL, 0444);
MODULE_PARM_DESC(dma8, "8-bit DMA # for SB16 driver.");
module_param_array(dma16, int, NULL, 0444);
MODULE_PARM_DESC(dma16, "16-bit DMA # for SB16 driver.");
module_param_array(mic_agc, int, NULL, 0444);
MODULE_PARM_DESC(mic_agc, "Mic Auto-Gain-Control switch.");
#ifdef CONFIG_SND_SB16_CSP
module_param_array(csp, int, NULL, 0444);
MODULE_PARM_DESC(csp, "ASP/CSP chip support.");
#endif
#ifdef SNDRV_SBAWE_EMU8000
module_param_array(seq_ports, int, NULL, 0444);
MODULE_PARM_DESC(seq_ports, "Number of sequencer ports for WaveTable synth.");
#endif
#ifdef CONFIG_PNP
static int isa_registered;
static int pnp_registered;
#endif
struct snd_card_sb16 {
struct resource *fm_res; /* used to block FM i/o region for legacy cards */
struct snd_sb *chip;
#ifdef CONFIG_PNP
int dev_no;
struct pnp_dev *dev;
#ifdef SNDRV_SBAWE_EMU8000
struct pnp_dev *devwt;
#endif
#endif
};
#ifdef CONFIG_PNP
static struct pnp_card_device_id snd_sb16_pnpids[] = {
#ifndef SNDRV_SBAWE
/* Sound Blaster 16 PnP */
{ .id = "CTL0024", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0025", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0026", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0027", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0028", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL0029", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL002a", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
/* Note: This card has also a CTL0051:StereoEnhance device!!! */
{ .id = "CTL002b", .devs = { { "CTL0031" } } },
/* Sound Blaster 16 PnP */
{ .id = "CTL002c", .devs = { { "CTL0031" } } },
/* Sound Blaster Vibra16S */
{ .id = "CTL0051", .devs = { { "CTL0001" } } },
/* Sound Blaster Vibra16C */
{ .id = "CTL0070", .devs = { { "CTL0001" } } },
/* Sound Blaster Vibra16CL - added by ctm@ardi.com */
{ .id = "CTL0080", .devs = { { "CTL0041" } } },
/* Sound Blaster 16 'value' PnP. It says model ct4130 on the pcb, */
/* but ct4131 on a sticker on the board.. */
{ .id = "CTL0086", .devs = { { "CTL0041" } } },
/* Sound Blaster Vibra16X */
{ .id = "CTL00f0", .devs = { { "CTL0043" } } },
/* Sound Blaster 16 (Virtual PC 2004) */
{ .id = "tBA03b0", .devs = { {.id="PNPb003" } } },
#else /* SNDRV_SBAWE defined */
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0035", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0039", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0042", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0043", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
/* Note: This card has also a CTL0051:StereoEnhance device!!! */
{ .id = "CTL0044", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
/* Note: This card has also a CTL0051:StereoEnhance device!!! */
{ .id = "CTL0045", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0046", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0047", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0048", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL0054", .devs = { { "CTL0031" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL009a", .devs = { { "CTL0041" }, { "CTL0021" } } },
/* Sound Blaster AWE 32 PnP */
{ .id = "CTL009c", .devs = { { "CTL0041" }, { "CTL0021" } } },
/* Sound Blaster 32 PnP */
{ .id = "CTL009f", .devs = { { "CTL0041" }, { "CTL0021" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL009d", .devs = { { "CTL0042" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP Gold */
{ .id = "CTL009e", .devs = { { "CTL0044" }, { "CTL0023" } } },
/* Sound Blaster AWE 64 PnP Gold */
{ .id = "CTL00b2", .devs = { { "CTL0044" }, { "CTL0023" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00c1", .devs = { { "CTL0042" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00c3", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00c5", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00c7", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00e4", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster AWE 64 PnP */
{ .id = "CTL00e9", .devs = { { "CTL0045" }, { "CTL0022" } } },
/* Sound Blaster 16 PnP (AWE) */
{ .id = "CTL00ed", .devs = { { "CTL0041" }, { "CTL0070" } } },
/* Generic entries */
{ .id = "CTLXXXX" , .devs = { { "CTL0031" }, { "CTL0021" } } },
{ .id = "CTLXXXX" , .devs = { { "CTL0041" }, { "CTL0021" } } },
{ .id = "CTLXXXX" , .devs = { { "CTL0042" }, { "CTL0022" } } },
{ .id = "CTLXXXX" , .devs = { { "CTL0044" }, { "CTL0023" } } },
{ .id = "CTLXXXX" , .devs = { { "CTL0045" }, { "CTL0022" } } },
#endif /* SNDRV_SBAWE */
{ .id = "", }
};
MODULE_DEVICE_TABLE(pnp_card, snd_sb16_pnpids);
#endif /* CONFIG_PNP */
#ifdef SNDRV_SBAWE_EMU8000
#define DRIVER_NAME "snd-card-sbawe"
#else
#define DRIVER_NAME "snd-card-sb16"
#endif
#ifdef CONFIG_PNP
static int __devinit snd_card_sb16_pnp(int dev, struct snd_card_sb16 *acard,
struct pnp_card_link *card,
const struct pnp_card_device_id *id)
{
struct pnp_dev *pdev;
int err;
acard->dev = pnp_request_card_device(card, id->devs[0].id, NULL);
if (acard->dev == NULL)
return -ENODEV;
#ifdef SNDRV_SBAWE_EMU8000
acard->devwt = pnp_request_card_device(card, id->devs[1].id, acard->dev);
#endif
/* Audio initialization */
pdev = acard->dev;
err = pnp_activate_dev(pdev);
if (err < 0) {
snd_printk(KERN_ERR PFX "AUDIO pnp configure failure\n");
return err;
}
port[dev] = pnp_port_start(pdev, 0);
mpu_port[dev] = pnp_port_start(pdev, 1);
fm_port[dev] = pnp_port_start(pdev, 2);
dma8[dev] = pnp_dma(pdev, 0);
dma16[dev] = pnp_dma(pdev, 1);
irq[dev] = pnp_irq(pdev, 0);
snd_printdd("pnp SB16: port=0x%lx, mpu port=0x%lx, fm port=0x%lx\n",
port[dev], mpu_port[dev], fm_port[dev]);
snd_printdd("pnp SB16: dma1=%i, dma2=%i, irq=%i\n",
dma8[dev], dma16[dev], irq[dev]);
#ifdef SNDRV_SBAWE_EMU8000
/* WaveTable initialization */
pdev = acard->devwt;
if (pdev != NULL) {
err = pnp_activate_dev(pdev);
if (err < 0) {
goto __wt_error;
}
awe_port[dev] = pnp_port_start(pdev, 0);
snd_printdd("pnp SB16: wavetable port=0x%llx\n",
(unsigned long long)pnp_port_start(pdev, 0));
} else {
__wt_error:
if (pdev) {
pnp_release_card_device(pdev);
snd_printk(KERN_ERR PFX "WaveTable pnp configure failure\n");
}
acard->devwt = NULL;
awe_port[dev] = -1;
}
#endif
return 0;
}
#endif /* CONFIG_PNP */
static void snd_sb16_free(struct snd_card *card)
{
struct snd_card_sb16 *acard = card->private_data;
if (acard == NULL)
return;
release_and_free_resource(acard->fm_res);
}
#ifdef CONFIG_PNP
#define is_isapnp_selected(dev) isapnp[dev]
#else
#define is_isapnp_selected(dev) 0
#endif
static int snd_sb16_card_new(int dev, struct snd_card **cardp)
{
struct snd_card *card;
int err;
err = snd_card_create(index[dev], id[dev], THIS_MODULE,
sizeof(struct snd_card_sb16), &card);
if (err < 0)
return err;
card->private_free = snd_sb16_free;
*cardp = card;
return 0;
}
static int __devinit snd_sb16_probe(struct snd_card *card, int dev)
{
int xirq, xdma8, xdma16;
struct snd_sb *chip;
struct snd_card_sb16 *acard = card->private_data;
struct snd_opl3 *opl3;
struct snd_hwdep *synth = NULL;
#ifdef CONFIG_SND_SB16_CSP
struct snd_hwdep *xcsp = NULL;
#endif
unsigned long flags;
int err;
xirq = irq[dev];
xdma8 = dma8[dev];
xdma16 = dma16[dev];
if ((err = snd_sbdsp_create(card,
port[dev],
xirq,
snd_sb16dsp_interrupt,
xdma8,
xdma16,
SB_HW_AUTO,
&chip)) < 0)
return err;
acard->chip = chip;
if (chip->hardware != SB_HW_16) {
snd_printk(KERN_ERR PFX "SB 16 chip was not detected at 0x%lx\n", port[dev]);
return -ENODEV;
}
chip->mpu_port = mpu_port[dev];
if (! is_isapnp_selected(dev) && (err = snd_sb16dsp_configure(chip)) < 0)
return err;
if ((err = snd_sb16dsp_pcm(chip, 0, &chip->pcm)) < 0)
return err;
strcpy(card->driver,
#ifdef SNDRV_SBAWE_EMU8000
awe_port[dev] > 0 ? "SB AWE" :
#endif
"SB16");
strcpy(card->shortname, chip->name);
sprintf(card->longname, "%s at 0x%lx, irq %i, dma ",
chip->name,
chip->port,
xirq);
if (xdma8 >= 0)
sprintf(card->longname + strlen(card->longname), "%d", xdma8);
if (xdma16 >= 0)
sprintf(card->longname + strlen(card->longname), "%s%d",
xdma8 >= 0 ? "&" : "", xdma16);
if (chip->mpu_port > 0 && chip->mpu_port != SNDRV_AUTO_PORT) {
if ((err = snd_mpu401_uart_new(card, 0, MPU401_HW_SB,
chip->mpu_port, 0,
xirq, 0, &chip->rmidi)) < 0)
return err;
chip->rmidi_callback = snd_mpu401_uart_interrupt;
}
#ifdef SNDRV_SBAWE_EMU8000
if (awe_port[dev] == SNDRV_AUTO_PORT)
awe_port[dev] = 0; /* disable */
#endif
if (fm_port[dev] > 0 && fm_port[dev] != SNDRV_AUTO_PORT) {
if (snd_opl3_create(card, fm_port[dev], fm_port[dev] + 2,
OPL3_HW_OPL3,
acard->fm_res != NULL || fm_port[dev] == port[dev],
&opl3) < 0) {
snd_printk(KERN_ERR PFX "no OPL device at 0x%lx-0x%lx\n",
fm_port[dev], fm_port[dev] + 2);
} else {
#ifdef SNDRV_SBAWE_EMU8000
int seqdev = awe_port[dev] > 0 ? 2 : 1;
#else
int seqdev = 1;
#endif
if ((err = snd_opl3_hwdep_new(opl3, 0, seqdev, &synth)) < 0)
return err;
}
}
if ((err = snd_sbmixer_new(chip)) < 0)
return err;
#ifdef CONFIG_SND_SB16_CSP
/* CSP chip on SB16ASP/AWE32 */
if ((chip->hardware == SB_HW_16) && csp[dev]) {
snd_sb_csp_new(chip, synth != NULL ? 1 : 0, &xcsp);
if (xcsp) {
chip->csp = xcsp->private_data;
chip->hardware = SB_HW_16CSP;
} else {
snd_printk(KERN_INFO PFX "warning - CSP chip not detected on soundcard #%i\n", dev + 1);
}
}
#endif
#ifdef SNDRV_SBAWE_EMU8000
if (awe_port[dev] > 0) {
if ((err = snd_emu8000_new(card, 1, awe_port[dev],
seq_ports[dev], NULL)) < 0) {
snd_printk(KERN_ERR PFX "fatal error - EMU-8000 synthesizer not detected at 0x%lx\n", awe_port[dev]);
return err;
}
}
#endif
/* setup Mic AGC */
spin_lock_irqsave(&chip->mixer_lock, flags);
snd_sbmixer_write(chip, SB_DSP4_MIC_AGC,
(snd_sbmixer_read(chip, SB_DSP4_MIC_AGC) & 0x01) |
(mic_agc[dev] ? 0x00 : 0x01));
spin_unlock_irqrestore(&chip->mixer_lock, flags);
if ((err = snd_card_register(card)) < 0)
return err;
return 0;
}
#ifdef CONFIG_PM
static int snd_sb16_suspend(struct snd_card *card, pm_message_t state)
{
struct snd_card_sb16 *acard = card->private_data;
struct snd_sb *chip = acard->chip;
snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
snd_pcm_suspend_all(chip->pcm);
snd_sbmixer_suspend(chip);
return 0;
}
static int snd_sb16_resume(struct snd_card *card)
{
struct snd_card_sb16 *acard = card->private_data;
struct snd_sb *chip = acard->chip;
snd_sbdsp_reset(chip);
snd_sbmixer_resume(chip);
snd_power_change_state(card, SNDRV_CTL_POWER_D0);
return 0;
}
#endif
static int __devinit snd_sb16_isa_probe1(int dev, struct device *pdev)
{
struct snd_card_sb16 *acard;
struct snd_card *card;
int err;
err = snd_sb16_card_new(dev, &card);
if (err < 0)
return err;
acard = card->private_data;
/* non-PnP FM port address is hardwired with base port address */
fm_port[dev] = port[dev];
/* block the 0x388 port to avoid PnP conflicts */
acard->fm_res = request_region(0x388, 4, "SoundBlaster FM");
#ifdef SNDRV_SBAWE_EMU8000
/* non-PnP AWE port address is hardwired with base port address */
awe_port[dev] = port[dev] + 0x400;
#endif
snd_card_set_dev(card, pdev);
if ((err = snd_sb16_probe(card, dev)) < 0) {
snd_card_free(card);
return err;
}
dev_set_drvdata(pdev, card);
return 0;
}
static int __devinit snd_sb16_isa_match(struct device *pdev, unsigned int dev)
{
return enable[dev] && !is_isapnp_selected(dev);
}
static int __devinit snd_sb16_isa_probe(struct device *pdev, unsigned int dev)
{
int err;
static int possible_irqs[] = {5, 9, 10, 7, -1};
static int possible_dmas8[] = {1, 3, 0, -1};
static int possible_dmas16[] = {5, 6, 7, -1};
if (irq[dev] == SNDRV_AUTO_IRQ) {
if ((irq[dev] = snd_legacy_find_free_irq(possible_irqs)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free IRQ\n");
return -EBUSY;
}
}
if (dma8[dev] == SNDRV_AUTO_DMA) {
if ((dma8[dev] = snd_legacy_find_free_dma(possible_dmas8)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free 8-bit DMA\n");
return -EBUSY;
}
}
if (dma16[dev] == SNDRV_AUTO_DMA) {
if ((dma16[dev] = snd_legacy_find_free_dma(possible_dmas16)) < 0) {
snd_printk(KERN_ERR PFX "unable to find a free 16-bit DMA\n");
return -EBUSY;
}
}
if (port[dev] != SNDRV_AUTO_PORT)
return snd_sb16_isa_probe1(dev, pdev);
else {
static int possible_ports[] = {0x220, 0x240, 0x260, 0x280};
int i;
for (i = 0; i < ARRAY_SIZE(possible_ports); i++) {
port[dev] = possible_ports[i];
err = snd_sb16_isa_probe1(dev, pdev);
if (! err)
return 0;
}
return err;
}
}
static int __devexit snd_sb16_isa_remove(struct device *pdev, unsigned int dev)
{
snd_card_free(dev_get_drvdata(pdev));
dev_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int snd_sb16_isa_suspend(struct device *dev, unsigned int n,
pm_message_t state)
{
return snd_sb16_suspend(dev_get_drvdata(dev), state);
}
static int snd_sb16_isa_resume(struct device *dev, unsigned int n)
{
return snd_sb16_resume(dev_get_drvdata(dev));
}
#endif
#ifdef SNDRV_SBAWE
#define DEV_NAME "sbawe"
#else
#define DEV_NAME "sb16"
#endif
static struct isa_driver snd_sb16_isa_driver = {
.match = snd_sb16_isa_match,
.probe = snd_sb16_isa_probe,
.remove = __devexit_p(snd_sb16_isa_remove),
#ifdef CONFIG_PM
.suspend = snd_sb16_isa_suspend,
.resume = snd_sb16_isa_resume,
#endif
.driver = {
.name = DEV_NAME
},
};
#ifdef CONFIG_PNP
static int __devinit snd_sb16_pnp_detect(struct pnp_card_link *pcard,
const struct pnp_card_device_id *pid)
{
static int dev;
struct snd_card *card;
int res;
for ( ; dev < SNDRV_CARDS; dev++) {
if (!enable[dev] || !isapnp[dev])
continue;
res = snd_sb16_card_new(dev, &card);
if (res < 0)
return res;
snd_card_set_dev(card, &pcard->card->dev);
if ((res = snd_card_sb16_pnp(dev, card->private_data, pcard, pid)) < 0 ||
(res = snd_sb16_probe(card, dev)) < 0) {
snd_card_free(card);
return res;
}
pnp_set_card_drvdata(pcard, card);
dev++;
return 0;
}
return -ENODEV;
}
static void __devexit snd_sb16_pnp_remove(struct pnp_card_link * pcard)
{
snd_card_free(pnp_get_card_drvdata(pcard));
pnp_set_card_drvdata(pcard, NULL);
}
#ifdef CONFIG_PM
static int snd_sb16_pnp_suspend(struct pnp_card_link *pcard, pm_message_t state)
{
return snd_sb16_suspend(pnp_get_card_drvdata(pcard), state);
}
static int snd_sb16_pnp_resume(struct pnp_card_link *pcard)
{
return snd_sb16_resume(pnp_get_card_drvdata(pcard));
}
#endif
static struct pnp_card_driver sb16_pnpc_driver = {
.flags = PNP_DRIVER_RES_DISABLE,
#ifdef SNDRV_SBAWE
.name = "sbawe",
#else
.name = "sb16",
#endif
.id_table = snd_sb16_pnpids,
.probe = snd_sb16_pnp_detect,
.remove = __devexit_p(snd_sb16_pnp_remove),
#ifdef CONFIG_PM
.suspend = snd_sb16_pnp_suspend,
.resume = snd_sb16_pnp_resume,
#endif
};
#endif /* CONFIG_PNP */
static int __init alsa_card_sb16_init(void)
{
int err;
err = isa_register_driver(&snd_sb16_isa_driver, SNDRV_CARDS);
#ifdef CONFIG_PNP
if (!err)
isa_registered = 1;
err = pnp_register_card_driver(&sb16_pnpc_driver);
if (!err)
pnp_registered = 1;
if (isa_registered)
err = 0;
#endif
return err;
}
static void __exit alsa_card_sb16_exit(void)
{
#ifdef CONFIG_PNP
if (pnp_registered)
pnp_unregister_card_driver(&sb16_pnpc_driver);
if (isa_registered)
#endif
isa_unregister_driver(&snd_sb16_isa_driver);
}
module_init(alsa_card_sb16_init)
module_exit(alsa_card_sb16_exit)
| gpl-2.0 |
sailesh341/lge-kernel-p880 | drivers/isdn/hisax/elsa.c | 4229 | 34367 | /* $Id: elsa.c,v 2.32.2.4 2004/01/24 20:47:21 keil Exp $
*
* low level stuff for Elsa isdn cards
*
* Author Karsten Keil
* Copyright by Karsten Keil <keil@isdn4linux.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* For changes and modifications please read
* Documentation/isdn/HiSax.cert
*
* Thanks to Elsa GmbH for documents and information
*
* Klaus Lichtenwalder (Klaus.Lichtenwalder@WebForum.DE)
* for ELSA PCMCIA support
*
*/
#include <linux/init.h>
#include <linux/slab.h>
#include "hisax.h"
#include "arcofi.h"
#include "isac.h"
#include "ipac.h"
#include "hscx.h"
#include "isdnl1.h"
#include <linux/pci.h>
#include <linux/isapnp.h>
#include <linux/serial.h>
#include <linux/serial_reg.h>
static const char *Elsa_revision = "$Revision: 2.32.2.4 $";
static const char *Elsa_Types[] =
{"None", "PC", "PCC-8", "PCC-16", "PCF", "PCF-Pro",
"PCMCIA", "QS 1000", "QS 3000", "Microlink PCI", "QS 3000 PCI",
"PCMCIA-IPAC" };
static const char *ITACVer[] =
{"?0?", "?1?", "?2?", "?3?", "?4?", "V2.2",
"B1", "A1"};
#define byteout(addr,val) outb(val,addr)
#define bytein(addr) inb(addr)
#define ELSA_ISAC 0
#define ELSA_ISAC_PCM 1
#define ELSA_ITAC 1
#define ELSA_HSCX 2
#define ELSA_ALE 3
#define ELSA_ALE_PCM 4
#define ELSA_CONTROL 4
#define ELSA_CONFIG 5
#define ELSA_START_TIMER 6
#define ELSA_TRIG_IRQ 7
#define ELSA_PC 1
#define ELSA_PCC8 2
#define ELSA_PCC16 3
#define ELSA_PCF 4
#define ELSA_PCFPRO 5
#define ELSA_PCMCIA 6
#define ELSA_QS1000 7
#define ELSA_QS3000 8
#define ELSA_QS1000PCI 9
#define ELSA_QS3000PCI 10
#define ELSA_PCMCIA_IPAC 11
/* PCI stuff */
#define ELSA_PCI_IRQ_MASK 0x04
/* ITAC Registeradressen (only Microlink PC) */
#define ITAC_SYS 0x34
#define ITAC_ISEN 0x48
#define ITAC_RFIE 0x4A
#define ITAC_XFIE 0x4C
#define ITAC_SCIE 0x4E
#define ITAC_STIE 0x46
/*** ***
*** Makros als Befehle fuer die Kartenregister ***
*** (mehrere Befehle werden durch Bit-Oderung kombiniert) ***
*** ***/
/* Config-Register (Read) */
#define ELIRQF_TIMER_RUN 0x02 /* Bit 1 des Config-Reg */
#define ELIRQF_TIMER_RUN_PCC8 0x01 /* Bit 0 des Config-Reg bei PCC */
#define ELSA_IRQ_IDX 0x38 /* Bit 3,4,5 des Config-Reg */
#define ELSA_IRQ_IDX_PCC8 0x30 /* Bit 4,5 des Config-Reg */
#define ELSA_IRQ_IDX_PC 0x0c /* Bit 2,3 des Config-Reg */
/* Control-Register (Write) */
#define ELSA_LINE_LED 0x02 /* Bit 1 Gelbe LED */
#define ELSA_STAT_LED 0x08 /* Bit 3 Gruene LED */
#define ELSA_ISDN_RESET 0x20 /* Bit 5 Reset-Leitung */
#define ELSA_ENA_TIMER_INT 0x80 /* Bit 7 Freigabe Timer Interrupt */
/* ALE-Register (Read) */
#define ELSA_HW_RELEASE 0x07 /* Bit 0-2 Hardwarerkennung */
#define ELSA_S0_POWER_BAD 0x08 /* Bit 3 S0-Bus Spannung fehlt */
/* Status Flags */
#define ELIRQF_TIMER_AKTIV 1
#define ELSA_BAD_PWR 2
#define ELSA_ASSIGN 4
#define RS_ISR_PASS_LIMIT 256
#define FLG_MODEM_ACTIVE 1
/* IPAC AUX */
#define ELSA_IPAC_LINE_LED 0x40 /* Bit 6 Gelbe LED */
#define ELSA_IPAC_STAT_LED 0x80 /* Bit 7 Gruene LED */
#if ARCOFI_USE
static struct arcofi_msg ARCOFI_XOP_F =
{NULL,0,2,{0xa1,0x3f,0,0,0,0,0,0,0,0}}; /* Normal OP */
static struct arcofi_msg ARCOFI_XOP_1 =
{&ARCOFI_XOP_F,0,2,{0xa1,0x31,0,0,0,0,0,0,0,0}}; /* PWR UP */
static struct arcofi_msg ARCOFI_SOP_F =
{&ARCOFI_XOP_1,0,10,{0xa1,0x1f,0x00,0x50,0x10,0x00,0x00,0x80,0x02,0x12}};
static struct arcofi_msg ARCOFI_COP_9 =
{&ARCOFI_SOP_F,0,10,{0xa1,0x29,0x80,0xcb,0xe9,0x88,0x00,0xc8,0xd8,0x80}}; /* RX */
static struct arcofi_msg ARCOFI_COP_8 =
{&ARCOFI_COP_9,0,10,{0xa1,0x28,0x49,0x31,0x8,0x13,0x6e,0x88,0x2a,0x61}}; /* TX */
static struct arcofi_msg ARCOFI_COP_7 =
{&ARCOFI_COP_8,0,4,{0xa1,0x27,0x80,0x80,0,0,0,0,0,0}}; /* GZ */
static struct arcofi_msg ARCOFI_COP_6 =
{&ARCOFI_COP_7,0,6,{0xa1,0x26,0,0,0x82,0x7c,0,0,0,0}}; /* GRL GRH */
static struct arcofi_msg ARCOFI_COP_5 =
{&ARCOFI_COP_6,0,4,{0xa1,0x25,0xbb,0x4a,0,0,0,0,0,0}}; /* GTX */
static struct arcofi_msg ARCOFI_VERSION =
{NULL,1,2,{0xa0,0,0,0,0,0,0,0,0,0}};
static struct arcofi_msg ARCOFI_XOP_0 =
{NULL,0,2,{0xa1,0x30,0,0,0,0,0,0,0,0}}; /* PWR Down */
static void set_arcofi(struct IsdnCardState *cs, int bc);
#include "elsa_ser.c"
#endif /* ARCOFI_USE */
static inline u_char
readreg(unsigned int ale, unsigned int adr, u_char off)
{
register u_char ret;
byteout(ale, off);
ret = bytein(adr);
return (ret);
}
static inline void
readfifo(unsigned int ale, unsigned int adr, u_char off, u_char * data, int size)
{
byteout(ale, off);
insb(adr, data, size);
}
static inline void
writereg(unsigned int ale, unsigned int adr, u_char off, u_char data)
{
byteout(ale, off);
byteout(adr, data);
}
static inline void
writefifo(unsigned int ale, unsigned int adr, u_char off, u_char * data, int size)
{
byteout(ale, off);
outsb(adr, data, size);
}
/* Interface functions */
static u_char
ReadISAC(struct IsdnCardState *cs, u_char offset)
{
return (readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, offset));
}
static void
WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value)
{
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, offset, value);
}
static void
ReadISACfifo(struct IsdnCardState *cs, u_char * data, int size)
{
readfifo(cs->hw.elsa.ale, cs->hw.elsa.isac, 0, data, size);
}
static void
WriteISACfifo(struct IsdnCardState *cs, u_char * data, int size)
{
writefifo(cs->hw.elsa.ale, cs->hw.elsa.isac, 0, data, size);
}
static u_char
ReadISAC_IPAC(struct IsdnCardState *cs, u_char offset)
{
return (readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, offset+0x80));
}
static void
WriteISAC_IPAC(struct IsdnCardState *cs, u_char offset, u_char value)
{
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, offset|0x80, value);
}
static void
ReadISACfifo_IPAC(struct IsdnCardState *cs, u_char * data, int size)
{
readfifo(cs->hw.elsa.ale, cs->hw.elsa.isac, 0x80, data, size);
}
static void
WriteISACfifo_IPAC(struct IsdnCardState *cs, u_char * data, int size)
{
writefifo(cs->hw.elsa.ale, cs->hw.elsa.isac, 0x80, data, size);
}
static u_char
ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset)
{
return (readreg(cs->hw.elsa.ale,
cs->hw.elsa.hscx, offset + (hscx ? 0x40 : 0)));
}
static void
WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value)
{
writereg(cs->hw.elsa.ale,
cs->hw.elsa.hscx, offset + (hscx ? 0x40 : 0), value);
}
static inline u_char
readitac(struct IsdnCardState *cs, u_char off)
{
register u_char ret;
byteout(cs->hw.elsa.ale, off);
ret = bytein(cs->hw.elsa.itac);
return (ret);
}
static inline void
writeitac(struct IsdnCardState *cs, u_char off, u_char data)
{
byteout(cs->hw.elsa.ale, off);
byteout(cs->hw.elsa.itac, data);
}
static inline int
TimerRun(struct IsdnCardState *cs)
{
register u_char v;
v = bytein(cs->hw.elsa.cfg);
if ((cs->subtyp == ELSA_QS1000) || (cs->subtyp == ELSA_QS3000))
return (0 == (v & ELIRQF_TIMER_RUN));
else if (cs->subtyp == ELSA_PCC8)
return (v & ELIRQF_TIMER_RUN_PCC8);
return (v & ELIRQF_TIMER_RUN);
}
/*
* fast interrupt HSCX stuff goes here
*/
#define READHSCX(cs, nr, reg) readreg(cs->hw.elsa.ale, \
cs->hw.elsa.hscx, reg + (nr ? 0x40 : 0))
#define WRITEHSCX(cs, nr, reg, data) writereg(cs->hw.elsa.ale, \
cs->hw.elsa.hscx, reg + (nr ? 0x40 : 0), data)
#define READHSCXFIFO(cs, nr, ptr, cnt) readfifo(cs->hw.elsa.ale, \
cs->hw.elsa.hscx, (nr ? 0x40 : 0), ptr, cnt)
#define WRITEHSCXFIFO(cs, nr, ptr, cnt) writefifo(cs->hw.elsa.ale, \
cs->hw.elsa.hscx, (nr ? 0x40 : 0), ptr, cnt)
#include "hscx_irq.c"
static irqreturn_t
elsa_interrupt(int intno, void *dev_id)
{
struct IsdnCardState *cs = dev_id;
u_long flags;
u_char val;
int icnt=5;
if ((cs->typ == ISDN_CTYPE_ELSA_PCMCIA) && (*cs->busy_flag == 1)) {
/* The card tends to generate interrupts while being removed
causing us to just crash the kernel. bad. */
printk(KERN_WARNING "Elsa: card not available!\n");
return IRQ_NONE;
}
spin_lock_irqsave(&cs->lock, flags);
#if ARCOFI_USE
if (cs->hw.elsa.MFlag) {
val = serial_inp(cs, UART_IIR);
if (!(val & UART_IIR_NO_INT)) {
debugl1(cs,"IIR %02x", val);
rs_interrupt_elsa(cs);
}
}
#endif
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_ISTA + 0x40);
Start_HSCX:
if (val) {
hscx_int_main(cs, val);
}
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_ISTA);
Start_ISAC:
if (val) {
isac_interrupt(cs, val);
}
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_ISTA + 0x40);
if (val && icnt) {
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "HSCX IntStat after IntRoutine");
icnt--;
goto Start_HSCX;
}
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_ISTA);
if (val && icnt) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "ISAC IntStat after IntRoutine");
icnt--;
goto Start_ISAC;
}
if (!icnt)
printk(KERN_WARNING"ELSA IRQ LOOP\n");
writereg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_MASK, 0xFF);
writereg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_MASK + 0x40, 0xFF);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_MASK, 0xFF);
if (cs->hw.elsa.status & ELIRQF_TIMER_AKTIV) {
if (!TimerRun(cs)) {
/* Timer Restart */
byteout(cs->hw.elsa.timer, 0);
cs->hw.elsa.counter++;
}
}
#if ARCOFI_USE
if (cs->hw.elsa.MFlag) {
val = serial_inp(cs, UART_MCR);
val ^= 0x8;
serial_outp(cs, UART_MCR, val);
val = serial_inp(cs, UART_MCR);
val ^= 0x8;
serial_outp(cs, UART_MCR, val);
}
#endif
if (cs->hw.elsa.trig)
byteout(cs->hw.elsa.trig, 0x00);
writereg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_MASK, 0x0);
writereg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_MASK + 0x40, 0x0);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_MASK, 0x0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static irqreturn_t
elsa_interrupt_ipac(int intno, void *dev_id)
{
struct IsdnCardState *cs = dev_id;
u_long flags;
u_char ista,val;
int icnt=5;
spin_lock_irqsave(&cs->lock, flags);
if (cs->subtyp == ELSA_QS1000PCI || cs->subtyp == ELSA_QS3000PCI) {
val = bytein(cs->hw.elsa.cfg + 0x4c); /* PCI IRQ */
if (!(val & ELSA_PCI_IRQ_MASK)) {
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_NONE;
}
}
#if ARCOFI_USE
if (cs->hw.elsa.MFlag) {
val = serial_inp(cs, UART_IIR);
if (!(val & UART_IIR_NO_INT)) {
debugl1(cs,"IIR %02x", val);
rs_interrupt_elsa(cs);
}
}
#endif
ista = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ISTA);
Start_IPAC:
if (cs->debug & L1_DEB_IPAC)
debugl1(cs, "IPAC ISTA %02X", ista);
if (ista & 0x0f) {
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_ISTA + 0x40);
if (ista & 0x01)
val |= 0x01;
if (ista & 0x04)
val |= 0x02;
if (ista & 0x08)
val |= 0x04;
if (val)
hscx_int_main(cs, val);
}
if (ista & 0x20) {
val = 0xfe & readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_ISTA + 0x80);
if (val) {
isac_interrupt(cs, val);
}
}
if (ista & 0x10) {
val = 0x01;
isac_interrupt(cs, val);
}
ista = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ISTA);
if ((ista & 0x3f) && icnt) {
icnt--;
goto Start_IPAC;
}
if (!icnt)
printk(KERN_WARNING "ELSA IRQ LOOP\n");
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_MASK, 0xFF);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_MASK, 0xC0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static void
release_io_elsa(struct IsdnCardState *cs)
{
int bytecnt = 8;
del_timer(&cs->hw.elsa.tl);
#if ARCOFI_USE
clear_arcofi(cs);
#endif
if (cs->hw.elsa.ctrl)
byteout(cs->hw.elsa.ctrl, 0); /* LEDs Out */
if (cs->subtyp == ELSA_QS1000PCI) {
byteout(cs->hw.elsa.cfg + 0x4c, 0x01); /* disable IRQ */
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, 0xff);
bytecnt = 2;
release_region(cs->hw.elsa.cfg, 0x80);
}
if (cs->subtyp == ELSA_QS3000PCI) {
byteout(cs->hw.elsa.cfg + 0x4c, 0x03); /* disable ELSA PCI IRQ */
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, 0xff);
release_region(cs->hw.elsa.cfg, 0x80);
}
if (cs->subtyp == ELSA_PCMCIA_IPAC) {
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, 0xff);
}
if ((cs->subtyp == ELSA_PCFPRO) ||
(cs->subtyp == ELSA_QS3000) ||
(cs->subtyp == ELSA_PCF) ||
(cs->subtyp == ELSA_QS3000PCI)) {
bytecnt = 16;
#if ARCOFI_USE
release_modem(cs);
#endif
}
if (cs->hw.elsa.base)
release_region(cs->hw.elsa.base, bytecnt);
}
static void
reset_elsa(struct IsdnCardState *cs)
{
if (cs->hw.elsa.timer) {
/* Wait 1 Timer */
byteout(cs->hw.elsa.timer, 0);
while (TimerRun(cs));
cs->hw.elsa.ctrl_reg |= 0x50;
cs->hw.elsa.ctrl_reg &= ~ELSA_ISDN_RESET; /* Reset On */
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
/* Wait 1 Timer */
byteout(cs->hw.elsa.timer, 0);
while (TimerRun(cs));
cs->hw.elsa.ctrl_reg |= ELSA_ISDN_RESET; /* Reset Off */
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
/* Wait 1 Timer */
byteout(cs->hw.elsa.timer, 0);
while (TimerRun(cs));
if (cs->hw.elsa.trig)
byteout(cs->hw.elsa.trig, 0xff);
}
if ((cs->subtyp == ELSA_QS1000PCI) || (cs->subtyp == ELSA_QS3000PCI) || (cs->subtyp == ELSA_PCMCIA_IPAC)) {
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_POTA2, 0x20);
mdelay(10);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_POTA2, 0x00);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_MASK, 0xc0);
mdelay(10);
if (cs->subtyp != ELSA_PCMCIA_IPAC) {
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ACFG, 0x0);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_AOE, 0x3c);
} else {
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_PCFG, 0x10);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ACFG, 0x4);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_AOE, 0xf8);
}
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, 0xff);
if (cs->subtyp == ELSA_QS1000PCI)
byteout(cs->hw.elsa.cfg + 0x4c, 0x41); /* enable ELSA PCI IRQ */
else if (cs->subtyp == ELSA_QS3000PCI)
byteout(cs->hw.elsa.cfg + 0x4c, 0x43); /* enable ELSA PCI IRQ */
}
}
#if ARCOFI_USE
static void
set_arcofi(struct IsdnCardState *cs, int bc) {
cs->dc.isac.arcofi_bc = bc;
arcofi_fsm(cs, ARCOFI_START, &ARCOFI_COP_5);
interruptible_sleep_on(&cs->dc.isac.arcofi_wait);
}
static int
check_arcofi(struct IsdnCardState *cs)
{
int arcofi_present = 0;
char tmp[40];
char *t;
u_char *p;
if (!cs->dc.isac.mon_tx)
if (!(cs->dc.isac.mon_tx=kmalloc(MAX_MON_FRAME, GFP_ATOMIC))) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "ISAC MON TX out of buffers!");
return(0);
}
cs->dc.isac.arcofi_bc = 0;
arcofi_fsm(cs, ARCOFI_START, &ARCOFI_VERSION);
interruptible_sleep_on(&cs->dc.isac.arcofi_wait);
if (!test_and_clear_bit(FLG_ARCOFI_ERROR, &cs->HW_Flags)) {
debugl1(cs, "Arcofi response received %d bytes", cs->dc.isac.mon_rxp);
p = cs->dc.isac.mon_rx;
t = tmp;
t += sprintf(tmp, "Arcofi data");
QuickHex(t, p, cs->dc.isac.mon_rxp);
debugl1(cs, tmp);
if ((cs->dc.isac.mon_rxp == 2) && (cs->dc.isac.mon_rx[0] == 0xa0)) {
switch(cs->dc.isac.mon_rx[1]) {
case 0x80:
debugl1(cs, "Arcofi 2160 detected");
arcofi_present = 1;
break;
case 0x82:
debugl1(cs, "Arcofi 2165 detected");
arcofi_present = 2;
break;
case 0x84:
debugl1(cs, "Arcofi 2163 detected");
arcofi_present = 3;
break;
default:
debugl1(cs, "unknown Arcofi response");
break;
}
} else
debugl1(cs, "undefined Monitor response");
cs->dc.isac.mon_rxp = 0;
} else if (cs->dc.isac.mon_tx) {
debugl1(cs, "Arcofi not detected");
}
if (arcofi_present) {
if (cs->subtyp==ELSA_QS1000) {
cs->subtyp = ELSA_QS3000;
printk(KERN_INFO
"Elsa: %s detected modem at 0x%lx\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base+8);
release_region(cs->hw.elsa.base, 8);
if (!request_region(cs->hw.elsa.base, 16, "elsa isdn modem")) {
printk(KERN_WARNING
"HiSax: %s config port %lx-%lx already in use\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base + 8,
cs->hw.elsa.base + 16);
}
} else if (cs->subtyp==ELSA_PCC16) {
cs->subtyp = ELSA_PCF;
printk(KERN_INFO
"Elsa: %s detected modem at 0x%lx\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base+8);
release_region(cs->hw.elsa.base, 8);
if (!request_region(cs->hw.elsa.base, 16, "elsa isdn modem")) {
printk(KERN_WARNING
"HiSax: %s config port %lx-%lx already in use\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base + 8,
cs->hw.elsa.base + 16);
}
} else
printk(KERN_INFO
"Elsa: %s detected modem at 0x%lx\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base+8);
arcofi_fsm(cs, ARCOFI_START, &ARCOFI_XOP_0);
interruptible_sleep_on(&cs->dc.isac.arcofi_wait);
return(1);
}
return(0);
}
#endif /* ARCOFI_USE */
static void
elsa_led_handler(struct IsdnCardState *cs)
{
int blink = 0;
if (cs->subtyp == ELSA_PCMCIA || cs->subtyp == ELSA_PCMCIA_IPAC)
return;
del_timer(&cs->hw.elsa.tl);
if (cs->hw.elsa.status & ELSA_ASSIGN)
cs->hw.elsa.ctrl_reg |= ELSA_STAT_LED;
else if (cs->hw.elsa.status & ELSA_BAD_PWR)
cs->hw.elsa.ctrl_reg &= ~ELSA_STAT_LED;
else {
cs->hw.elsa.ctrl_reg ^= ELSA_STAT_LED;
blink = 250;
}
if (cs->hw.elsa.status & 0xf000)
cs->hw.elsa.ctrl_reg |= ELSA_LINE_LED;
else if (cs->hw.elsa.status & 0x0f00) {
cs->hw.elsa.ctrl_reg ^= ELSA_LINE_LED;
blink = 500;
} else
cs->hw.elsa.ctrl_reg &= ~ELSA_LINE_LED;
if ((cs->subtyp == ELSA_QS1000PCI) ||
(cs->subtyp == ELSA_QS3000PCI)) {
u_char led = 0xff;
if (cs->hw.elsa.ctrl_reg & ELSA_LINE_LED)
led ^= ELSA_IPAC_LINE_LED;
if (cs->hw.elsa.ctrl_reg & ELSA_STAT_LED)
led ^= ELSA_IPAC_STAT_LED;
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, led);
} else
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
if (blink) {
init_timer(&cs->hw.elsa.tl);
cs->hw.elsa.tl.expires = jiffies + ((blink * HZ) / 1000);
add_timer(&cs->hw.elsa.tl);
}
}
static int
Elsa_card_msg(struct IsdnCardState *cs, int mt, void *arg)
{
int ret = 0;
u_long flags;
switch (mt) {
case CARD_RESET:
spin_lock_irqsave(&cs->lock, flags);
reset_elsa(cs);
spin_unlock_irqrestore(&cs->lock, flags);
return(0);
case CARD_RELEASE:
release_io_elsa(cs);
return(0);
case CARD_INIT:
spin_lock_irqsave(&cs->lock, flags);
cs->debug |= L1_DEB_IPAC;
reset_elsa(cs);
inithscxisac(cs, 1);
if ((cs->subtyp == ELSA_QS1000) ||
(cs->subtyp == ELSA_QS3000))
{
byteout(cs->hw.elsa.timer, 0);
}
if (cs->hw.elsa.trig)
byteout(cs->hw.elsa.trig, 0xff);
inithscxisac(cs, 2);
spin_unlock_irqrestore(&cs->lock, flags);
return(0);
case CARD_TEST:
if ((cs->subtyp == ELSA_PCMCIA) ||
(cs->subtyp == ELSA_PCMCIA_IPAC) ||
(cs->subtyp == ELSA_QS1000PCI)) {
return(0);
} else if (cs->subtyp == ELSA_QS3000PCI) {
ret = 0;
} else {
spin_lock_irqsave(&cs->lock, flags);
cs->hw.elsa.counter = 0;
cs->hw.elsa.ctrl_reg |= ELSA_ENA_TIMER_INT;
cs->hw.elsa.status |= ELIRQF_TIMER_AKTIV;
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
byteout(cs->hw.elsa.timer, 0);
spin_unlock_irqrestore(&cs->lock, flags);
msleep(110);
spin_lock_irqsave(&cs->lock, flags);
cs->hw.elsa.ctrl_reg &= ~ELSA_ENA_TIMER_INT;
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
cs->hw.elsa.status &= ~ELIRQF_TIMER_AKTIV;
spin_unlock_irqrestore(&cs->lock, flags);
printk(KERN_INFO "Elsa: %d timer tics in 110 msek\n",
cs->hw.elsa.counter);
if ((cs->hw.elsa.counter > 10) &&
(cs->hw.elsa.counter < 16)) {
printk(KERN_INFO "Elsa: timer and irq OK\n");
ret = 0;
} else {
printk(KERN_WARNING
"Elsa: timer tic problem (%d/12) maybe an IRQ(%d) conflict\n",
cs->hw.elsa.counter, cs->irq);
ret = 1;
}
}
#if ARCOFI_USE
if (check_arcofi(cs)) {
init_modem(cs);
}
#endif
elsa_led_handler(cs);
return(ret);
case (MDL_REMOVE | REQUEST):
cs->hw.elsa.status &= 0;
break;
case (MDL_ASSIGN | REQUEST):
cs->hw.elsa.status |= ELSA_ASSIGN;
break;
case MDL_INFO_SETUP:
if ((long) arg)
cs->hw.elsa.status |= 0x0200;
else
cs->hw.elsa.status |= 0x0100;
break;
case MDL_INFO_CONN:
if ((long) arg)
cs->hw.elsa.status |= 0x2000;
else
cs->hw.elsa.status |= 0x1000;
break;
case MDL_INFO_REL:
if ((long) arg) {
cs->hw.elsa.status &= ~0x2000;
cs->hw.elsa.status &= ~0x0200;
} else {
cs->hw.elsa.status &= ~0x1000;
cs->hw.elsa.status &= ~0x0100;
}
break;
#if ARCOFI_USE
case CARD_AUX_IND:
if (cs->hw.elsa.MFlag) {
int len;
u_char *msg;
if (!arg)
return(0);
msg = arg;
len = *msg;
msg++;
modem_write_cmd(cs, msg, len);
}
break;
#endif
}
if (cs->typ == ISDN_CTYPE_ELSA) {
int pwr = bytein(cs->hw.elsa.ale);
if (pwr & 0x08)
cs->hw.elsa.status |= ELSA_BAD_PWR;
else
cs->hw.elsa.status &= ~ELSA_BAD_PWR;
}
elsa_led_handler(cs);
return(ret);
}
static unsigned char
probe_elsa_adr(unsigned int adr, int typ)
{
int i, in1, in2, p16_1 = 0, p16_2 = 0, p8_1 = 0, p8_2 = 0, pc_1 = 0,
pc_2 = 0, pfp_1 = 0, pfp_2 = 0;
/* In case of the elsa pcmcia card, this region is in use,
reserved for us by the card manager. So we do not check it
here, it would fail. */
if (typ != ISDN_CTYPE_ELSA_PCMCIA) {
if (request_region(adr, 8, "elsa card")) {
release_region(adr, 8);
} else {
printk(KERN_WARNING
"Elsa: Probing Port 0x%x: already in use\n", adr);
return (0);
}
}
for (i = 0; i < 16; i++) {
in1 = inb(adr + ELSA_CONFIG); /* 'toggelt' bei */
in2 = inb(adr + ELSA_CONFIG); /* jedem Zugriff */
p16_1 += 0x04 & in1;
p16_2 += 0x04 & in2;
p8_1 += 0x02 & in1;
p8_2 += 0x02 & in2;
pc_1 += 0x01 & in1;
pc_2 += 0x01 & in2;
pfp_1 += 0x40 & in1;
pfp_2 += 0x40 & in2;
}
printk(KERN_INFO "Elsa: Probing IO 0x%x", adr);
if (65 == ++p16_1 * ++p16_2) {
printk(" PCC-16/PCF found\n");
return (ELSA_PCC16);
} else if (1025 == ++pfp_1 * ++pfp_2) {
printk(" PCF-Pro found\n");
return (ELSA_PCFPRO);
} else if (33 == ++p8_1 * ++p8_2) {
printk(" PCC8 found\n");
return (ELSA_PCC8);
} else if (17 == ++pc_1 * ++pc_2) {
printk(" PC found\n");
return (ELSA_PC);
} else {
printk(" failed\n");
return (0);
}
}
static unsigned int
probe_elsa(struct IsdnCardState *cs)
{
int i;
unsigned int CARD_portlist[] =
{0x160, 0x170, 0x260, 0x360, 0};
for (i = 0; CARD_portlist[i]; i++) {
if ((cs->subtyp = probe_elsa_adr(CARD_portlist[i], cs->typ)))
break;
}
return (CARD_portlist[i]);
}
static int __devinit
setup_elsa_isa(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
u_char val;
cs->hw.elsa.base = card->para[0];
printk(KERN_INFO "Elsa: Microlink IO probing\n");
if (cs->hw.elsa.base) {
if (!(cs->subtyp = probe_elsa_adr(cs->hw.elsa.base,
cs->typ))) {
printk(KERN_WARNING
"Elsa: no Elsa Microlink at %#lx\n",
cs->hw.elsa.base);
return (0);
}
} else
cs->hw.elsa.base = probe_elsa(cs);
if (!cs->hw.elsa.base) {
printk(KERN_WARNING
"No Elsa Microlink found\n");
return (0);
}
cs->hw.elsa.cfg = cs->hw.elsa.base + ELSA_CONFIG;
cs->hw.elsa.ctrl = cs->hw.elsa.base + ELSA_CONTROL;
cs->hw.elsa.ale = cs->hw.elsa.base + ELSA_ALE;
cs->hw.elsa.isac = cs->hw.elsa.base + ELSA_ISAC;
cs->hw.elsa.itac = cs->hw.elsa.base + ELSA_ITAC;
cs->hw.elsa.hscx = cs->hw.elsa.base + ELSA_HSCX;
cs->hw.elsa.trig = cs->hw.elsa.base + ELSA_TRIG_IRQ;
cs->hw.elsa.timer = cs->hw.elsa.base + ELSA_START_TIMER;
val = bytein(cs->hw.elsa.cfg);
if (cs->subtyp == ELSA_PC) {
const u_char CARD_IrqTab[8] =
{7, 3, 5, 9, 0, 0, 0, 0};
cs->irq = CARD_IrqTab[(val & ELSA_IRQ_IDX_PC) >> 2];
} else if (cs->subtyp == ELSA_PCC8) {
const u_char CARD_IrqTab[8] =
{7, 3, 5, 9, 0, 0, 0, 0};
cs->irq = CARD_IrqTab[(val & ELSA_IRQ_IDX_PCC8) >> 4];
} else {
const u_char CARD_IrqTab[8] =
{15, 10, 15, 3, 11, 5, 11, 9};
cs->irq = CARD_IrqTab[(val & ELSA_IRQ_IDX) >> 3];
}
val = bytein(cs->hw.elsa.ale) & ELSA_HW_RELEASE;
if (val < 3)
val |= 8;
val += 'A' - 3;
if (val == 'B' || val == 'C')
val ^= 1;
if ((cs->subtyp == ELSA_PCFPRO) && (val == 'G'))
val = 'C';
printk(KERN_INFO
"Elsa: %s found at %#lx Rev.:%c IRQ %d\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base,
val, cs->irq);
val = bytein(cs->hw.elsa.ale) & ELSA_S0_POWER_BAD;
if (val) {
printk(KERN_WARNING
"Elsa: Microlink S0 bus power bad\n");
cs->hw.elsa.status |= ELSA_BAD_PWR;
}
return (1);
}
#ifdef __ISAPNP__
static struct isapnp_device_id elsa_ids[] __devinitdata = {
{ ISAPNP_VENDOR('E', 'L', 'S'), ISAPNP_FUNCTION(0x0133),
ISAPNP_VENDOR('E', 'L', 'S'), ISAPNP_FUNCTION(0x0133),
(unsigned long) "Elsa QS1000" },
{ ISAPNP_VENDOR('E', 'L', 'S'), ISAPNP_FUNCTION(0x0134),
ISAPNP_VENDOR('E', 'L', 'S'), ISAPNP_FUNCTION(0x0134),
(unsigned long) "Elsa QS3000" },
{ 0, }
};
static struct isapnp_device_id *ipid __devinitdata = &elsa_ids[0];
static struct pnp_card *pnp_c __devinitdata = NULL;
#endif /* __ISAPNP__ */
static int __devinit
setup_elsa_isapnp(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
#ifdef __ISAPNP__
if (!card->para[1] && isapnp_present()) {
struct pnp_dev *pnp_d;
while(ipid->card_vendor) {
if ((pnp_c = pnp_find_card(ipid->card_vendor,
ipid->card_device, pnp_c))) {
pnp_d = NULL;
if ((pnp_d = pnp_find_dev(pnp_c,
ipid->vendor, ipid->function, pnp_d))) {
int err;
printk(KERN_INFO "HiSax: %s detected\n",
(char *)ipid->driver_data);
pnp_disable_dev(pnp_d);
err = pnp_activate_dev(pnp_d);
if (err<0) {
printk(KERN_WARNING "%s: pnp_activate_dev ret(%d)\n",
__func__, err);
return(0);
}
card->para[1] = pnp_port_start(pnp_d, 0);
card->para[0] = pnp_irq(pnp_d, 0);
if (!card->para[0] || !card->para[1]) {
printk(KERN_ERR "Elsa PnP:some resources are missing %ld/%lx\n",
card->para[0], card->para[1]);
pnp_disable_dev(pnp_d);
return(0);
}
if (ipid->function == ISAPNP_FUNCTION(0x133))
cs->subtyp = ELSA_QS1000;
else
cs->subtyp = ELSA_QS3000;
break;
} else {
printk(KERN_ERR "Elsa PnP: PnP error card found, no device\n");
return(0);
}
}
ipid++;
pnp_c=NULL;
}
if (!ipid->card_vendor) {
printk(KERN_INFO "Elsa PnP: no ISAPnP card found\n");
return(0);
}
}
#endif /* __ISAPNP__ */
if (card->para[1] && card->para[0]) {
cs->hw.elsa.base = card->para[1];
cs->irq = card->para[0];
if (!cs->subtyp)
cs->subtyp = ELSA_QS1000;
} else {
printk(KERN_ERR "Elsa PnP: no parameter\n");
}
cs->hw.elsa.cfg = cs->hw.elsa.base + ELSA_CONFIG;
cs->hw.elsa.ale = cs->hw.elsa.base + ELSA_ALE;
cs->hw.elsa.isac = cs->hw.elsa.base + ELSA_ISAC;
cs->hw.elsa.hscx = cs->hw.elsa.base + ELSA_HSCX;
cs->hw.elsa.trig = cs->hw.elsa.base + ELSA_TRIG_IRQ;
cs->hw.elsa.timer = cs->hw.elsa.base + ELSA_START_TIMER;
cs->hw.elsa.ctrl = cs->hw.elsa.base + ELSA_CONTROL;
printk(KERN_INFO
"Elsa: %s defined at %#lx IRQ %d\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base,
cs->irq);
return (1);
}
static void __devinit
setup_elsa_pcmcia(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
u_char val;
cs->hw.elsa.base = card->para[1];
cs->irq = card->para[0];
val = readreg(cs->hw.elsa.base + 0, cs->hw.elsa.base + 2, IPAC_ID);
if ((val == 1) || (val == 2)) { /* IPAC version 1.1/1.2 */
cs->subtyp = ELSA_PCMCIA_IPAC;
cs->hw.elsa.ale = cs->hw.elsa.base + 0;
cs->hw.elsa.isac = cs->hw.elsa.base + 2;
cs->hw.elsa.hscx = cs->hw.elsa.base + 2;
test_and_set_bit(HW_IPAC, &cs->HW_Flags);
} else {
cs->subtyp = ELSA_PCMCIA;
cs->hw.elsa.ale = cs->hw.elsa.base + ELSA_ALE_PCM;
cs->hw.elsa.isac = cs->hw.elsa.base + ELSA_ISAC_PCM;
cs->hw.elsa.hscx = cs->hw.elsa.base + ELSA_HSCX;
}
cs->hw.elsa.timer = 0;
cs->hw.elsa.trig = 0;
cs->hw.elsa.ctrl = 0;
cs->irq_flags |= IRQF_SHARED;
printk(KERN_INFO
"Elsa: %s defined at %#lx IRQ %d\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base,
cs->irq);
}
#ifdef CONFIG_PCI
static struct pci_dev *dev_qs1000 __devinitdata = NULL;
static struct pci_dev *dev_qs3000 __devinitdata = NULL;
static int __devinit
setup_elsa_pci(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
cs->subtyp = 0;
if ((dev_qs1000 = hisax_find_pci_device(PCI_VENDOR_ID_ELSA,
PCI_DEVICE_ID_ELSA_MICROLINK, dev_qs1000))) {
if (pci_enable_device(dev_qs1000))
return(0);
cs->subtyp = ELSA_QS1000PCI;
cs->irq = dev_qs1000->irq;
cs->hw.elsa.cfg = pci_resource_start(dev_qs1000, 1);
cs->hw.elsa.base = pci_resource_start(dev_qs1000, 3);
} else if ((dev_qs3000 = hisax_find_pci_device(PCI_VENDOR_ID_ELSA,
PCI_DEVICE_ID_ELSA_QS3000, dev_qs3000))) {
if (pci_enable_device(dev_qs3000))
return(0);
cs->subtyp = ELSA_QS3000PCI;
cs->irq = dev_qs3000->irq;
cs->hw.elsa.cfg = pci_resource_start(dev_qs3000, 1);
cs->hw.elsa.base = pci_resource_start(dev_qs3000, 3);
} else {
printk(KERN_WARNING "Elsa: No PCI card found\n");
return(0);
}
if (!cs->irq) {
printk(KERN_WARNING "Elsa: No IRQ for PCI card found\n");
return(0);
}
if (!(cs->hw.elsa.base && cs->hw.elsa.cfg)) {
printk(KERN_WARNING "Elsa: No IO-Adr for PCI card found\n");
return(0);
}
if ((cs->hw.elsa.cfg & 0xff) || (cs->hw.elsa.base & 0xf)) {
printk(KERN_WARNING "Elsa: You may have a wrong PCI bios\n");
printk(KERN_WARNING "Elsa: If your system hangs now, read\n");
printk(KERN_WARNING "Elsa: Documentation/isdn/README.HiSax\n");
}
cs->hw.elsa.ale = cs->hw.elsa.base;
cs->hw.elsa.isac = cs->hw.elsa.base +1;
cs->hw.elsa.hscx = cs->hw.elsa.base +1;
test_and_set_bit(HW_IPAC, &cs->HW_Flags);
cs->hw.elsa.timer = 0;
cs->hw.elsa.trig = 0;
cs->irq_flags |= IRQF_SHARED;
printk(KERN_INFO
"Elsa: %s defined at %#lx/0x%x IRQ %d\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base,
cs->hw.elsa.cfg,
cs->irq);
return (1);
}
#else
static int __devinit
setup_elsa_pci(struct IsdnCard *card)
{
return (1);
}
#endif /* CONFIG_PCI */
static int __devinit
setup_elsa_common(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
u_char val;
int bytecnt;
switch (cs->subtyp) {
case ELSA_PC:
case ELSA_PCC8:
case ELSA_PCC16:
case ELSA_QS1000:
case ELSA_PCMCIA:
case ELSA_PCMCIA_IPAC:
bytecnt = 8;
break;
case ELSA_PCFPRO:
case ELSA_PCF:
case ELSA_QS3000:
case ELSA_QS3000PCI:
bytecnt = 16;
break;
case ELSA_QS1000PCI:
bytecnt = 2;
break;
default:
printk(KERN_WARNING
"Unknown ELSA subtype %d\n", cs->subtyp);
return (0);
}
/* In case of the elsa pcmcia card, this region is in use,
reserved for us by the card manager. So we do not check it
here, it would fail. */
if (cs->typ != ISDN_CTYPE_ELSA_PCMCIA && !request_region(cs->hw.elsa.base, bytecnt, "elsa isdn")) {
printk(KERN_WARNING
"HiSax: ELSA config port %#lx-%#lx already in use\n",
cs->hw.elsa.base,
cs->hw.elsa.base + bytecnt);
return (0);
}
if ((cs->subtyp == ELSA_QS1000PCI) || (cs->subtyp == ELSA_QS3000PCI)) {
if (!request_region(cs->hw.elsa.cfg, 0x80, "elsa isdn pci")) {
printk(KERN_WARNING
"HiSax: ELSA pci port %x-%x already in use\n",
cs->hw.elsa.cfg,
cs->hw.elsa.cfg + 0x80);
release_region(cs->hw.elsa.base, bytecnt);
return (0);
}
}
#if ARCOFI_USE
init_arcofi(cs);
#endif
setup_isac(cs);
cs->hw.elsa.tl.function = (void *) elsa_led_handler;
cs->hw.elsa.tl.data = (long) cs;
init_timer(&cs->hw.elsa.tl);
/* Teste Timer */
if (cs->hw.elsa.timer) {
byteout(cs->hw.elsa.trig, 0xff);
byteout(cs->hw.elsa.timer, 0);
if (!TimerRun(cs)) {
byteout(cs->hw.elsa.timer, 0); /* 2. Versuch */
if (!TimerRun(cs)) {
printk(KERN_WARNING
"Elsa: timer do not start\n");
release_io_elsa(cs);
return (0);
}
}
HZDELAY((HZ/100) + 1); /* wait >=10 ms */
if (TimerRun(cs)) {
printk(KERN_WARNING "Elsa: timer do not run down\n");
release_io_elsa(cs);
return (0);
}
printk(KERN_INFO "Elsa: timer OK; resetting card\n");
}
cs->BC_Read_Reg = &ReadHSCX;
cs->BC_Write_Reg = &WriteHSCX;
cs->BC_Send_Data = &hscx_fill_fifo;
cs->cardmsg = &Elsa_card_msg;
if ((cs->subtyp == ELSA_QS1000PCI) || (cs->subtyp == ELSA_QS3000PCI) || (cs->subtyp == ELSA_PCMCIA_IPAC)) {
cs->readisac = &ReadISAC_IPAC;
cs->writeisac = &WriteISAC_IPAC;
cs->readisacfifo = &ReadISACfifo_IPAC;
cs->writeisacfifo = &WriteISACfifo_IPAC;
cs->irq_func = &elsa_interrupt_ipac;
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ID);
printk(KERN_INFO "Elsa: IPAC version %x\n", val);
} else {
cs->readisac = &ReadISAC;
cs->writeisac = &WriteISAC;
cs->readisacfifo = &ReadISACfifo;
cs->writeisacfifo = &WriteISACfifo;
cs->irq_func = &elsa_interrupt;
ISACVersion(cs, "Elsa:");
if (HscxVersion(cs, "Elsa:")) {
printk(KERN_WARNING
"Elsa: wrong HSCX versions check IO address\n");
release_io_elsa(cs);
return (0);
}
}
if (cs->subtyp == ELSA_PC) {
val = readitac(cs, ITAC_SYS);
printk(KERN_INFO "Elsa: ITAC version %s\n", ITACVer[val & 7]);
writeitac(cs, ITAC_ISEN, 0);
writeitac(cs, ITAC_RFIE, 0);
writeitac(cs, ITAC_XFIE, 0);
writeitac(cs, ITAC_SCIE, 0);
writeitac(cs, ITAC_STIE, 0);
}
return (1);
}
int __devinit
setup_elsa(struct IsdnCard *card)
{
int rc;
struct IsdnCardState *cs = card->cs;
char tmp[64];
strcpy(tmp, Elsa_revision);
printk(KERN_INFO "HiSax: Elsa driver Rev. %s\n", HiSax_getrev(tmp));
cs->hw.elsa.ctrl_reg = 0;
cs->hw.elsa.status = 0;
cs->hw.elsa.MFlag = 0;
cs->subtyp = 0;
if (cs->typ == ISDN_CTYPE_ELSA) {
rc = setup_elsa_isa(card);
if (!rc)
return (0);
} else if (cs->typ == ISDN_CTYPE_ELSA_PNP) {
rc = setup_elsa_isapnp(card);
if (!rc)
return (0);
} else if (cs->typ == ISDN_CTYPE_ELSA_PCMCIA)
setup_elsa_pcmcia(card);
else if (cs->typ == ISDN_CTYPE_ELSA_PCI) {
rc = setup_elsa_pci(card);
if (!rc)
return (0);
} else
return (0);
return setup_elsa_common(card);
}
| gpl-2.0 |
utilite-computer/linux-kernel-3.0 | drivers/isdn/hisax/elsa.c | 4229 | 34367 | /* $Id: elsa.c,v 2.32.2.4 2004/01/24 20:47:21 keil Exp $
*
* low level stuff for Elsa isdn cards
*
* Author Karsten Keil
* Copyright by Karsten Keil <keil@isdn4linux.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* For changes and modifications please read
* Documentation/isdn/HiSax.cert
*
* Thanks to Elsa GmbH for documents and information
*
* Klaus Lichtenwalder (Klaus.Lichtenwalder@WebForum.DE)
* for ELSA PCMCIA support
*
*/
#include <linux/init.h>
#include <linux/slab.h>
#include "hisax.h"
#include "arcofi.h"
#include "isac.h"
#include "ipac.h"
#include "hscx.h"
#include "isdnl1.h"
#include <linux/pci.h>
#include <linux/isapnp.h>
#include <linux/serial.h>
#include <linux/serial_reg.h>
static const char *Elsa_revision = "$Revision: 2.32.2.4 $";
static const char *Elsa_Types[] =
{"None", "PC", "PCC-8", "PCC-16", "PCF", "PCF-Pro",
"PCMCIA", "QS 1000", "QS 3000", "Microlink PCI", "QS 3000 PCI",
"PCMCIA-IPAC" };
static const char *ITACVer[] =
{"?0?", "?1?", "?2?", "?3?", "?4?", "V2.2",
"B1", "A1"};
#define byteout(addr,val) outb(val,addr)
#define bytein(addr) inb(addr)
#define ELSA_ISAC 0
#define ELSA_ISAC_PCM 1
#define ELSA_ITAC 1
#define ELSA_HSCX 2
#define ELSA_ALE 3
#define ELSA_ALE_PCM 4
#define ELSA_CONTROL 4
#define ELSA_CONFIG 5
#define ELSA_START_TIMER 6
#define ELSA_TRIG_IRQ 7
#define ELSA_PC 1
#define ELSA_PCC8 2
#define ELSA_PCC16 3
#define ELSA_PCF 4
#define ELSA_PCFPRO 5
#define ELSA_PCMCIA 6
#define ELSA_QS1000 7
#define ELSA_QS3000 8
#define ELSA_QS1000PCI 9
#define ELSA_QS3000PCI 10
#define ELSA_PCMCIA_IPAC 11
/* PCI stuff */
#define ELSA_PCI_IRQ_MASK 0x04
/* ITAC Registeradressen (only Microlink PC) */
#define ITAC_SYS 0x34
#define ITAC_ISEN 0x48
#define ITAC_RFIE 0x4A
#define ITAC_XFIE 0x4C
#define ITAC_SCIE 0x4E
#define ITAC_STIE 0x46
/*** ***
*** Makros als Befehle fuer die Kartenregister ***
*** (mehrere Befehle werden durch Bit-Oderung kombiniert) ***
*** ***/
/* Config-Register (Read) */
#define ELIRQF_TIMER_RUN 0x02 /* Bit 1 des Config-Reg */
#define ELIRQF_TIMER_RUN_PCC8 0x01 /* Bit 0 des Config-Reg bei PCC */
#define ELSA_IRQ_IDX 0x38 /* Bit 3,4,5 des Config-Reg */
#define ELSA_IRQ_IDX_PCC8 0x30 /* Bit 4,5 des Config-Reg */
#define ELSA_IRQ_IDX_PC 0x0c /* Bit 2,3 des Config-Reg */
/* Control-Register (Write) */
#define ELSA_LINE_LED 0x02 /* Bit 1 Gelbe LED */
#define ELSA_STAT_LED 0x08 /* Bit 3 Gruene LED */
#define ELSA_ISDN_RESET 0x20 /* Bit 5 Reset-Leitung */
#define ELSA_ENA_TIMER_INT 0x80 /* Bit 7 Freigabe Timer Interrupt */
/* ALE-Register (Read) */
#define ELSA_HW_RELEASE 0x07 /* Bit 0-2 Hardwarerkennung */
#define ELSA_S0_POWER_BAD 0x08 /* Bit 3 S0-Bus Spannung fehlt */
/* Status Flags */
#define ELIRQF_TIMER_AKTIV 1
#define ELSA_BAD_PWR 2
#define ELSA_ASSIGN 4
#define RS_ISR_PASS_LIMIT 256
#define FLG_MODEM_ACTIVE 1
/* IPAC AUX */
#define ELSA_IPAC_LINE_LED 0x40 /* Bit 6 Gelbe LED */
#define ELSA_IPAC_STAT_LED 0x80 /* Bit 7 Gruene LED */
#if ARCOFI_USE
static struct arcofi_msg ARCOFI_XOP_F =
{NULL,0,2,{0xa1,0x3f,0,0,0,0,0,0,0,0}}; /* Normal OP */
static struct arcofi_msg ARCOFI_XOP_1 =
{&ARCOFI_XOP_F,0,2,{0xa1,0x31,0,0,0,0,0,0,0,0}}; /* PWR UP */
static struct arcofi_msg ARCOFI_SOP_F =
{&ARCOFI_XOP_1,0,10,{0xa1,0x1f,0x00,0x50,0x10,0x00,0x00,0x80,0x02,0x12}};
static struct arcofi_msg ARCOFI_COP_9 =
{&ARCOFI_SOP_F,0,10,{0xa1,0x29,0x80,0xcb,0xe9,0x88,0x00,0xc8,0xd8,0x80}}; /* RX */
static struct arcofi_msg ARCOFI_COP_8 =
{&ARCOFI_COP_9,0,10,{0xa1,0x28,0x49,0x31,0x8,0x13,0x6e,0x88,0x2a,0x61}}; /* TX */
static struct arcofi_msg ARCOFI_COP_7 =
{&ARCOFI_COP_8,0,4,{0xa1,0x27,0x80,0x80,0,0,0,0,0,0}}; /* GZ */
static struct arcofi_msg ARCOFI_COP_6 =
{&ARCOFI_COP_7,0,6,{0xa1,0x26,0,0,0x82,0x7c,0,0,0,0}}; /* GRL GRH */
static struct arcofi_msg ARCOFI_COP_5 =
{&ARCOFI_COP_6,0,4,{0xa1,0x25,0xbb,0x4a,0,0,0,0,0,0}}; /* GTX */
static struct arcofi_msg ARCOFI_VERSION =
{NULL,1,2,{0xa0,0,0,0,0,0,0,0,0,0}};
static struct arcofi_msg ARCOFI_XOP_0 =
{NULL,0,2,{0xa1,0x30,0,0,0,0,0,0,0,0}}; /* PWR Down */
static void set_arcofi(struct IsdnCardState *cs, int bc);
#include "elsa_ser.c"
#endif /* ARCOFI_USE */
static inline u_char
readreg(unsigned int ale, unsigned int adr, u_char off)
{
register u_char ret;
byteout(ale, off);
ret = bytein(adr);
return (ret);
}
static inline void
readfifo(unsigned int ale, unsigned int adr, u_char off, u_char * data, int size)
{
byteout(ale, off);
insb(adr, data, size);
}
static inline void
writereg(unsigned int ale, unsigned int adr, u_char off, u_char data)
{
byteout(ale, off);
byteout(adr, data);
}
static inline void
writefifo(unsigned int ale, unsigned int adr, u_char off, u_char * data, int size)
{
byteout(ale, off);
outsb(adr, data, size);
}
/* Interface functions */
static u_char
ReadISAC(struct IsdnCardState *cs, u_char offset)
{
return (readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, offset));
}
static void
WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value)
{
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, offset, value);
}
static void
ReadISACfifo(struct IsdnCardState *cs, u_char * data, int size)
{
readfifo(cs->hw.elsa.ale, cs->hw.elsa.isac, 0, data, size);
}
static void
WriteISACfifo(struct IsdnCardState *cs, u_char * data, int size)
{
writefifo(cs->hw.elsa.ale, cs->hw.elsa.isac, 0, data, size);
}
static u_char
ReadISAC_IPAC(struct IsdnCardState *cs, u_char offset)
{
return (readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, offset+0x80));
}
static void
WriteISAC_IPAC(struct IsdnCardState *cs, u_char offset, u_char value)
{
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, offset|0x80, value);
}
static void
ReadISACfifo_IPAC(struct IsdnCardState *cs, u_char * data, int size)
{
readfifo(cs->hw.elsa.ale, cs->hw.elsa.isac, 0x80, data, size);
}
static void
WriteISACfifo_IPAC(struct IsdnCardState *cs, u_char * data, int size)
{
writefifo(cs->hw.elsa.ale, cs->hw.elsa.isac, 0x80, data, size);
}
static u_char
ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset)
{
return (readreg(cs->hw.elsa.ale,
cs->hw.elsa.hscx, offset + (hscx ? 0x40 : 0)));
}
static void
WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value)
{
writereg(cs->hw.elsa.ale,
cs->hw.elsa.hscx, offset + (hscx ? 0x40 : 0), value);
}
static inline u_char
readitac(struct IsdnCardState *cs, u_char off)
{
register u_char ret;
byteout(cs->hw.elsa.ale, off);
ret = bytein(cs->hw.elsa.itac);
return (ret);
}
static inline void
writeitac(struct IsdnCardState *cs, u_char off, u_char data)
{
byteout(cs->hw.elsa.ale, off);
byteout(cs->hw.elsa.itac, data);
}
static inline int
TimerRun(struct IsdnCardState *cs)
{
register u_char v;
v = bytein(cs->hw.elsa.cfg);
if ((cs->subtyp == ELSA_QS1000) || (cs->subtyp == ELSA_QS3000))
return (0 == (v & ELIRQF_TIMER_RUN));
else if (cs->subtyp == ELSA_PCC8)
return (v & ELIRQF_TIMER_RUN_PCC8);
return (v & ELIRQF_TIMER_RUN);
}
/*
* fast interrupt HSCX stuff goes here
*/
#define READHSCX(cs, nr, reg) readreg(cs->hw.elsa.ale, \
cs->hw.elsa.hscx, reg + (nr ? 0x40 : 0))
#define WRITEHSCX(cs, nr, reg, data) writereg(cs->hw.elsa.ale, \
cs->hw.elsa.hscx, reg + (nr ? 0x40 : 0), data)
#define READHSCXFIFO(cs, nr, ptr, cnt) readfifo(cs->hw.elsa.ale, \
cs->hw.elsa.hscx, (nr ? 0x40 : 0), ptr, cnt)
#define WRITEHSCXFIFO(cs, nr, ptr, cnt) writefifo(cs->hw.elsa.ale, \
cs->hw.elsa.hscx, (nr ? 0x40 : 0), ptr, cnt)
#include "hscx_irq.c"
static irqreturn_t
elsa_interrupt(int intno, void *dev_id)
{
struct IsdnCardState *cs = dev_id;
u_long flags;
u_char val;
int icnt=5;
if ((cs->typ == ISDN_CTYPE_ELSA_PCMCIA) && (*cs->busy_flag == 1)) {
/* The card tends to generate interrupts while being removed
causing us to just crash the kernel. bad. */
printk(KERN_WARNING "Elsa: card not available!\n");
return IRQ_NONE;
}
spin_lock_irqsave(&cs->lock, flags);
#if ARCOFI_USE
if (cs->hw.elsa.MFlag) {
val = serial_inp(cs, UART_IIR);
if (!(val & UART_IIR_NO_INT)) {
debugl1(cs,"IIR %02x", val);
rs_interrupt_elsa(cs);
}
}
#endif
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_ISTA + 0x40);
Start_HSCX:
if (val) {
hscx_int_main(cs, val);
}
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_ISTA);
Start_ISAC:
if (val) {
isac_interrupt(cs, val);
}
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_ISTA + 0x40);
if (val && icnt) {
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "HSCX IntStat after IntRoutine");
icnt--;
goto Start_HSCX;
}
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_ISTA);
if (val && icnt) {
if (cs->debug & L1_DEB_ISAC)
debugl1(cs, "ISAC IntStat after IntRoutine");
icnt--;
goto Start_ISAC;
}
if (!icnt)
printk(KERN_WARNING"ELSA IRQ LOOP\n");
writereg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_MASK, 0xFF);
writereg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_MASK + 0x40, 0xFF);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_MASK, 0xFF);
if (cs->hw.elsa.status & ELIRQF_TIMER_AKTIV) {
if (!TimerRun(cs)) {
/* Timer Restart */
byteout(cs->hw.elsa.timer, 0);
cs->hw.elsa.counter++;
}
}
#if ARCOFI_USE
if (cs->hw.elsa.MFlag) {
val = serial_inp(cs, UART_MCR);
val ^= 0x8;
serial_outp(cs, UART_MCR, val);
val = serial_inp(cs, UART_MCR);
val ^= 0x8;
serial_outp(cs, UART_MCR, val);
}
#endif
if (cs->hw.elsa.trig)
byteout(cs->hw.elsa.trig, 0x00);
writereg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_MASK, 0x0);
writereg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_MASK + 0x40, 0x0);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_MASK, 0x0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static irqreturn_t
elsa_interrupt_ipac(int intno, void *dev_id)
{
struct IsdnCardState *cs = dev_id;
u_long flags;
u_char ista,val;
int icnt=5;
spin_lock_irqsave(&cs->lock, flags);
if (cs->subtyp == ELSA_QS1000PCI || cs->subtyp == ELSA_QS3000PCI) {
val = bytein(cs->hw.elsa.cfg + 0x4c); /* PCI IRQ */
if (!(val & ELSA_PCI_IRQ_MASK)) {
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_NONE;
}
}
#if ARCOFI_USE
if (cs->hw.elsa.MFlag) {
val = serial_inp(cs, UART_IIR);
if (!(val & UART_IIR_NO_INT)) {
debugl1(cs,"IIR %02x", val);
rs_interrupt_elsa(cs);
}
}
#endif
ista = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ISTA);
Start_IPAC:
if (cs->debug & L1_DEB_IPAC)
debugl1(cs, "IPAC ISTA %02X", ista);
if (ista & 0x0f) {
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.hscx, HSCX_ISTA + 0x40);
if (ista & 0x01)
val |= 0x01;
if (ista & 0x04)
val |= 0x02;
if (ista & 0x08)
val |= 0x04;
if (val)
hscx_int_main(cs, val);
}
if (ista & 0x20) {
val = 0xfe & readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, ISAC_ISTA + 0x80);
if (val) {
isac_interrupt(cs, val);
}
}
if (ista & 0x10) {
val = 0x01;
isac_interrupt(cs, val);
}
ista = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ISTA);
if ((ista & 0x3f) && icnt) {
icnt--;
goto Start_IPAC;
}
if (!icnt)
printk(KERN_WARNING "ELSA IRQ LOOP\n");
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_MASK, 0xFF);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_MASK, 0xC0);
spin_unlock_irqrestore(&cs->lock, flags);
return IRQ_HANDLED;
}
static void
release_io_elsa(struct IsdnCardState *cs)
{
int bytecnt = 8;
del_timer(&cs->hw.elsa.tl);
#if ARCOFI_USE
clear_arcofi(cs);
#endif
if (cs->hw.elsa.ctrl)
byteout(cs->hw.elsa.ctrl, 0); /* LEDs Out */
if (cs->subtyp == ELSA_QS1000PCI) {
byteout(cs->hw.elsa.cfg + 0x4c, 0x01); /* disable IRQ */
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, 0xff);
bytecnt = 2;
release_region(cs->hw.elsa.cfg, 0x80);
}
if (cs->subtyp == ELSA_QS3000PCI) {
byteout(cs->hw.elsa.cfg + 0x4c, 0x03); /* disable ELSA PCI IRQ */
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, 0xff);
release_region(cs->hw.elsa.cfg, 0x80);
}
if (cs->subtyp == ELSA_PCMCIA_IPAC) {
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, 0xff);
}
if ((cs->subtyp == ELSA_PCFPRO) ||
(cs->subtyp == ELSA_QS3000) ||
(cs->subtyp == ELSA_PCF) ||
(cs->subtyp == ELSA_QS3000PCI)) {
bytecnt = 16;
#if ARCOFI_USE
release_modem(cs);
#endif
}
if (cs->hw.elsa.base)
release_region(cs->hw.elsa.base, bytecnt);
}
static void
reset_elsa(struct IsdnCardState *cs)
{
if (cs->hw.elsa.timer) {
/* Wait 1 Timer */
byteout(cs->hw.elsa.timer, 0);
while (TimerRun(cs));
cs->hw.elsa.ctrl_reg |= 0x50;
cs->hw.elsa.ctrl_reg &= ~ELSA_ISDN_RESET; /* Reset On */
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
/* Wait 1 Timer */
byteout(cs->hw.elsa.timer, 0);
while (TimerRun(cs));
cs->hw.elsa.ctrl_reg |= ELSA_ISDN_RESET; /* Reset Off */
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
/* Wait 1 Timer */
byteout(cs->hw.elsa.timer, 0);
while (TimerRun(cs));
if (cs->hw.elsa.trig)
byteout(cs->hw.elsa.trig, 0xff);
}
if ((cs->subtyp == ELSA_QS1000PCI) || (cs->subtyp == ELSA_QS3000PCI) || (cs->subtyp == ELSA_PCMCIA_IPAC)) {
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_POTA2, 0x20);
mdelay(10);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_POTA2, 0x00);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_MASK, 0xc0);
mdelay(10);
if (cs->subtyp != ELSA_PCMCIA_IPAC) {
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ACFG, 0x0);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_AOE, 0x3c);
} else {
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_PCFG, 0x10);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ACFG, 0x4);
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_AOE, 0xf8);
}
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, 0xff);
if (cs->subtyp == ELSA_QS1000PCI)
byteout(cs->hw.elsa.cfg + 0x4c, 0x41); /* enable ELSA PCI IRQ */
else if (cs->subtyp == ELSA_QS3000PCI)
byteout(cs->hw.elsa.cfg + 0x4c, 0x43); /* enable ELSA PCI IRQ */
}
}
#if ARCOFI_USE
static void
set_arcofi(struct IsdnCardState *cs, int bc) {
cs->dc.isac.arcofi_bc = bc;
arcofi_fsm(cs, ARCOFI_START, &ARCOFI_COP_5);
interruptible_sleep_on(&cs->dc.isac.arcofi_wait);
}
static int
check_arcofi(struct IsdnCardState *cs)
{
int arcofi_present = 0;
char tmp[40];
char *t;
u_char *p;
if (!cs->dc.isac.mon_tx)
if (!(cs->dc.isac.mon_tx=kmalloc(MAX_MON_FRAME, GFP_ATOMIC))) {
if (cs->debug & L1_DEB_WARN)
debugl1(cs, "ISAC MON TX out of buffers!");
return(0);
}
cs->dc.isac.arcofi_bc = 0;
arcofi_fsm(cs, ARCOFI_START, &ARCOFI_VERSION);
interruptible_sleep_on(&cs->dc.isac.arcofi_wait);
if (!test_and_clear_bit(FLG_ARCOFI_ERROR, &cs->HW_Flags)) {
debugl1(cs, "Arcofi response received %d bytes", cs->dc.isac.mon_rxp);
p = cs->dc.isac.mon_rx;
t = tmp;
t += sprintf(tmp, "Arcofi data");
QuickHex(t, p, cs->dc.isac.mon_rxp);
debugl1(cs, tmp);
if ((cs->dc.isac.mon_rxp == 2) && (cs->dc.isac.mon_rx[0] == 0xa0)) {
switch(cs->dc.isac.mon_rx[1]) {
case 0x80:
debugl1(cs, "Arcofi 2160 detected");
arcofi_present = 1;
break;
case 0x82:
debugl1(cs, "Arcofi 2165 detected");
arcofi_present = 2;
break;
case 0x84:
debugl1(cs, "Arcofi 2163 detected");
arcofi_present = 3;
break;
default:
debugl1(cs, "unknown Arcofi response");
break;
}
} else
debugl1(cs, "undefined Monitor response");
cs->dc.isac.mon_rxp = 0;
} else if (cs->dc.isac.mon_tx) {
debugl1(cs, "Arcofi not detected");
}
if (arcofi_present) {
if (cs->subtyp==ELSA_QS1000) {
cs->subtyp = ELSA_QS3000;
printk(KERN_INFO
"Elsa: %s detected modem at 0x%lx\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base+8);
release_region(cs->hw.elsa.base, 8);
if (!request_region(cs->hw.elsa.base, 16, "elsa isdn modem")) {
printk(KERN_WARNING
"HiSax: %s config port %lx-%lx already in use\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base + 8,
cs->hw.elsa.base + 16);
}
} else if (cs->subtyp==ELSA_PCC16) {
cs->subtyp = ELSA_PCF;
printk(KERN_INFO
"Elsa: %s detected modem at 0x%lx\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base+8);
release_region(cs->hw.elsa.base, 8);
if (!request_region(cs->hw.elsa.base, 16, "elsa isdn modem")) {
printk(KERN_WARNING
"HiSax: %s config port %lx-%lx already in use\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base + 8,
cs->hw.elsa.base + 16);
}
} else
printk(KERN_INFO
"Elsa: %s detected modem at 0x%lx\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base+8);
arcofi_fsm(cs, ARCOFI_START, &ARCOFI_XOP_0);
interruptible_sleep_on(&cs->dc.isac.arcofi_wait);
return(1);
}
return(0);
}
#endif /* ARCOFI_USE */
static void
elsa_led_handler(struct IsdnCardState *cs)
{
int blink = 0;
if (cs->subtyp == ELSA_PCMCIA || cs->subtyp == ELSA_PCMCIA_IPAC)
return;
del_timer(&cs->hw.elsa.tl);
if (cs->hw.elsa.status & ELSA_ASSIGN)
cs->hw.elsa.ctrl_reg |= ELSA_STAT_LED;
else if (cs->hw.elsa.status & ELSA_BAD_PWR)
cs->hw.elsa.ctrl_reg &= ~ELSA_STAT_LED;
else {
cs->hw.elsa.ctrl_reg ^= ELSA_STAT_LED;
blink = 250;
}
if (cs->hw.elsa.status & 0xf000)
cs->hw.elsa.ctrl_reg |= ELSA_LINE_LED;
else if (cs->hw.elsa.status & 0x0f00) {
cs->hw.elsa.ctrl_reg ^= ELSA_LINE_LED;
blink = 500;
} else
cs->hw.elsa.ctrl_reg &= ~ELSA_LINE_LED;
if ((cs->subtyp == ELSA_QS1000PCI) ||
(cs->subtyp == ELSA_QS3000PCI)) {
u_char led = 0xff;
if (cs->hw.elsa.ctrl_reg & ELSA_LINE_LED)
led ^= ELSA_IPAC_LINE_LED;
if (cs->hw.elsa.ctrl_reg & ELSA_STAT_LED)
led ^= ELSA_IPAC_STAT_LED;
writereg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ATX, led);
} else
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
if (blink) {
init_timer(&cs->hw.elsa.tl);
cs->hw.elsa.tl.expires = jiffies + ((blink * HZ) / 1000);
add_timer(&cs->hw.elsa.tl);
}
}
static int
Elsa_card_msg(struct IsdnCardState *cs, int mt, void *arg)
{
int ret = 0;
u_long flags;
switch (mt) {
case CARD_RESET:
spin_lock_irqsave(&cs->lock, flags);
reset_elsa(cs);
spin_unlock_irqrestore(&cs->lock, flags);
return(0);
case CARD_RELEASE:
release_io_elsa(cs);
return(0);
case CARD_INIT:
spin_lock_irqsave(&cs->lock, flags);
cs->debug |= L1_DEB_IPAC;
reset_elsa(cs);
inithscxisac(cs, 1);
if ((cs->subtyp == ELSA_QS1000) ||
(cs->subtyp == ELSA_QS3000))
{
byteout(cs->hw.elsa.timer, 0);
}
if (cs->hw.elsa.trig)
byteout(cs->hw.elsa.trig, 0xff);
inithscxisac(cs, 2);
spin_unlock_irqrestore(&cs->lock, flags);
return(0);
case CARD_TEST:
if ((cs->subtyp == ELSA_PCMCIA) ||
(cs->subtyp == ELSA_PCMCIA_IPAC) ||
(cs->subtyp == ELSA_QS1000PCI)) {
return(0);
} else if (cs->subtyp == ELSA_QS3000PCI) {
ret = 0;
} else {
spin_lock_irqsave(&cs->lock, flags);
cs->hw.elsa.counter = 0;
cs->hw.elsa.ctrl_reg |= ELSA_ENA_TIMER_INT;
cs->hw.elsa.status |= ELIRQF_TIMER_AKTIV;
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
byteout(cs->hw.elsa.timer, 0);
spin_unlock_irqrestore(&cs->lock, flags);
msleep(110);
spin_lock_irqsave(&cs->lock, flags);
cs->hw.elsa.ctrl_reg &= ~ELSA_ENA_TIMER_INT;
byteout(cs->hw.elsa.ctrl, cs->hw.elsa.ctrl_reg);
cs->hw.elsa.status &= ~ELIRQF_TIMER_AKTIV;
spin_unlock_irqrestore(&cs->lock, flags);
printk(KERN_INFO "Elsa: %d timer tics in 110 msek\n",
cs->hw.elsa.counter);
if ((cs->hw.elsa.counter > 10) &&
(cs->hw.elsa.counter < 16)) {
printk(KERN_INFO "Elsa: timer and irq OK\n");
ret = 0;
} else {
printk(KERN_WARNING
"Elsa: timer tic problem (%d/12) maybe an IRQ(%d) conflict\n",
cs->hw.elsa.counter, cs->irq);
ret = 1;
}
}
#if ARCOFI_USE
if (check_arcofi(cs)) {
init_modem(cs);
}
#endif
elsa_led_handler(cs);
return(ret);
case (MDL_REMOVE | REQUEST):
cs->hw.elsa.status &= 0;
break;
case (MDL_ASSIGN | REQUEST):
cs->hw.elsa.status |= ELSA_ASSIGN;
break;
case MDL_INFO_SETUP:
if ((long) arg)
cs->hw.elsa.status |= 0x0200;
else
cs->hw.elsa.status |= 0x0100;
break;
case MDL_INFO_CONN:
if ((long) arg)
cs->hw.elsa.status |= 0x2000;
else
cs->hw.elsa.status |= 0x1000;
break;
case MDL_INFO_REL:
if ((long) arg) {
cs->hw.elsa.status &= ~0x2000;
cs->hw.elsa.status &= ~0x0200;
} else {
cs->hw.elsa.status &= ~0x1000;
cs->hw.elsa.status &= ~0x0100;
}
break;
#if ARCOFI_USE
case CARD_AUX_IND:
if (cs->hw.elsa.MFlag) {
int len;
u_char *msg;
if (!arg)
return(0);
msg = arg;
len = *msg;
msg++;
modem_write_cmd(cs, msg, len);
}
break;
#endif
}
if (cs->typ == ISDN_CTYPE_ELSA) {
int pwr = bytein(cs->hw.elsa.ale);
if (pwr & 0x08)
cs->hw.elsa.status |= ELSA_BAD_PWR;
else
cs->hw.elsa.status &= ~ELSA_BAD_PWR;
}
elsa_led_handler(cs);
return(ret);
}
static unsigned char
probe_elsa_adr(unsigned int adr, int typ)
{
int i, in1, in2, p16_1 = 0, p16_2 = 0, p8_1 = 0, p8_2 = 0, pc_1 = 0,
pc_2 = 0, pfp_1 = 0, pfp_2 = 0;
/* In case of the elsa pcmcia card, this region is in use,
reserved for us by the card manager. So we do not check it
here, it would fail. */
if (typ != ISDN_CTYPE_ELSA_PCMCIA) {
if (request_region(adr, 8, "elsa card")) {
release_region(adr, 8);
} else {
printk(KERN_WARNING
"Elsa: Probing Port 0x%x: already in use\n", adr);
return (0);
}
}
for (i = 0; i < 16; i++) {
in1 = inb(adr + ELSA_CONFIG); /* 'toggelt' bei */
in2 = inb(adr + ELSA_CONFIG); /* jedem Zugriff */
p16_1 += 0x04 & in1;
p16_2 += 0x04 & in2;
p8_1 += 0x02 & in1;
p8_2 += 0x02 & in2;
pc_1 += 0x01 & in1;
pc_2 += 0x01 & in2;
pfp_1 += 0x40 & in1;
pfp_2 += 0x40 & in2;
}
printk(KERN_INFO "Elsa: Probing IO 0x%x", adr);
if (65 == ++p16_1 * ++p16_2) {
printk(" PCC-16/PCF found\n");
return (ELSA_PCC16);
} else if (1025 == ++pfp_1 * ++pfp_2) {
printk(" PCF-Pro found\n");
return (ELSA_PCFPRO);
} else if (33 == ++p8_1 * ++p8_2) {
printk(" PCC8 found\n");
return (ELSA_PCC8);
} else if (17 == ++pc_1 * ++pc_2) {
printk(" PC found\n");
return (ELSA_PC);
} else {
printk(" failed\n");
return (0);
}
}
static unsigned int
probe_elsa(struct IsdnCardState *cs)
{
int i;
unsigned int CARD_portlist[] =
{0x160, 0x170, 0x260, 0x360, 0};
for (i = 0; CARD_portlist[i]; i++) {
if ((cs->subtyp = probe_elsa_adr(CARD_portlist[i], cs->typ)))
break;
}
return (CARD_portlist[i]);
}
static int __devinit
setup_elsa_isa(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
u_char val;
cs->hw.elsa.base = card->para[0];
printk(KERN_INFO "Elsa: Microlink IO probing\n");
if (cs->hw.elsa.base) {
if (!(cs->subtyp = probe_elsa_adr(cs->hw.elsa.base,
cs->typ))) {
printk(KERN_WARNING
"Elsa: no Elsa Microlink at %#lx\n",
cs->hw.elsa.base);
return (0);
}
} else
cs->hw.elsa.base = probe_elsa(cs);
if (!cs->hw.elsa.base) {
printk(KERN_WARNING
"No Elsa Microlink found\n");
return (0);
}
cs->hw.elsa.cfg = cs->hw.elsa.base + ELSA_CONFIG;
cs->hw.elsa.ctrl = cs->hw.elsa.base + ELSA_CONTROL;
cs->hw.elsa.ale = cs->hw.elsa.base + ELSA_ALE;
cs->hw.elsa.isac = cs->hw.elsa.base + ELSA_ISAC;
cs->hw.elsa.itac = cs->hw.elsa.base + ELSA_ITAC;
cs->hw.elsa.hscx = cs->hw.elsa.base + ELSA_HSCX;
cs->hw.elsa.trig = cs->hw.elsa.base + ELSA_TRIG_IRQ;
cs->hw.elsa.timer = cs->hw.elsa.base + ELSA_START_TIMER;
val = bytein(cs->hw.elsa.cfg);
if (cs->subtyp == ELSA_PC) {
const u_char CARD_IrqTab[8] =
{7, 3, 5, 9, 0, 0, 0, 0};
cs->irq = CARD_IrqTab[(val & ELSA_IRQ_IDX_PC) >> 2];
} else if (cs->subtyp == ELSA_PCC8) {
const u_char CARD_IrqTab[8] =
{7, 3, 5, 9, 0, 0, 0, 0};
cs->irq = CARD_IrqTab[(val & ELSA_IRQ_IDX_PCC8) >> 4];
} else {
const u_char CARD_IrqTab[8] =
{15, 10, 15, 3, 11, 5, 11, 9};
cs->irq = CARD_IrqTab[(val & ELSA_IRQ_IDX) >> 3];
}
val = bytein(cs->hw.elsa.ale) & ELSA_HW_RELEASE;
if (val < 3)
val |= 8;
val += 'A' - 3;
if (val == 'B' || val == 'C')
val ^= 1;
if ((cs->subtyp == ELSA_PCFPRO) && (val == 'G'))
val = 'C';
printk(KERN_INFO
"Elsa: %s found at %#lx Rev.:%c IRQ %d\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base,
val, cs->irq);
val = bytein(cs->hw.elsa.ale) & ELSA_S0_POWER_BAD;
if (val) {
printk(KERN_WARNING
"Elsa: Microlink S0 bus power bad\n");
cs->hw.elsa.status |= ELSA_BAD_PWR;
}
return (1);
}
#ifdef __ISAPNP__
static struct isapnp_device_id elsa_ids[] __devinitdata = {
{ ISAPNP_VENDOR('E', 'L', 'S'), ISAPNP_FUNCTION(0x0133),
ISAPNP_VENDOR('E', 'L', 'S'), ISAPNP_FUNCTION(0x0133),
(unsigned long) "Elsa QS1000" },
{ ISAPNP_VENDOR('E', 'L', 'S'), ISAPNP_FUNCTION(0x0134),
ISAPNP_VENDOR('E', 'L', 'S'), ISAPNP_FUNCTION(0x0134),
(unsigned long) "Elsa QS3000" },
{ 0, }
};
static struct isapnp_device_id *ipid __devinitdata = &elsa_ids[0];
static struct pnp_card *pnp_c __devinitdata = NULL;
#endif /* __ISAPNP__ */
static int __devinit
setup_elsa_isapnp(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
#ifdef __ISAPNP__
if (!card->para[1] && isapnp_present()) {
struct pnp_dev *pnp_d;
while(ipid->card_vendor) {
if ((pnp_c = pnp_find_card(ipid->card_vendor,
ipid->card_device, pnp_c))) {
pnp_d = NULL;
if ((pnp_d = pnp_find_dev(pnp_c,
ipid->vendor, ipid->function, pnp_d))) {
int err;
printk(KERN_INFO "HiSax: %s detected\n",
(char *)ipid->driver_data);
pnp_disable_dev(pnp_d);
err = pnp_activate_dev(pnp_d);
if (err<0) {
printk(KERN_WARNING "%s: pnp_activate_dev ret(%d)\n",
__func__, err);
return(0);
}
card->para[1] = pnp_port_start(pnp_d, 0);
card->para[0] = pnp_irq(pnp_d, 0);
if (!card->para[0] || !card->para[1]) {
printk(KERN_ERR "Elsa PnP:some resources are missing %ld/%lx\n",
card->para[0], card->para[1]);
pnp_disable_dev(pnp_d);
return(0);
}
if (ipid->function == ISAPNP_FUNCTION(0x133))
cs->subtyp = ELSA_QS1000;
else
cs->subtyp = ELSA_QS3000;
break;
} else {
printk(KERN_ERR "Elsa PnP: PnP error card found, no device\n");
return(0);
}
}
ipid++;
pnp_c=NULL;
}
if (!ipid->card_vendor) {
printk(KERN_INFO "Elsa PnP: no ISAPnP card found\n");
return(0);
}
}
#endif /* __ISAPNP__ */
if (card->para[1] && card->para[0]) {
cs->hw.elsa.base = card->para[1];
cs->irq = card->para[0];
if (!cs->subtyp)
cs->subtyp = ELSA_QS1000;
} else {
printk(KERN_ERR "Elsa PnP: no parameter\n");
}
cs->hw.elsa.cfg = cs->hw.elsa.base + ELSA_CONFIG;
cs->hw.elsa.ale = cs->hw.elsa.base + ELSA_ALE;
cs->hw.elsa.isac = cs->hw.elsa.base + ELSA_ISAC;
cs->hw.elsa.hscx = cs->hw.elsa.base + ELSA_HSCX;
cs->hw.elsa.trig = cs->hw.elsa.base + ELSA_TRIG_IRQ;
cs->hw.elsa.timer = cs->hw.elsa.base + ELSA_START_TIMER;
cs->hw.elsa.ctrl = cs->hw.elsa.base + ELSA_CONTROL;
printk(KERN_INFO
"Elsa: %s defined at %#lx IRQ %d\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base,
cs->irq);
return (1);
}
static void __devinit
setup_elsa_pcmcia(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
u_char val;
cs->hw.elsa.base = card->para[1];
cs->irq = card->para[0];
val = readreg(cs->hw.elsa.base + 0, cs->hw.elsa.base + 2, IPAC_ID);
if ((val == 1) || (val == 2)) { /* IPAC version 1.1/1.2 */
cs->subtyp = ELSA_PCMCIA_IPAC;
cs->hw.elsa.ale = cs->hw.elsa.base + 0;
cs->hw.elsa.isac = cs->hw.elsa.base + 2;
cs->hw.elsa.hscx = cs->hw.elsa.base + 2;
test_and_set_bit(HW_IPAC, &cs->HW_Flags);
} else {
cs->subtyp = ELSA_PCMCIA;
cs->hw.elsa.ale = cs->hw.elsa.base + ELSA_ALE_PCM;
cs->hw.elsa.isac = cs->hw.elsa.base + ELSA_ISAC_PCM;
cs->hw.elsa.hscx = cs->hw.elsa.base + ELSA_HSCX;
}
cs->hw.elsa.timer = 0;
cs->hw.elsa.trig = 0;
cs->hw.elsa.ctrl = 0;
cs->irq_flags |= IRQF_SHARED;
printk(KERN_INFO
"Elsa: %s defined at %#lx IRQ %d\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base,
cs->irq);
}
#ifdef CONFIG_PCI
static struct pci_dev *dev_qs1000 __devinitdata = NULL;
static struct pci_dev *dev_qs3000 __devinitdata = NULL;
static int __devinit
setup_elsa_pci(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
cs->subtyp = 0;
if ((dev_qs1000 = hisax_find_pci_device(PCI_VENDOR_ID_ELSA,
PCI_DEVICE_ID_ELSA_MICROLINK, dev_qs1000))) {
if (pci_enable_device(dev_qs1000))
return(0);
cs->subtyp = ELSA_QS1000PCI;
cs->irq = dev_qs1000->irq;
cs->hw.elsa.cfg = pci_resource_start(dev_qs1000, 1);
cs->hw.elsa.base = pci_resource_start(dev_qs1000, 3);
} else if ((dev_qs3000 = hisax_find_pci_device(PCI_VENDOR_ID_ELSA,
PCI_DEVICE_ID_ELSA_QS3000, dev_qs3000))) {
if (pci_enable_device(dev_qs3000))
return(0);
cs->subtyp = ELSA_QS3000PCI;
cs->irq = dev_qs3000->irq;
cs->hw.elsa.cfg = pci_resource_start(dev_qs3000, 1);
cs->hw.elsa.base = pci_resource_start(dev_qs3000, 3);
} else {
printk(KERN_WARNING "Elsa: No PCI card found\n");
return(0);
}
if (!cs->irq) {
printk(KERN_WARNING "Elsa: No IRQ for PCI card found\n");
return(0);
}
if (!(cs->hw.elsa.base && cs->hw.elsa.cfg)) {
printk(KERN_WARNING "Elsa: No IO-Adr for PCI card found\n");
return(0);
}
if ((cs->hw.elsa.cfg & 0xff) || (cs->hw.elsa.base & 0xf)) {
printk(KERN_WARNING "Elsa: You may have a wrong PCI bios\n");
printk(KERN_WARNING "Elsa: If your system hangs now, read\n");
printk(KERN_WARNING "Elsa: Documentation/isdn/README.HiSax\n");
}
cs->hw.elsa.ale = cs->hw.elsa.base;
cs->hw.elsa.isac = cs->hw.elsa.base +1;
cs->hw.elsa.hscx = cs->hw.elsa.base +1;
test_and_set_bit(HW_IPAC, &cs->HW_Flags);
cs->hw.elsa.timer = 0;
cs->hw.elsa.trig = 0;
cs->irq_flags |= IRQF_SHARED;
printk(KERN_INFO
"Elsa: %s defined at %#lx/0x%x IRQ %d\n",
Elsa_Types[cs->subtyp],
cs->hw.elsa.base,
cs->hw.elsa.cfg,
cs->irq);
return (1);
}
#else
static int __devinit
setup_elsa_pci(struct IsdnCard *card)
{
return (1);
}
#endif /* CONFIG_PCI */
static int __devinit
setup_elsa_common(struct IsdnCard *card)
{
struct IsdnCardState *cs = card->cs;
u_char val;
int bytecnt;
switch (cs->subtyp) {
case ELSA_PC:
case ELSA_PCC8:
case ELSA_PCC16:
case ELSA_QS1000:
case ELSA_PCMCIA:
case ELSA_PCMCIA_IPAC:
bytecnt = 8;
break;
case ELSA_PCFPRO:
case ELSA_PCF:
case ELSA_QS3000:
case ELSA_QS3000PCI:
bytecnt = 16;
break;
case ELSA_QS1000PCI:
bytecnt = 2;
break;
default:
printk(KERN_WARNING
"Unknown ELSA subtype %d\n", cs->subtyp);
return (0);
}
/* In case of the elsa pcmcia card, this region is in use,
reserved for us by the card manager. So we do not check it
here, it would fail. */
if (cs->typ != ISDN_CTYPE_ELSA_PCMCIA && !request_region(cs->hw.elsa.base, bytecnt, "elsa isdn")) {
printk(KERN_WARNING
"HiSax: ELSA config port %#lx-%#lx already in use\n",
cs->hw.elsa.base,
cs->hw.elsa.base + bytecnt);
return (0);
}
if ((cs->subtyp == ELSA_QS1000PCI) || (cs->subtyp == ELSA_QS3000PCI)) {
if (!request_region(cs->hw.elsa.cfg, 0x80, "elsa isdn pci")) {
printk(KERN_WARNING
"HiSax: ELSA pci port %x-%x already in use\n",
cs->hw.elsa.cfg,
cs->hw.elsa.cfg + 0x80);
release_region(cs->hw.elsa.base, bytecnt);
return (0);
}
}
#if ARCOFI_USE
init_arcofi(cs);
#endif
setup_isac(cs);
cs->hw.elsa.tl.function = (void *) elsa_led_handler;
cs->hw.elsa.tl.data = (long) cs;
init_timer(&cs->hw.elsa.tl);
/* Teste Timer */
if (cs->hw.elsa.timer) {
byteout(cs->hw.elsa.trig, 0xff);
byteout(cs->hw.elsa.timer, 0);
if (!TimerRun(cs)) {
byteout(cs->hw.elsa.timer, 0); /* 2. Versuch */
if (!TimerRun(cs)) {
printk(KERN_WARNING
"Elsa: timer do not start\n");
release_io_elsa(cs);
return (0);
}
}
HZDELAY((HZ/100) + 1); /* wait >=10 ms */
if (TimerRun(cs)) {
printk(KERN_WARNING "Elsa: timer do not run down\n");
release_io_elsa(cs);
return (0);
}
printk(KERN_INFO "Elsa: timer OK; resetting card\n");
}
cs->BC_Read_Reg = &ReadHSCX;
cs->BC_Write_Reg = &WriteHSCX;
cs->BC_Send_Data = &hscx_fill_fifo;
cs->cardmsg = &Elsa_card_msg;
if ((cs->subtyp == ELSA_QS1000PCI) || (cs->subtyp == ELSA_QS3000PCI) || (cs->subtyp == ELSA_PCMCIA_IPAC)) {
cs->readisac = &ReadISAC_IPAC;
cs->writeisac = &WriteISAC_IPAC;
cs->readisacfifo = &ReadISACfifo_IPAC;
cs->writeisacfifo = &WriteISACfifo_IPAC;
cs->irq_func = &elsa_interrupt_ipac;
val = readreg(cs->hw.elsa.ale, cs->hw.elsa.isac, IPAC_ID);
printk(KERN_INFO "Elsa: IPAC version %x\n", val);
} else {
cs->readisac = &ReadISAC;
cs->writeisac = &WriteISAC;
cs->readisacfifo = &ReadISACfifo;
cs->writeisacfifo = &WriteISACfifo;
cs->irq_func = &elsa_interrupt;
ISACVersion(cs, "Elsa:");
if (HscxVersion(cs, "Elsa:")) {
printk(KERN_WARNING
"Elsa: wrong HSCX versions check IO address\n");
release_io_elsa(cs);
return (0);
}
}
if (cs->subtyp == ELSA_PC) {
val = readitac(cs, ITAC_SYS);
printk(KERN_INFO "Elsa: ITAC version %s\n", ITACVer[val & 7]);
writeitac(cs, ITAC_ISEN, 0);
writeitac(cs, ITAC_RFIE, 0);
writeitac(cs, ITAC_XFIE, 0);
writeitac(cs, ITAC_SCIE, 0);
writeitac(cs, ITAC_STIE, 0);
}
return (1);
}
int __devinit
setup_elsa(struct IsdnCard *card)
{
int rc;
struct IsdnCardState *cs = card->cs;
char tmp[64];
strcpy(tmp, Elsa_revision);
printk(KERN_INFO "HiSax: Elsa driver Rev. %s\n", HiSax_getrev(tmp));
cs->hw.elsa.ctrl_reg = 0;
cs->hw.elsa.status = 0;
cs->hw.elsa.MFlag = 0;
cs->subtyp = 0;
if (cs->typ == ISDN_CTYPE_ELSA) {
rc = setup_elsa_isa(card);
if (!rc)
return (0);
} else if (cs->typ == ISDN_CTYPE_ELSA_PNP) {
rc = setup_elsa_isapnp(card);
if (!rc)
return (0);
} else if (cs->typ == ISDN_CTYPE_ELSA_PCMCIA)
setup_elsa_pcmcia(card);
else if (cs->typ == ISDN_CTYPE_ELSA_PCI) {
rc = setup_elsa_pci(card);
if (!rc)
return (0);
} else
return (0);
return setup_elsa_common(card);
}
| gpl-2.0 |
Kurre/kernel_samsung_manta | fs/ncpfs/ioctl.c | 4741 | 22958 | /*
* ioctl.c
*
* Copyright (C) 1995, 1996 by Volker Lendecke
* Modified 1997 Peter Waltenberg, Bill Hawes, David Woodhouse for 2.1 dcache
* Modified 1998, 1999 Wolfram Pienkoss for NLS
*
*/
#include <linux/capability.h>
#include <linux/compat.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/ioctl.h>
#include <linux/time.h>
#include <linux/mm.h>
#include <linux/mount.h>
#include <linux/slab.h>
#include <linux/highuid.h>
#include <linux/vmalloc.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#include "ncp_fs.h"
/* maximum limit for ncp_objectname_ioctl */
#define NCP_OBJECT_NAME_MAX_LEN 4096
/* maximum limit for ncp_privatedata_ioctl */
#define NCP_PRIVATE_DATA_MAX_LEN 8192
/* maximum negotiable packet size */
#define NCP_PACKET_SIZE_INTERNAL 65536
static int
ncp_get_fs_info(struct ncp_server * server, struct inode *inode,
struct ncp_fs_info __user *arg)
{
struct ncp_fs_info info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
if (info.version != NCP_GET_FS_INFO_VERSION) {
DPRINTK("info.version invalid: %d\n", info.version);
return -EINVAL;
}
/* TODO: info.addr = server->m.serv_addr; */
SET_UID(info.mounted_uid, server->m.mounted_uid);
info.connection = server->connection;
info.buffer_size = server->buffer_size;
info.volume_number = NCP_FINFO(inode)->volNumber;
info.directory_id = NCP_FINFO(inode)->DosDirNum;
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
static int
ncp_get_fs_info_v2(struct ncp_server * server, struct inode *inode,
struct ncp_fs_info_v2 __user * arg)
{
struct ncp_fs_info_v2 info2;
if (copy_from_user(&info2, arg, sizeof(info2)))
return -EFAULT;
if (info2.version != NCP_GET_FS_INFO_VERSION_V2) {
DPRINTK("info.version invalid: %d\n", info2.version);
return -EINVAL;
}
info2.mounted_uid = server->m.mounted_uid;
info2.connection = server->connection;
info2.buffer_size = server->buffer_size;
info2.volume_number = NCP_FINFO(inode)->volNumber;
info2.directory_id = NCP_FINFO(inode)->DosDirNum;
info2.dummy1 = info2.dummy2 = info2.dummy3 = 0;
if (copy_to_user(arg, &info2, sizeof(info2)))
return -EFAULT;
return 0;
}
#ifdef CONFIG_COMPAT
struct compat_ncp_objectname_ioctl
{
s32 auth_type;
u32 object_name_len;
compat_caddr_t object_name; /* a userspace data, in most cases user name */
};
struct compat_ncp_fs_info_v2 {
s32 version;
u32 mounted_uid;
u32 connection;
u32 buffer_size;
u32 volume_number;
u32 directory_id;
u32 dummy1;
u32 dummy2;
u32 dummy3;
};
struct compat_ncp_ioctl_request {
u32 function;
u32 size;
compat_caddr_t data;
};
struct compat_ncp_privatedata_ioctl
{
u32 len;
compat_caddr_t data; /* ~1000 for NDS */
};
#define NCP_IOC_GET_FS_INFO_V2_32 _IOWR('n', 4, struct compat_ncp_fs_info_v2)
#define NCP_IOC_NCPREQUEST_32 _IOR('n', 1, struct compat_ncp_ioctl_request)
#define NCP_IOC_GETOBJECTNAME_32 _IOWR('n', 9, struct compat_ncp_objectname_ioctl)
#define NCP_IOC_SETOBJECTNAME_32 _IOR('n', 9, struct compat_ncp_objectname_ioctl)
#define NCP_IOC_GETPRIVATEDATA_32 _IOWR('n', 10, struct compat_ncp_privatedata_ioctl)
#define NCP_IOC_SETPRIVATEDATA_32 _IOR('n', 10, struct compat_ncp_privatedata_ioctl)
static int
ncp_get_compat_fs_info_v2(struct ncp_server * server, struct inode *inode,
struct compat_ncp_fs_info_v2 __user * arg)
{
struct compat_ncp_fs_info_v2 info2;
if (copy_from_user(&info2, arg, sizeof(info2)))
return -EFAULT;
if (info2.version != NCP_GET_FS_INFO_VERSION_V2) {
DPRINTK("info.version invalid: %d\n", info2.version);
return -EINVAL;
}
info2.mounted_uid = server->m.mounted_uid;
info2.connection = server->connection;
info2.buffer_size = server->buffer_size;
info2.volume_number = NCP_FINFO(inode)->volNumber;
info2.directory_id = NCP_FINFO(inode)->DosDirNum;
info2.dummy1 = info2.dummy2 = info2.dummy3 = 0;
if (copy_to_user(arg, &info2, sizeof(info2)))
return -EFAULT;
return 0;
}
#endif
#define NCP_IOC_GETMOUNTUID16 _IOW('n', 2, u16)
#define NCP_IOC_GETMOUNTUID32 _IOW('n', 2, u32)
#define NCP_IOC_GETMOUNTUID64 _IOW('n', 2, u64)
#ifdef CONFIG_NCPFS_NLS
/* Here we are select the iocharset and the codepage for NLS.
* Thanks Petr Vandrovec for idea and many hints.
*/
static int
ncp_set_charsets(struct ncp_server* server, struct ncp_nls_ioctl __user *arg)
{
struct ncp_nls_ioctl user;
struct nls_table *codepage;
struct nls_table *iocharset;
struct nls_table *oldset_io;
struct nls_table *oldset_cp;
int utf8;
int err;
if (copy_from_user(&user, arg, sizeof(user)))
return -EFAULT;
codepage = NULL;
user.codepage[NCP_IOCSNAME_LEN] = 0;
if (!user.codepage[0] || !strcmp(user.codepage, "default"))
codepage = load_nls_default();
else {
codepage = load_nls(user.codepage);
if (!codepage) {
return -EBADRQC;
}
}
iocharset = NULL;
user.iocharset[NCP_IOCSNAME_LEN] = 0;
if (!user.iocharset[0] || !strcmp(user.iocharset, "default")) {
iocharset = load_nls_default();
utf8 = 0;
} else if (!strcmp(user.iocharset, "utf8")) {
iocharset = load_nls_default();
utf8 = 1;
} else {
iocharset = load_nls(user.iocharset);
if (!iocharset) {
unload_nls(codepage);
return -EBADRQC;
}
utf8 = 0;
}
mutex_lock(&server->root_setup_lock);
if (server->root_setuped) {
oldset_cp = codepage;
oldset_io = iocharset;
err = -EBUSY;
} else {
if (utf8)
NCP_SET_FLAG(server, NCP_FLAG_UTF8);
else
NCP_CLR_FLAG(server, NCP_FLAG_UTF8);
oldset_cp = server->nls_vol;
server->nls_vol = codepage;
oldset_io = server->nls_io;
server->nls_io = iocharset;
err = 0;
}
mutex_unlock(&server->root_setup_lock);
unload_nls(oldset_cp);
unload_nls(oldset_io);
return err;
}
static int
ncp_get_charsets(struct ncp_server* server, struct ncp_nls_ioctl __user *arg)
{
struct ncp_nls_ioctl user;
int len;
memset(&user, 0, sizeof(user));
mutex_lock(&server->root_setup_lock);
if (server->nls_vol && server->nls_vol->charset) {
len = strlen(server->nls_vol->charset);
if (len > NCP_IOCSNAME_LEN)
len = NCP_IOCSNAME_LEN;
strncpy(user.codepage, server->nls_vol->charset, len);
user.codepage[len] = 0;
}
if (NCP_IS_FLAG(server, NCP_FLAG_UTF8))
strcpy(user.iocharset, "utf8");
else if (server->nls_io && server->nls_io->charset) {
len = strlen(server->nls_io->charset);
if (len > NCP_IOCSNAME_LEN)
len = NCP_IOCSNAME_LEN;
strncpy(user.iocharset, server->nls_io->charset, len);
user.iocharset[len] = 0;
}
mutex_unlock(&server->root_setup_lock);
if (copy_to_user(arg, &user, sizeof(user)))
return -EFAULT;
return 0;
}
#endif /* CONFIG_NCPFS_NLS */
static long __ncp_ioctl(struct inode *inode, unsigned int cmd, unsigned long arg)
{
struct ncp_server *server = NCP_SERVER(inode);
int result;
struct ncp_ioctl_request request;
char* bouncebuffer;
void __user *argp = (void __user *)arg;
switch (cmd) {
#ifdef CONFIG_COMPAT
case NCP_IOC_NCPREQUEST_32:
#endif
case NCP_IOC_NCPREQUEST:
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_NCPREQUEST_32) {
struct compat_ncp_ioctl_request request32;
if (copy_from_user(&request32, argp, sizeof(request32)))
return -EFAULT;
request.function = request32.function;
request.size = request32.size;
request.data = compat_ptr(request32.data);
} else
#endif
if (copy_from_user(&request, argp, sizeof(request)))
return -EFAULT;
if ((request.function > 255)
|| (request.size >
NCP_PACKET_SIZE - sizeof(struct ncp_request_header))) {
return -EINVAL;
}
bouncebuffer = vmalloc(NCP_PACKET_SIZE_INTERNAL);
if (!bouncebuffer)
return -ENOMEM;
if (copy_from_user(bouncebuffer, request.data, request.size)) {
vfree(bouncebuffer);
return -EFAULT;
}
ncp_lock_server(server);
/* FIXME: We hack around in the server's structures
here to be able to use ncp_request */
server->has_subfunction = 0;
server->current_size = request.size;
memcpy(server->packet, bouncebuffer, request.size);
result = ncp_request2(server, request.function,
bouncebuffer, NCP_PACKET_SIZE_INTERNAL);
if (result < 0)
result = -EIO;
else
result = server->reply_size;
ncp_unlock_server(server);
DPRINTK("ncp_ioctl: copy %d bytes\n",
result);
if (result >= 0)
if (copy_to_user(request.data, bouncebuffer, result))
result = -EFAULT;
vfree(bouncebuffer);
return result;
case NCP_IOC_CONN_LOGGED_IN:
if (!(server->m.int_flags & NCP_IMOUNT_LOGGEDIN_POSSIBLE))
return -EINVAL;
mutex_lock(&server->root_setup_lock);
if (server->root_setuped)
result = -EBUSY;
else {
result = ncp_conn_logged_in(inode->i_sb);
if (result == 0)
server->root_setuped = 1;
}
mutex_unlock(&server->root_setup_lock);
return result;
case NCP_IOC_GET_FS_INFO:
return ncp_get_fs_info(server, inode, argp);
case NCP_IOC_GET_FS_INFO_V2:
return ncp_get_fs_info_v2(server, inode, argp);
#ifdef CONFIG_COMPAT
case NCP_IOC_GET_FS_INFO_V2_32:
return ncp_get_compat_fs_info_v2(server, inode, argp);
#endif
/* we have too many combinations of CONFIG_COMPAT,
* CONFIG_64BIT and CONFIG_UID16, so just handle
* any of the possible ioctls */
case NCP_IOC_GETMOUNTUID16:
{
u16 uid;
SET_UID(uid, server->m.mounted_uid);
if (put_user(uid, (u16 __user *)argp))
return -EFAULT;
return 0;
}
case NCP_IOC_GETMOUNTUID32:
if (put_user(server->m.mounted_uid,
(u32 __user *)argp))
return -EFAULT;
return 0;
case NCP_IOC_GETMOUNTUID64:
if (put_user(server->m.mounted_uid,
(u64 __user *)argp))
return -EFAULT;
return 0;
case NCP_IOC_GETROOT:
{
struct ncp_setroot_ioctl sr;
result = -EACCES;
mutex_lock(&server->root_setup_lock);
if (server->m.mounted_vol[0]) {
struct dentry* dentry = inode->i_sb->s_root;
if (dentry) {
struct inode* s_inode = dentry->d_inode;
if (s_inode) {
sr.volNumber = NCP_FINFO(s_inode)->volNumber;
sr.dirEntNum = NCP_FINFO(s_inode)->dirEntNum;
sr.namespace = server->name_space[sr.volNumber];
result = 0;
} else
DPRINTK("ncpfs: s_root->d_inode==NULL\n");
} else
DPRINTK("ncpfs: s_root==NULL\n");
} else {
sr.volNumber = -1;
sr.namespace = 0;
sr.dirEntNum = 0;
result = 0;
}
mutex_unlock(&server->root_setup_lock);
if (!result && copy_to_user(argp, &sr, sizeof(sr)))
result = -EFAULT;
return result;
}
case NCP_IOC_SETROOT:
{
struct ncp_setroot_ioctl sr;
__u32 vnum;
__le32 de;
__le32 dosde;
struct dentry* dentry;
if (copy_from_user(&sr, argp, sizeof(sr)))
return -EFAULT;
mutex_lock(&server->root_setup_lock);
if (server->root_setuped)
result = -EBUSY;
else {
if (sr.volNumber < 0) {
server->m.mounted_vol[0] = 0;
vnum = NCP_NUMBER_OF_VOLUMES;
de = 0;
dosde = 0;
result = 0;
} else if (sr.volNumber >= NCP_NUMBER_OF_VOLUMES) {
result = -EINVAL;
} else if (ncp_mount_subdir(server, sr.volNumber,
sr.namespace, sr.dirEntNum,
&vnum, &de, &dosde)) {
result = -ENOENT;
} else
result = 0;
if (result == 0) {
dentry = inode->i_sb->s_root;
if (dentry) {
struct inode* s_inode = dentry->d_inode;
if (s_inode) {
NCP_FINFO(s_inode)->volNumber = vnum;
NCP_FINFO(s_inode)->dirEntNum = de;
NCP_FINFO(s_inode)->DosDirNum = dosde;
server->root_setuped = 1;
} else {
DPRINTK("ncpfs: s_root->d_inode==NULL\n");
result = -EIO;
}
} else {
DPRINTK("ncpfs: s_root==NULL\n");
result = -EIO;
}
}
result = 0;
}
mutex_unlock(&server->root_setup_lock);
return result;
}
#ifdef CONFIG_NCPFS_PACKET_SIGNING
case NCP_IOC_SIGN_INIT:
{
struct ncp_sign_init sign;
if (argp)
if (copy_from_user(&sign, argp, sizeof(sign)))
return -EFAULT;
ncp_lock_server(server);
mutex_lock(&server->rcv.creq_mutex);
if (argp) {
if (server->sign_wanted) {
memcpy(server->sign_root,sign.sign_root,8);
memcpy(server->sign_last,sign.sign_last,16);
server->sign_active = 1;
}
/* ignore when signatures not wanted */
} else {
server->sign_active = 0;
}
mutex_unlock(&server->rcv.creq_mutex);
ncp_unlock_server(server);
return 0;
}
case NCP_IOC_SIGN_WANTED:
{
int state;
ncp_lock_server(server);
state = server->sign_wanted;
ncp_unlock_server(server);
if (put_user(state, (int __user *)argp))
return -EFAULT;
return 0;
}
case NCP_IOC_SET_SIGN_WANTED:
{
int newstate;
/* get only low 8 bits... */
if (get_user(newstate, (unsigned char __user *)argp))
return -EFAULT;
result = 0;
ncp_lock_server(server);
if (server->sign_active) {
/* cannot turn signatures OFF when active */
if (!newstate)
result = -EINVAL;
} else {
server->sign_wanted = newstate != 0;
}
ncp_unlock_server(server);
return result;
}
#endif /* CONFIG_NCPFS_PACKET_SIGNING */
#ifdef CONFIG_NCPFS_IOCTL_LOCKING
case NCP_IOC_LOCKUNLOCK:
{
struct ncp_lock_ioctl rqdata;
if (copy_from_user(&rqdata, argp, sizeof(rqdata)))
return -EFAULT;
if (rqdata.origin != 0)
return -EINVAL;
/* check for cmd */
switch (rqdata.cmd) {
case NCP_LOCK_EX:
case NCP_LOCK_SH:
if (rqdata.timeout == 0)
rqdata.timeout = NCP_LOCK_DEFAULT_TIMEOUT;
else if (rqdata.timeout > NCP_LOCK_MAX_TIMEOUT)
rqdata.timeout = NCP_LOCK_MAX_TIMEOUT;
break;
case NCP_LOCK_LOG:
rqdata.timeout = NCP_LOCK_DEFAULT_TIMEOUT; /* has no effect */
case NCP_LOCK_CLEAR:
break;
default:
return -EINVAL;
}
/* locking needs both read and write access */
if ((result = ncp_make_open(inode, O_RDWR)) != 0)
{
return result;
}
result = -EISDIR;
if (!S_ISREG(inode->i_mode))
goto outrel;
if (rqdata.cmd == NCP_LOCK_CLEAR)
{
result = ncp_ClearPhysicalRecord(NCP_SERVER(inode),
NCP_FINFO(inode)->file_handle,
rqdata.offset,
rqdata.length);
if (result > 0) result = 0; /* no such lock */
}
else
{
int lockcmd;
switch (rqdata.cmd)
{
case NCP_LOCK_EX: lockcmd=1; break;
case NCP_LOCK_SH: lockcmd=3; break;
default: lockcmd=0; break;
}
result = ncp_LogPhysicalRecord(NCP_SERVER(inode),
NCP_FINFO(inode)->file_handle,
lockcmd,
rqdata.offset,
rqdata.length,
rqdata.timeout);
if (result > 0) result = -EAGAIN;
}
outrel:
ncp_inode_close(inode);
return result;
}
#endif /* CONFIG_NCPFS_IOCTL_LOCKING */
#ifdef CONFIG_COMPAT
case NCP_IOC_GETOBJECTNAME_32:
{
struct compat_ncp_objectname_ioctl user;
size_t outl;
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
down_read(&server->auth_rwsem);
user.auth_type = server->auth.auth_type;
outl = user.object_name_len;
user.object_name_len = server->auth.object_name_len;
if (outl > user.object_name_len)
outl = user.object_name_len;
result = 0;
if (outl) {
if (copy_to_user(compat_ptr(user.object_name),
server->auth.object_name,
outl))
result = -EFAULT;
}
up_read(&server->auth_rwsem);
if (!result && copy_to_user(argp, &user, sizeof(user)))
result = -EFAULT;
return result;
}
#endif
case NCP_IOC_GETOBJECTNAME:
{
struct ncp_objectname_ioctl user;
size_t outl;
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
down_read(&server->auth_rwsem);
user.auth_type = server->auth.auth_type;
outl = user.object_name_len;
user.object_name_len = server->auth.object_name_len;
if (outl > user.object_name_len)
outl = user.object_name_len;
result = 0;
if (outl) {
if (copy_to_user(user.object_name,
server->auth.object_name,
outl))
result = -EFAULT;
}
up_read(&server->auth_rwsem);
if (!result && copy_to_user(argp, &user, sizeof(user)))
result = -EFAULT;
return result;
}
#ifdef CONFIG_COMPAT
case NCP_IOC_SETOBJECTNAME_32:
#endif
case NCP_IOC_SETOBJECTNAME:
{
struct ncp_objectname_ioctl user;
void* newname;
void* oldname;
size_t oldnamelen;
void* oldprivate;
size_t oldprivatelen;
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_SETOBJECTNAME_32) {
struct compat_ncp_objectname_ioctl user32;
if (copy_from_user(&user32, argp, sizeof(user32)))
return -EFAULT;
user.auth_type = user32.auth_type;
user.object_name_len = user32.object_name_len;
user.object_name = compat_ptr(user32.object_name);
} else
#endif
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
if (user.object_name_len > NCP_OBJECT_NAME_MAX_LEN)
return -ENOMEM;
if (user.object_name_len) {
newname = memdup_user(user.object_name,
user.object_name_len);
if (IS_ERR(newname))
return PTR_ERR(newname);
} else {
newname = NULL;
}
down_write(&server->auth_rwsem);
oldname = server->auth.object_name;
oldnamelen = server->auth.object_name_len;
oldprivate = server->priv.data;
oldprivatelen = server->priv.len;
server->auth.auth_type = user.auth_type;
server->auth.object_name_len = user.object_name_len;
server->auth.object_name = newname;
server->priv.len = 0;
server->priv.data = NULL;
up_write(&server->auth_rwsem);
kfree(oldprivate);
kfree(oldname);
return 0;
}
#ifdef CONFIG_COMPAT
case NCP_IOC_GETPRIVATEDATA_32:
#endif
case NCP_IOC_GETPRIVATEDATA:
{
struct ncp_privatedata_ioctl user;
size_t outl;
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_GETPRIVATEDATA_32) {
struct compat_ncp_privatedata_ioctl user32;
if (copy_from_user(&user32, argp, sizeof(user32)))
return -EFAULT;
user.len = user32.len;
user.data = compat_ptr(user32.data);
} else
#endif
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
down_read(&server->auth_rwsem);
outl = user.len;
user.len = server->priv.len;
if (outl > user.len) outl = user.len;
result = 0;
if (outl) {
if (copy_to_user(user.data,
server->priv.data,
outl))
result = -EFAULT;
}
up_read(&server->auth_rwsem);
if (result)
return result;
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_GETPRIVATEDATA_32) {
struct compat_ncp_privatedata_ioctl user32;
user32.len = user.len;
user32.data = (unsigned long) user.data;
if (copy_to_user(argp, &user32, sizeof(user32)))
return -EFAULT;
} else
#endif
if (copy_to_user(argp, &user, sizeof(user)))
return -EFAULT;
return 0;
}
#ifdef CONFIG_COMPAT
case NCP_IOC_SETPRIVATEDATA_32:
#endif
case NCP_IOC_SETPRIVATEDATA:
{
struct ncp_privatedata_ioctl user;
void* new;
void* old;
size_t oldlen;
#ifdef CONFIG_COMPAT
if (cmd == NCP_IOC_SETPRIVATEDATA_32) {
struct compat_ncp_privatedata_ioctl user32;
if (copy_from_user(&user32, argp, sizeof(user32)))
return -EFAULT;
user.len = user32.len;
user.data = compat_ptr(user32.data);
} else
#endif
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
if (user.len > NCP_PRIVATE_DATA_MAX_LEN)
return -ENOMEM;
if (user.len) {
new = memdup_user(user.data, user.len);
if (IS_ERR(new))
return PTR_ERR(new);
} else {
new = NULL;
}
down_write(&server->auth_rwsem);
old = server->priv.data;
oldlen = server->priv.len;
server->priv.len = user.len;
server->priv.data = new;
up_write(&server->auth_rwsem);
kfree(old);
return 0;
}
#ifdef CONFIG_NCPFS_NLS
case NCP_IOC_SETCHARSETS:
return ncp_set_charsets(server, argp);
case NCP_IOC_GETCHARSETS:
return ncp_get_charsets(server, argp);
#endif /* CONFIG_NCPFS_NLS */
case NCP_IOC_SETDENTRYTTL:
{
u_int32_t user;
if (copy_from_user(&user, argp, sizeof(user)))
return -EFAULT;
/* 20 secs at most... */
if (user > 20000)
return -EINVAL;
user = (user * HZ) / 1000;
atomic_set(&server->dentry_ttl, user);
return 0;
}
case NCP_IOC_GETDENTRYTTL:
{
u_int32_t user = (atomic_read(&server->dentry_ttl) * 1000) / HZ;
if (copy_to_user(argp, &user, sizeof(user)))
return -EFAULT;
return 0;
}
}
return -EINVAL;
}
long ncp_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct inode *inode = filp->f_dentry->d_inode;
struct ncp_server *server = NCP_SERVER(inode);
uid_t uid = current_uid();
int need_drop_write = 0;
long ret;
switch (cmd) {
case NCP_IOC_SETCHARSETS:
case NCP_IOC_CONN_LOGGED_IN:
case NCP_IOC_SETROOT:
if (!capable(CAP_SYS_ADMIN)) {
ret = -EACCES;
goto out;
}
break;
}
if (server->m.mounted_uid != uid) {
switch (cmd) {
/*
* Only mount owner can issue these ioctls. Information
* necessary to authenticate to other NDS servers are
* stored here.
*/
case NCP_IOC_GETOBJECTNAME:
case NCP_IOC_SETOBJECTNAME:
case NCP_IOC_GETPRIVATEDATA:
case NCP_IOC_SETPRIVATEDATA:
#ifdef CONFIG_COMPAT
case NCP_IOC_GETOBJECTNAME_32:
case NCP_IOC_SETOBJECTNAME_32:
case NCP_IOC_GETPRIVATEDATA_32:
case NCP_IOC_SETPRIVATEDATA_32:
#endif
ret = -EACCES;
goto out;
/*
* These require write access on the inode if user id
* does not match. Note that they do not write to the
* file... But old code did mnt_want_write, so I keep
* it as is. Of course not for mountpoint owner, as
* that breaks read-only mounts altogether as ncpmount
* needs working NCP_IOC_NCPREQUEST and
* NCP_IOC_GET_FS_INFO. Some of these codes (setdentryttl,
* signinit, setsignwanted) should be probably restricted
* to owner only, or even more to CAP_SYS_ADMIN).
*/
case NCP_IOC_GET_FS_INFO:
case NCP_IOC_GET_FS_INFO_V2:
case NCP_IOC_NCPREQUEST:
case NCP_IOC_SETDENTRYTTL:
case NCP_IOC_SIGN_INIT:
case NCP_IOC_LOCKUNLOCK:
case NCP_IOC_SET_SIGN_WANTED:
#ifdef CONFIG_COMPAT
case NCP_IOC_GET_FS_INFO_V2_32:
case NCP_IOC_NCPREQUEST_32:
#endif
ret = mnt_want_write_file(filp);
if (ret)
goto out;
need_drop_write = 1;
ret = inode_permission(inode, MAY_WRITE);
if (ret)
goto outDropWrite;
break;
/*
* Read access required.
*/
case NCP_IOC_GETMOUNTUID16:
case NCP_IOC_GETMOUNTUID32:
case NCP_IOC_GETMOUNTUID64:
case NCP_IOC_GETROOT:
case NCP_IOC_SIGN_WANTED:
ret = inode_permission(inode, MAY_READ);
if (ret)
goto out;
break;
/*
* Anybody can read these.
*/
case NCP_IOC_GETCHARSETS:
case NCP_IOC_GETDENTRYTTL:
default:
/* Three codes below are protected by CAP_SYS_ADMIN above. */
case NCP_IOC_SETCHARSETS:
case NCP_IOC_CONN_LOGGED_IN:
case NCP_IOC_SETROOT:
break;
}
}
ret = __ncp_ioctl(inode, cmd, arg);
outDropWrite:
if (need_drop_write)
mnt_drop_write_file(filp);
out:
return ret;
}
#ifdef CONFIG_COMPAT
long ncp_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
long ret;
arg = (unsigned long) compat_ptr(arg);
ret = ncp_ioctl(file, cmd, arg);
return ret;
}
#endif
| gpl-2.0 |
sinutech/sinuos-kernel | arch/mips/bcm47xx/serial.c | 4997 | 2459 | /*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*
* Copyright (C) 2007 Aurelien Jarno <aurelien@aurel32.net>
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/serial.h>
#include <linux/serial_8250.h>
#include <linux/ssb/ssb.h>
#include <bcm47xx.h>
static struct plat_serial8250_port uart8250_data[5];
static struct platform_device uart8250_device = {
.name = "serial8250",
.id = PLAT8250_DEV_PLATFORM,
.dev = {
.platform_data = uart8250_data,
},
};
#ifdef CONFIG_BCM47XX_SSB
static int __init uart8250_init_ssb(void)
{
int i;
struct ssb_mipscore *mcore = &(bcm47xx_bus.ssb.mipscore);
memset(&uart8250_data, 0, sizeof(uart8250_data));
for (i = 0; i < mcore->nr_serial_ports; i++) {
struct plat_serial8250_port *p = &(uart8250_data[i]);
struct ssb_serial_port *ssb_port = &(mcore->serial_ports[i]);
p->mapbase = (unsigned int) ssb_port->regs;
p->membase = (void *) ssb_port->regs;
p->irq = ssb_port->irq + 2;
p->uartclk = ssb_port->baud_base;
p->regshift = ssb_port->reg_shift;
p->iotype = UPIO_MEM;
p->flags = UPF_BOOT_AUTOCONF | UPF_SHARE_IRQ;
}
return platform_device_register(&uart8250_device);
}
#endif
#ifdef CONFIG_BCM47XX_BCMA
static int __init uart8250_init_bcma(void)
{
int i;
struct bcma_drv_cc *cc = &(bcm47xx_bus.bcma.bus.drv_cc);
memset(&uart8250_data, 0, sizeof(uart8250_data));
for (i = 0; i < cc->nr_serial_ports; i++) {
struct plat_serial8250_port *p = &(uart8250_data[i]);
struct bcma_serial_port *bcma_port;
bcma_port = &(cc->serial_ports[i]);
p->mapbase = (unsigned int) bcma_port->regs;
p->membase = (void *) bcma_port->regs;
p->irq = bcma_port->irq + 2;
p->uartclk = bcma_port->baud_base;
p->regshift = bcma_port->reg_shift;
p->iotype = UPIO_MEM;
p->flags = UPF_BOOT_AUTOCONF | UPF_SHARE_IRQ;
}
return platform_device_register(&uart8250_device);
}
#endif
static int __init uart8250_init(void)
{
switch (bcm47xx_bus_type) {
#ifdef CONFIG_BCM47XX_SSB
case BCM47XX_BUS_TYPE_SSB:
return uart8250_init_ssb();
#endif
#ifdef CONFIG_BCM47XX_BCMA
case BCM47XX_BUS_TYPE_BCMA:
return uart8250_init_bcma();
#endif
}
return -EINVAL;
}
module_init(uart8250_init);
MODULE_AUTHOR("Aurelien Jarno <aurelien@aurel32.net>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("8250 UART probe driver for the BCM47XX platforms");
| gpl-2.0 |
ion-storm/L-Kernel-Mako | drivers/net/wireless/rtlwifi/rtl8192cu/table.c | 7557 | 41168 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "table.h"
u32 RTL8192CUPHY_REG_2TARRAY[RTL8192CUPHY_REG_2TARRAY_LENGTH] = {
0x024, 0x0011800f,
0x028, 0x00ffdb83,
0x800, 0x80040002,
0x804, 0x00000003,
0x808, 0x0000fc00,
0x80c, 0x0000000a,
0x810, 0x10005388,
0x814, 0x020c3d10,
0x818, 0x02200385,
0x81c, 0x00000000,
0x820, 0x01000100,
0x824, 0x00390004,
0x828, 0x01000100,
0x82c, 0x00390004,
0x830, 0x27272727,
0x834, 0x27272727,
0x838, 0x27272727,
0x83c, 0x27272727,
0x840, 0x00010000,
0x844, 0x00010000,
0x848, 0x27272727,
0x84c, 0x27272727,
0x850, 0x00000000,
0x854, 0x00000000,
0x858, 0x569a569a,
0x85c, 0x0c1b25a4,
0x860, 0x66e60230,
0x864, 0x061f0130,
0x868, 0x27272727,
0x86c, 0x2b2b2b27,
0x870, 0x07000700,
0x874, 0x22184000,
0x878, 0x08080808,
0x87c, 0x00000000,
0x880, 0xc0083070,
0x884, 0x000004d5,
0x888, 0x00000000,
0x88c, 0xcc0000c0,
0x890, 0x00000800,
0x894, 0xfffffffe,
0x898, 0x40302010,
0x89c, 0x00706050,
0x900, 0x00000000,
0x904, 0x00000023,
0x908, 0x00000000,
0x90c, 0x81121313,
0xa00, 0x00d047c8,
0xa04, 0x80ff000c,
0xa08, 0x8c838300,
0xa0c, 0x2e68120f,
0xa10, 0x9500bb78,
0xa14, 0x11144028,
0xa18, 0x00881117,
0xa1c, 0x89140f00,
0xa20, 0x1a1b0000,
0xa24, 0x090e1317,
0xa28, 0x00000204,
0xa2c, 0x00d30000,
0xa70, 0x101fbf00,
0xa74, 0x00000007,
0xc00, 0x48071d40,
0xc04, 0x03a05633,
0xc08, 0x000000e4,
0xc0c, 0x6c6c6c6c,
0xc10, 0x08800000,
0xc14, 0x40000100,
0xc18, 0x08800000,
0xc1c, 0x40000100,
0xc20, 0x00000000,
0xc24, 0x00000000,
0xc28, 0x00000000,
0xc2c, 0x00000000,
0xc30, 0x69e9ac44,
0xc34, 0x469652cf,
0xc38, 0x49795994,
0xc3c, 0x0a97971c,
0xc40, 0x1f7c403f,
0xc44, 0x000100b7,
0xc48, 0xec020107,
0xc4c, 0x007f037f,
0xc50, 0x6954341e,
0xc54, 0x43bc0094,
0xc58, 0x6954341e,
0xc5c, 0x433c0094,
0xc60, 0x00000000,
0xc64, 0x5116848b,
0xc68, 0x47c00bff,
0xc6c, 0x00000036,
0xc70, 0x2c7f000d,
0xc74, 0x0186115b,
0xc78, 0x0000001f,
0xc7c, 0x00b99612,
0xc80, 0x40000100,
0xc84, 0x20f60000,
0xc88, 0x40000100,
0xc8c, 0x20200000,
0xc90, 0x00121820,
0xc94, 0x00000000,
0xc98, 0x00121820,
0xc9c, 0x00007f7f,
0xca0, 0x00000000,
0xca4, 0x00000080,
0xca8, 0x00000000,
0xcac, 0x00000000,
0xcb0, 0x00000000,
0xcb4, 0x00000000,
0xcb8, 0x00000000,
0xcbc, 0x28000000,
0xcc0, 0x00000000,
0xcc4, 0x00000000,
0xcc8, 0x00000000,
0xccc, 0x00000000,
0xcd0, 0x00000000,
0xcd4, 0x00000000,
0xcd8, 0x64b22427,
0xcdc, 0x00766932,
0xce0, 0x00222222,
0xce4, 0x00000000,
0xce8, 0x37644302,
0xcec, 0x2f97d40c,
0xd00, 0x00080740,
0xd04, 0x00020403,
0xd08, 0x0000907f,
0xd0c, 0x20010201,
0xd10, 0xa0633333,
0xd14, 0x3333bc43,
0xd18, 0x7a8f5b6b,
0xd2c, 0xcc979975,
0xd30, 0x00000000,
0xd34, 0x80608000,
0xd38, 0x00000000,
0xd3c, 0x00027293,
0xd40, 0x00000000,
0xd44, 0x00000000,
0xd48, 0x00000000,
0xd4c, 0x00000000,
0xd50, 0x6437140a,
0xd54, 0x00000000,
0xd58, 0x00000000,
0xd5c, 0x30032064,
0xd60, 0x4653de68,
0xd64, 0x04518a3c,
0xd68, 0x00002101,
0xd6c, 0x2a201c16,
0xd70, 0x1812362e,
0xd74, 0x322c2220,
0xd78, 0x000e3c24,
0xe00, 0x2a2a2a2a,
0xe04, 0x2a2a2a2a,
0xe08, 0x03902a2a,
0xe10, 0x2a2a2a2a,
0xe14, 0x2a2a2a2a,
0xe18, 0x2a2a2a2a,
0xe1c, 0x2a2a2a2a,
0xe28, 0x00000000,
0xe30, 0x1000dc1f,
0xe34, 0x10008c1f,
0xe38, 0x02140102,
0xe3c, 0x681604c2,
0xe40, 0x01007c00,
0xe44, 0x01004800,
0xe48, 0xfb000000,
0xe4c, 0x000028d1,
0xe50, 0x1000dc1f,
0xe54, 0x10008c1f,
0xe58, 0x02140102,
0xe5c, 0x28160d05,
0xe60, 0x00000010,
0xe68, 0x001b25a4,
0xe6c, 0x63db25a4,
0xe70, 0x63db25a4,
0xe74, 0x0c1b25a4,
0xe78, 0x0c1b25a4,
0xe7c, 0x0c1b25a4,
0xe80, 0x0c1b25a4,
0xe84, 0x63db25a4,
0xe88, 0x0c1b25a4,
0xe8c, 0x63db25a4,
0xed0, 0x63db25a4,
0xed4, 0x63db25a4,
0xed8, 0x63db25a4,
0xedc, 0x001b25a4,
0xee0, 0x001b25a4,
0xeec, 0x6fdb25a4,
0xf14, 0x00000003,
0xf4c, 0x00000000,
0xf00, 0x00000300,
};
u32 RTL8192CUPHY_REG_1TARRAY[RTL8192CUPHY_REG_1TARRAY_LENGTH] = {
0x024, 0x0011800f,
0x028, 0x00ffdb83,
0x800, 0x80040000,
0x804, 0x00000001,
0x808, 0x0000fc00,
0x80c, 0x0000000a,
0x810, 0x10005388,
0x814, 0x020c3d10,
0x818, 0x02200385,
0x81c, 0x00000000,
0x820, 0x01000100,
0x824, 0x00390004,
0x828, 0x00000000,
0x82c, 0x00000000,
0x830, 0x00000000,
0x834, 0x00000000,
0x838, 0x00000000,
0x83c, 0x00000000,
0x840, 0x00010000,
0x844, 0x00000000,
0x848, 0x00000000,
0x84c, 0x00000000,
0x850, 0x00000000,
0x854, 0x00000000,
0x858, 0x569a569a,
0x85c, 0x001b25a4,
0x860, 0x66e60230,
0x864, 0x061f0130,
0x868, 0x00000000,
0x86c, 0x32323200,
0x870, 0x07000700,
0x874, 0x22004000,
0x878, 0x00000808,
0x87c, 0x00000000,
0x880, 0xc0083070,
0x884, 0x000004d5,
0x888, 0x00000000,
0x88c, 0xccc000c0,
0x890, 0x00000800,
0x894, 0xfffffffe,
0x898, 0x40302010,
0x89c, 0x00706050,
0x900, 0x00000000,
0x904, 0x00000023,
0x908, 0x00000000,
0x90c, 0x81121111,
0xa00, 0x00d047c8,
0xa04, 0x80ff000c,
0xa08, 0x8c838300,
0xa0c, 0x2e68120f,
0xa10, 0x9500bb78,
0xa14, 0x11144028,
0xa18, 0x00881117,
0xa1c, 0x89140f00,
0xa20, 0x1a1b0000,
0xa24, 0x090e1317,
0xa28, 0x00000204,
0xa2c, 0x00d30000,
0xa70, 0x101fbf00,
0xa74, 0x00000007,
0xc00, 0x48071d40,
0xc04, 0x03a05611,
0xc08, 0x000000e4,
0xc0c, 0x6c6c6c6c,
0xc10, 0x08800000,
0xc14, 0x40000100,
0xc18, 0x08800000,
0xc1c, 0x40000100,
0xc20, 0x00000000,
0xc24, 0x00000000,
0xc28, 0x00000000,
0xc2c, 0x00000000,
0xc30, 0x69e9ac44,
0xc34, 0x469652cf,
0xc38, 0x49795994,
0xc3c, 0x0a97971c,
0xc40, 0x1f7c403f,
0xc44, 0x000100b7,
0xc48, 0xec020107,
0xc4c, 0x007f037f,
0xc50, 0x6954341e,
0xc54, 0x43bc0094,
0xc58, 0x6954341e,
0xc5c, 0x433c0094,
0xc60, 0x00000000,
0xc64, 0x5116848b,
0xc68, 0x47c00bff,
0xc6c, 0x00000036,
0xc70, 0x2c7f000d,
0xc74, 0x018610db,
0xc78, 0x0000001f,
0xc7c, 0x00b91612,
0xc80, 0x40000100,
0xc84, 0x20f60000,
0xc88, 0x40000100,
0xc8c, 0x20200000,
0xc90, 0x00121820,
0xc94, 0x00000000,
0xc98, 0x00121820,
0xc9c, 0x00007f7f,
0xca0, 0x00000000,
0xca4, 0x00000080,
0xca8, 0x00000000,
0xcac, 0x00000000,
0xcb0, 0x00000000,
0xcb4, 0x00000000,
0xcb8, 0x00000000,
0xcbc, 0x28000000,
0xcc0, 0x00000000,
0xcc4, 0x00000000,
0xcc8, 0x00000000,
0xccc, 0x00000000,
0xcd0, 0x00000000,
0xcd4, 0x00000000,
0xcd8, 0x64b22427,
0xcdc, 0x00766932,
0xce0, 0x00222222,
0xce4, 0x00000000,
0xce8, 0x37644302,
0xcec, 0x2f97d40c,
0xd00, 0x00080740,
0xd04, 0x00020401,
0xd08, 0x0000907f,
0xd0c, 0x20010201,
0xd10, 0xa0633333,
0xd14, 0x3333bc43,
0xd18, 0x7a8f5b6b,
0xd2c, 0xcc979975,
0xd30, 0x00000000,
0xd34, 0x80608000,
0xd38, 0x00000000,
0xd3c, 0x00027293,
0xd40, 0x00000000,
0xd44, 0x00000000,
0xd48, 0x00000000,
0xd4c, 0x00000000,
0xd50, 0x6437140a,
0xd54, 0x00000000,
0xd58, 0x00000000,
0xd5c, 0x30032064,
0xd60, 0x4653de68,
0xd64, 0x04518a3c,
0xd68, 0x00002101,
0xd6c, 0x2a201c16,
0xd70, 0x1812362e,
0xd74, 0x322c2220,
0xd78, 0x000e3c24,
0xe00, 0x2a2a2a2a,
0xe04, 0x2a2a2a2a,
0xe08, 0x03902a2a,
0xe10, 0x2a2a2a2a,
0xe14, 0x2a2a2a2a,
0xe18, 0x2a2a2a2a,
0xe1c, 0x2a2a2a2a,
0xe28, 0x00000000,
0xe30, 0x1000dc1f,
0xe34, 0x10008c1f,
0xe38, 0x02140102,
0xe3c, 0x681604c2,
0xe40, 0x01007c00,
0xe44, 0x01004800,
0xe48, 0xfb000000,
0xe4c, 0x000028d1,
0xe50, 0x1000dc1f,
0xe54, 0x10008c1f,
0xe58, 0x02140102,
0xe5c, 0x28160d05,
0xe60, 0x00000008,
0xe68, 0x001b25a4,
0xe6c, 0x631b25a0,
0xe70, 0x631b25a0,
0xe74, 0x081b25a0,
0xe78, 0x081b25a0,
0xe7c, 0x081b25a0,
0xe80, 0x081b25a0,
0xe84, 0x631b25a0,
0xe88, 0x081b25a0,
0xe8c, 0x631b25a0,
0xed0, 0x631b25a0,
0xed4, 0x631b25a0,
0xed8, 0x631b25a0,
0xedc, 0x001b25a0,
0xee0, 0x001b25a0,
0xeec, 0x6b1b25a0,
0xf14, 0x00000003,
0xf4c, 0x00000000,
0xf00, 0x00000300,
};
u32 RTL8192CUPHY_REG_ARRAY_PG[RTL8192CUPHY_REG_ARRAY_PGLENGTH] = {
0xe00, 0xffffffff, 0x07090c0c,
0xe04, 0xffffffff, 0x01020405,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x0b0c0c0e,
0xe14, 0xffffffff, 0x01030506,
0xe18, 0xffffffff, 0x0b0c0d0e,
0xe1c, 0xffffffff, 0x01030509,
0x830, 0xffffffff, 0x07090c0c,
0x834, 0xffffffff, 0x01020405,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x0b0c0d0e,
0x848, 0xffffffff, 0x01030509,
0x84c, 0xffffffff, 0x0b0c0d0e,
0x868, 0xffffffff, 0x01030509,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x04040404,
0xe04, 0xffffffff, 0x00020204,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x06060606,
0xe14, 0xffffffff, 0x00020406,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x04040404,
0x834, 0xffffffff, 0x00020204,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x06060606,
0x848, 0xffffffff, 0x00020406,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x04040404,
0xe04, 0xffffffff, 0x00020204,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x04040404,
0x834, 0xffffffff, 0x00020204,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
};
u32 RTL8192CURADIOA_2TARRAY[RTL8192CURADIOA_2TARRAYLENGTH] = {
0x000, 0x00030159,
0x001, 0x00031284,
0x002, 0x00098000,
0x003, 0x00018c63,
0x004, 0x000210e7,
0x009, 0x0002044f,
0x00a, 0x0001adb1,
0x00b, 0x00054867,
0x00c, 0x0008992e,
0x00d, 0x0000e52c,
0x00e, 0x00039ce7,
0x00f, 0x00000451,
0x019, 0x00000000,
0x01a, 0x00010255,
0x01b, 0x00060a00,
0x01c, 0x000fc378,
0x01d, 0x000a1250,
0x01e, 0x0004445f,
0x01f, 0x00080001,
0x020, 0x0000b614,
0x021, 0x0006c000,
0x022, 0x00000000,
0x023, 0x00001558,
0x024, 0x00000060,
0x025, 0x00000483,
0x026, 0x0004f000,
0x027, 0x000ec7d9,
0x028, 0x000577c0,
0x029, 0x00004783,
0x02a, 0x00000001,
0x02b, 0x00021334,
0x02a, 0x00000000,
0x02b, 0x00000054,
0x02a, 0x00000001,
0x02b, 0x00000808,
0x02b, 0x00053333,
0x02c, 0x0000000c,
0x02a, 0x00000002,
0x02b, 0x00000808,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000003,
0x02b, 0x00000808,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000004,
0x02b, 0x00000808,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x00000005,
0x02b, 0x00000808,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x00000006,
0x02b, 0x00000709,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000007,
0x02b, 0x00000709,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000008,
0x02b, 0x0000060a,
0x02b, 0x0004b333,
0x02c, 0x0000000d,
0x02a, 0x00000009,
0x02b, 0x0000060a,
0x02b, 0x00053333,
0x02c, 0x0000000d,
0x02a, 0x0000000a,
0x02b, 0x0000060a,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x0000000b,
0x02b, 0x0000060a,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x0000000c,
0x02b, 0x0000060a,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x0000000d,
0x02b, 0x0000060a,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x0000000e,
0x02b, 0x0000050b,
0x02b, 0x00066666,
0x02c, 0x0000001a,
0x02a, 0x000e0000,
0x010, 0x0004000f,
0x011, 0x000e31fc,
0x010, 0x0006000f,
0x011, 0x000ff9f8,
0x010, 0x0002000f,
0x011, 0x000203f9,
0x010, 0x0003000f,
0x011, 0x000ff500,
0x010, 0x00000000,
0x011, 0x00000000,
0x010, 0x0008000f,
0x011, 0x0003f100,
0x010, 0x0009000f,
0x011, 0x00023100,
0x012, 0x00032000,
0x012, 0x00071000,
0x012, 0x000b0000,
0x012, 0x000fc000,
0x013, 0x000287af,
0x013, 0x000244b7,
0x013, 0x000204ab,
0x013, 0x0001c49f,
0x013, 0x00018493,
0x013, 0x00014297,
0x013, 0x00010295,
0x013, 0x0000c298,
0x013, 0x0000819c,
0x013, 0x000040a8,
0x013, 0x0000001c,
0x014, 0x0001944c,
0x014, 0x00059444,
0x014, 0x0009944c,
0x014, 0x000d9444,
0x015, 0x0000f424,
0x015, 0x0004f424,
0x015, 0x0008f424,
0x015, 0x000cf424,
0x016, 0x000e0330,
0x016, 0x000a0330,
0x016, 0x00060330,
0x016, 0x00020330,
0x000, 0x00010159,
0x018, 0x0000f401,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01f, 0x00080003,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01e, 0x00044457,
0x01f, 0x00080000,
0x000, 0x00030159,
};
u32 RTL8192CU_RADIOB_2TARRAY[RTL8192CURADIOB_2TARRAYLENGTH] = {
0x000, 0x00030159,
0x001, 0x00031284,
0x002, 0x00098000,
0x003, 0x00018c63,
0x004, 0x000210e7,
0x009, 0x0002044f,
0x00a, 0x0001adb1,
0x00b, 0x00054867,
0x00c, 0x0008992e,
0x00d, 0x0000e52c,
0x00e, 0x00039ce7,
0x00f, 0x00000451,
0x012, 0x00032000,
0x012, 0x00071000,
0x012, 0x000b0000,
0x012, 0x000fc000,
0x013, 0x000287af,
0x013, 0x000244b7,
0x013, 0x000204ab,
0x013, 0x0001c49f,
0x013, 0x00018493,
0x013, 0x00014297,
0x013, 0x00010295,
0x013, 0x0000c298,
0x013, 0x0000819c,
0x013, 0x000040a8,
0x013, 0x0000001c,
0x014, 0x0001944c,
0x014, 0x00059444,
0x014, 0x0009944c,
0x014, 0x000d9444,
0x015, 0x0000f424,
0x015, 0x0004f424,
0x015, 0x0008f424,
0x015, 0x000cf424,
0x016, 0x000e0330,
0x016, 0x000a0330,
0x016, 0x00060330,
0x016, 0x00020330,
};
u32 RTL8192CU_RADIOA_1TARRAY[RTL8192CURADIOA_1TARRAYLENGTH] = {
0x000, 0x00030159,
0x001, 0x00031284,
0x002, 0x00098000,
0x003, 0x00018c63,
0x004, 0x000210e7,
0x009, 0x0002044f,
0x00a, 0x0001adb1,
0x00b, 0x00054867,
0x00c, 0x0008992e,
0x00d, 0x0000e52c,
0x00e, 0x00039ce7,
0x00f, 0x00000451,
0x019, 0x00000000,
0x01a, 0x00010255,
0x01b, 0x00060a00,
0x01c, 0x000fc378,
0x01d, 0x000a1250,
0x01e, 0x0004445f,
0x01f, 0x00080001,
0x020, 0x0000b614,
0x021, 0x0006c000,
0x022, 0x00000000,
0x023, 0x00001558,
0x024, 0x00000060,
0x025, 0x00000483,
0x026, 0x0004f000,
0x027, 0x000ec7d9,
0x028, 0x000577c0,
0x029, 0x00004783,
0x02a, 0x00000001,
0x02b, 0x00021334,
0x02a, 0x00000000,
0x02b, 0x00000054,
0x02a, 0x00000001,
0x02b, 0x00000808,
0x02b, 0x00053333,
0x02c, 0x0000000c,
0x02a, 0x00000002,
0x02b, 0x00000808,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000003,
0x02b, 0x00000808,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000004,
0x02b, 0x00000808,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x00000005,
0x02b, 0x00000808,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x00000006,
0x02b, 0x00000709,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000007,
0x02b, 0x00000709,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000008,
0x02b, 0x0000060a,
0x02b, 0x0004b333,
0x02c, 0x0000000d,
0x02a, 0x00000009,
0x02b, 0x0000060a,
0x02b, 0x00053333,
0x02c, 0x0000000d,
0x02a, 0x0000000a,
0x02b, 0x0000060a,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x0000000b,
0x02b, 0x0000060a,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x0000000c,
0x02b, 0x0000060a,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x0000000d,
0x02b, 0x0000060a,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x0000000e,
0x02b, 0x0000050b,
0x02b, 0x00066666,
0x02c, 0x0000001a,
0x02a, 0x000e0000,
0x010, 0x0004000f,
0x011, 0x000e31fc,
0x010, 0x0006000f,
0x011, 0x000ff9f8,
0x010, 0x0002000f,
0x011, 0x000203f9,
0x010, 0x0003000f,
0x011, 0x000ff500,
0x010, 0x00000000,
0x011, 0x00000000,
0x010, 0x0008000f,
0x011, 0x0003f100,
0x010, 0x0009000f,
0x011, 0x00023100,
0x012, 0x00032000,
0x012, 0x00071000,
0x012, 0x000b0000,
0x012, 0x000fc000,
0x013, 0x000287b3,
0x013, 0x000244b7,
0x013, 0x000204ab,
0x013, 0x0001c49f,
0x013, 0x00018493,
0x013, 0x0001429b,
0x013, 0x00010299,
0x013, 0x0000c29c,
0x013, 0x000081a0,
0x013, 0x000040ac,
0x013, 0x00000020,
0x014, 0x0001944c,
0x014, 0x00059444,
0x014, 0x0009944c,
0x014, 0x000d9444,
0x015, 0x0000f405,
0x015, 0x0004f405,
0x015, 0x0008f405,
0x015, 0x000cf405,
0x016, 0x000e0330,
0x016, 0x000a0330,
0x016, 0x00060330,
0x016, 0x00020330,
0x000, 0x00010159,
0x018, 0x0000f401,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01f, 0x00080003,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01e, 0x00044457,
0x01f, 0x00080000,
0x000, 0x00030159,
};
u32 RTL8192CU_RADIOB_1TARRAY[RTL8192CURADIOB_1TARRAYLENGTH] = {
0x0,
};
u32 RTL8192CUMAC_2T_ARRAY[RTL8192CUMAC_2T_ARRAYLENGTH] = {
0x420, 0x00000080,
0x423, 0x00000000,
0x430, 0x00000000,
0x431, 0x00000000,
0x432, 0x00000000,
0x433, 0x00000001,
0x434, 0x00000004,
0x435, 0x00000005,
0x436, 0x00000006,
0x437, 0x00000007,
0x438, 0x00000000,
0x439, 0x00000000,
0x43a, 0x00000000,
0x43b, 0x00000001,
0x43c, 0x00000004,
0x43d, 0x00000005,
0x43e, 0x00000006,
0x43f, 0x00000007,
0x440, 0x0000005d,
0x441, 0x00000001,
0x442, 0x00000000,
0x444, 0x00000015,
0x445, 0x000000f0,
0x446, 0x0000000f,
0x447, 0x00000000,
0x458, 0x00000041,
0x459, 0x000000a8,
0x45a, 0x00000072,
0x45b, 0x000000b9,
0x460, 0x00000066,
0x461, 0x00000066,
0x462, 0x00000008,
0x463, 0x00000003,
0x4c8, 0x000000ff,
0x4c9, 0x00000008,
0x4cc, 0x000000ff,
0x4cd, 0x000000ff,
0x4ce, 0x00000001,
0x500, 0x00000026,
0x501, 0x000000a2,
0x502, 0x0000002f,
0x503, 0x00000000,
0x504, 0x00000028,
0x505, 0x000000a3,
0x506, 0x0000005e,
0x507, 0x00000000,
0x508, 0x0000002b,
0x509, 0x000000a4,
0x50a, 0x0000005e,
0x50b, 0x00000000,
0x50c, 0x0000004f,
0x50d, 0x000000a4,
0x50e, 0x00000000,
0x50f, 0x00000000,
0x512, 0x0000001c,
0x514, 0x0000000a,
0x515, 0x00000010,
0x516, 0x0000000a,
0x517, 0x00000010,
0x51a, 0x00000016,
0x524, 0x0000000f,
0x525, 0x0000004f,
0x546, 0x00000040,
0x547, 0x00000000,
0x550, 0x00000010,
0x551, 0x00000010,
0x559, 0x00000002,
0x55a, 0x00000002,
0x55d, 0x000000ff,
0x605, 0x00000030,
0x608, 0x0000000e,
0x609, 0x0000002a,
0x652, 0x00000020,
0x63c, 0x0000000a,
0x63d, 0x0000000e,
0x63e, 0x0000000a,
0x63f, 0x0000000e,
0x66e, 0x00000005,
0x700, 0x00000021,
0x701, 0x00000043,
0x702, 0x00000065,
0x703, 0x00000087,
0x708, 0x00000021,
0x709, 0x00000043,
0x70a, 0x00000065,
0x70b, 0x00000087,
};
u32 RTL8192CUAGCTAB_2TARRAY[RTL8192CUAGCTAB_2TARRAYLENGTH] = {
0xc78, 0x7b000001,
0xc78, 0x7b010001,
0xc78, 0x7b020001,
0xc78, 0x7b030001,
0xc78, 0x7b040001,
0xc78, 0x7b050001,
0xc78, 0x7a060001,
0xc78, 0x79070001,
0xc78, 0x78080001,
0xc78, 0x77090001,
0xc78, 0x760a0001,
0xc78, 0x750b0001,
0xc78, 0x740c0001,
0xc78, 0x730d0001,
0xc78, 0x720e0001,
0xc78, 0x710f0001,
0xc78, 0x70100001,
0xc78, 0x6f110001,
0xc78, 0x6e120001,
0xc78, 0x6d130001,
0xc78, 0x6c140001,
0xc78, 0x6b150001,
0xc78, 0x6a160001,
0xc78, 0x69170001,
0xc78, 0x68180001,
0xc78, 0x67190001,
0xc78, 0x661a0001,
0xc78, 0x651b0001,
0xc78, 0x641c0001,
0xc78, 0x631d0001,
0xc78, 0x621e0001,
0xc78, 0x611f0001,
0xc78, 0x60200001,
0xc78, 0x49210001,
0xc78, 0x48220001,
0xc78, 0x47230001,
0xc78, 0x46240001,
0xc78, 0x45250001,
0xc78, 0x44260001,
0xc78, 0x43270001,
0xc78, 0x42280001,
0xc78, 0x41290001,
0xc78, 0x402a0001,
0xc78, 0x262b0001,
0xc78, 0x252c0001,
0xc78, 0x242d0001,
0xc78, 0x232e0001,
0xc78, 0x222f0001,
0xc78, 0x21300001,
0xc78, 0x20310001,
0xc78, 0x06320001,
0xc78, 0x05330001,
0xc78, 0x04340001,
0xc78, 0x03350001,
0xc78, 0x02360001,
0xc78, 0x01370001,
0xc78, 0x00380001,
0xc78, 0x00390001,
0xc78, 0x003a0001,
0xc78, 0x003b0001,
0xc78, 0x003c0001,
0xc78, 0x003d0001,
0xc78, 0x003e0001,
0xc78, 0x003f0001,
0xc78, 0x7b400001,
0xc78, 0x7b410001,
0xc78, 0x7b420001,
0xc78, 0x7b430001,
0xc78, 0x7b440001,
0xc78, 0x7b450001,
0xc78, 0x7a460001,
0xc78, 0x79470001,
0xc78, 0x78480001,
0xc78, 0x77490001,
0xc78, 0x764a0001,
0xc78, 0x754b0001,
0xc78, 0x744c0001,
0xc78, 0x734d0001,
0xc78, 0x724e0001,
0xc78, 0x714f0001,
0xc78, 0x70500001,
0xc78, 0x6f510001,
0xc78, 0x6e520001,
0xc78, 0x6d530001,
0xc78, 0x6c540001,
0xc78, 0x6b550001,
0xc78, 0x6a560001,
0xc78, 0x69570001,
0xc78, 0x68580001,
0xc78, 0x67590001,
0xc78, 0x665a0001,
0xc78, 0x655b0001,
0xc78, 0x645c0001,
0xc78, 0x635d0001,
0xc78, 0x625e0001,
0xc78, 0x615f0001,
0xc78, 0x60600001,
0xc78, 0x49610001,
0xc78, 0x48620001,
0xc78, 0x47630001,
0xc78, 0x46640001,
0xc78, 0x45650001,
0xc78, 0x44660001,
0xc78, 0x43670001,
0xc78, 0x42680001,
0xc78, 0x41690001,
0xc78, 0x406a0001,
0xc78, 0x266b0001,
0xc78, 0x256c0001,
0xc78, 0x246d0001,
0xc78, 0x236e0001,
0xc78, 0x226f0001,
0xc78, 0x21700001,
0xc78, 0x20710001,
0xc78, 0x06720001,
0xc78, 0x05730001,
0xc78, 0x04740001,
0xc78, 0x03750001,
0xc78, 0x02760001,
0xc78, 0x01770001,
0xc78, 0x00780001,
0xc78, 0x00790001,
0xc78, 0x007a0001,
0xc78, 0x007b0001,
0xc78, 0x007c0001,
0xc78, 0x007d0001,
0xc78, 0x007e0001,
0xc78, 0x007f0001,
0xc78, 0x3800001e,
0xc78, 0x3801001e,
0xc78, 0x3802001e,
0xc78, 0x3803001e,
0xc78, 0x3804001e,
0xc78, 0x3805001e,
0xc78, 0x3806001e,
0xc78, 0x3807001e,
0xc78, 0x3808001e,
0xc78, 0x3c09001e,
0xc78, 0x3e0a001e,
0xc78, 0x400b001e,
0xc78, 0x440c001e,
0xc78, 0x480d001e,
0xc78, 0x4c0e001e,
0xc78, 0x500f001e,
0xc78, 0x5210001e,
0xc78, 0x5611001e,
0xc78, 0x5a12001e,
0xc78, 0x5e13001e,
0xc78, 0x6014001e,
0xc78, 0x6015001e,
0xc78, 0x6016001e,
0xc78, 0x6217001e,
0xc78, 0x6218001e,
0xc78, 0x6219001e,
0xc78, 0x621a001e,
0xc78, 0x621b001e,
0xc78, 0x621c001e,
0xc78, 0x621d001e,
0xc78, 0x621e001e,
0xc78, 0x621f001e,
};
u32 RTL8192CUAGCTAB_1TARRAY[RTL8192CUAGCTAB_1TARRAYLENGTH] = {
0xc78, 0x7b000001,
0xc78, 0x7b010001,
0xc78, 0x7b020001,
0xc78, 0x7b030001,
0xc78, 0x7b040001,
0xc78, 0x7b050001,
0xc78, 0x7a060001,
0xc78, 0x79070001,
0xc78, 0x78080001,
0xc78, 0x77090001,
0xc78, 0x760a0001,
0xc78, 0x750b0001,
0xc78, 0x740c0001,
0xc78, 0x730d0001,
0xc78, 0x720e0001,
0xc78, 0x710f0001,
0xc78, 0x70100001,
0xc78, 0x6f110001,
0xc78, 0x6e120001,
0xc78, 0x6d130001,
0xc78, 0x6c140001,
0xc78, 0x6b150001,
0xc78, 0x6a160001,
0xc78, 0x69170001,
0xc78, 0x68180001,
0xc78, 0x67190001,
0xc78, 0x661a0001,
0xc78, 0x651b0001,
0xc78, 0x641c0001,
0xc78, 0x631d0001,
0xc78, 0x621e0001,
0xc78, 0x611f0001,
0xc78, 0x60200001,
0xc78, 0x49210001,
0xc78, 0x48220001,
0xc78, 0x47230001,
0xc78, 0x46240001,
0xc78, 0x45250001,
0xc78, 0x44260001,
0xc78, 0x43270001,
0xc78, 0x42280001,
0xc78, 0x41290001,
0xc78, 0x402a0001,
0xc78, 0x262b0001,
0xc78, 0x252c0001,
0xc78, 0x242d0001,
0xc78, 0x232e0001,
0xc78, 0x222f0001,
0xc78, 0x21300001,
0xc78, 0x20310001,
0xc78, 0x06320001,
0xc78, 0x05330001,
0xc78, 0x04340001,
0xc78, 0x03350001,
0xc78, 0x02360001,
0xc78, 0x01370001,
0xc78, 0x00380001,
0xc78, 0x00390001,
0xc78, 0x003a0001,
0xc78, 0x003b0001,
0xc78, 0x003c0001,
0xc78, 0x003d0001,
0xc78, 0x003e0001,
0xc78, 0x003f0001,
0xc78, 0x7b400001,
0xc78, 0x7b410001,
0xc78, 0x7b420001,
0xc78, 0x7b430001,
0xc78, 0x7b440001,
0xc78, 0x7b450001,
0xc78, 0x7a460001,
0xc78, 0x79470001,
0xc78, 0x78480001,
0xc78, 0x77490001,
0xc78, 0x764a0001,
0xc78, 0x754b0001,
0xc78, 0x744c0001,
0xc78, 0x734d0001,
0xc78, 0x724e0001,
0xc78, 0x714f0001,
0xc78, 0x70500001,
0xc78, 0x6f510001,
0xc78, 0x6e520001,
0xc78, 0x6d530001,
0xc78, 0x6c540001,
0xc78, 0x6b550001,
0xc78, 0x6a560001,
0xc78, 0x69570001,
0xc78, 0x68580001,
0xc78, 0x67590001,
0xc78, 0x665a0001,
0xc78, 0x655b0001,
0xc78, 0x645c0001,
0xc78, 0x635d0001,
0xc78, 0x625e0001,
0xc78, 0x615f0001,
0xc78, 0x60600001,
0xc78, 0x49610001,
0xc78, 0x48620001,
0xc78, 0x47630001,
0xc78, 0x46640001,
0xc78, 0x45650001,
0xc78, 0x44660001,
0xc78, 0x43670001,
0xc78, 0x42680001,
0xc78, 0x41690001,
0xc78, 0x406a0001,
0xc78, 0x266b0001,
0xc78, 0x256c0001,
0xc78, 0x246d0001,
0xc78, 0x236e0001,
0xc78, 0x226f0001,
0xc78, 0x21700001,
0xc78, 0x20710001,
0xc78, 0x06720001,
0xc78, 0x05730001,
0xc78, 0x04740001,
0xc78, 0x03750001,
0xc78, 0x02760001,
0xc78, 0x01770001,
0xc78, 0x00780001,
0xc78, 0x00790001,
0xc78, 0x007a0001,
0xc78, 0x007b0001,
0xc78, 0x007c0001,
0xc78, 0x007d0001,
0xc78, 0x007e0001,
0xc78, 0x007f0001,
0xc78, 0x3800001e,
0xc78, 0x3801001e,
0xc78, 0x3802001e,
0xc78, 0x3803001e,
0xc78, 0x3804001e,
0xc78, 0x3805001e,
0xc78, 0x3806001e,
0xc78, 0x3807001e,
0xc78, 0x3808001e,
0xc78, 0x3c09001e,
0xc78, 0x3e0a001e,
0xc78, 0x400b001e,
0xc78, 0x440c001e,
0xc78, 0x480d001e,
0xc78, 0x4c0e001e,
0xc78, 0x500f001e,
0xc78, 0x5210001e,
0xc78, 0x5611001e,
0xc78, 0x5a12001e,
0xc78, 0x5e13001e,
0xc78, 0x6014001e,
0xc78, 0x6015001e,
0xc78, 0x6016001e,
0xc78, 0x6217001e,
0xc78, 0x6218001e,
0xc78, 0x6219001e,
0xc78, 0x621a001e,
0xc78, 0x621b001e,
0xc78, 0x621c001e,
0xc78, 0x621d001e,
0xc78, 0x621e001e,
0xc78, 0x621f001e,
};
u32 RTL8192CUPHY_REG_1T_HPArray[RTL8192CUPHY_REG_1T_HPArrayLength] = {
0x024, 0x0011800f,
0x028, 0x00ffdb83,
0x040, 0x000c0004,
0x800, 0x80040000,
0x804, 0x00000001,
0x808, 0x0000fc00,
0x80c, 0x0000000a,
0x810, 0x10005388,
0x814, 0x020c3d10,
0x818, 0x02200385,
0x81c, 0x00000000,
0x820, 0x01000100,
0x824, 0x00390204,
0x828, 0x00000000,
0x82c, 0x00000000,
0x830, 0x00000000,
0x834, 0x00000000,
0x838, 0x00000000,
0x83c, 0x00000000,
0x840, 0x00010000,
0x844, 0x00000000,
0x848, 0x00000000,
0x84c, 0x00000000,
0x850, 0x00000000,
0x854, 0x00000000,
0x858, 0x569a569a,
0x85c, 0x001b25a4,
0x860, 0x66e60230,
0x864, 0x061f0130,
0x868, 0x00000000,
0x86c, 0x20202000,
0x870, 0x03000300,
0x874, 0x22004000,
0x878, 0x00000808,
0x87c, 0x00ffc3f1,
0x880, 0xc0083070,
0x884, 0x000004d5,
0x888, 0x00000000,
0x88c, 0xccc000c0,
0x890, 0x00000800,
0x894, 0xfffffffe,
0x898, 0x40302010,
0x89c, 0x00706050,
0x900, 0x00000000,
0x904, 0x00000023,
0x908, 0x00000000,
0x90c, 0x81121111,
0xa00, 0x00d047c8,
0xa04, 0x80ff000c,
0xa08, 0x8c838300,
0xa0c, 0x2e68120f,
0xa10, 0x9500bb78,
0xa14, 0x11144028,
0xa18, 0x00881117,
0xa1c, 0x89140f00,
0xa20, 0x15160000,
0xa24, 0x070b0f12,
0xa28, 0x00000104,
0xa2c, 0x00d30000,
0xa70, 0x101fbf00,
0xa74, 0x00000007,
0xc00, 0x48071d40,
0xc04, 0x03a05611,
0xc08, 0x000000e4,
0xc0c, 0x6c6c6c6c,
0xc10, 0x08800000,
0xc14, 0x40000100,
0xc18, 0x08800000,
0xc1c, 0x40000100,
0xc20, 0x00000000,
0xc24, 0x00000000,
0xc28, 0x00000000,
0xc2c, 0x00000000,
0xc30, 0x69e9ac44,
0xc34, 0x469652cf,
0xc38, 0x49795994,
0xc3c, 0x0a97971c,
0xc40, 0x1f7c403f,
0xc44, 0x000100b7,
0xc48, 0xec020107,
0xc4c, 0x007f037f,
0xc50, 0x6954342e,
0xc54, 0x43bc0094,
0xc58, 0x6954342f,
0xc5c, 0x433c0094,
0xc60, 0x00000000,
0xc64, 0x5116848b,
0xc68, 0x47c00bff,
0xc6c, 0x00000036,
0xc70, 0x2c46000d,
0xc74, 0x018610db,
0xc78, 0x0000001f,
0xc7c, 0x00b91612,
0xc80, 0x24000090,
0xc84, 0x20f60000,
0xc88, 0x24000090,
0xc8c, 0x20200000,
0xc90, 0x00121820,
0xc94, 0x00000000,
0xc98, 0x00121820,
0xc9c, 0x00007f7f,
0xca0, 0x00000000,
0xca4, 0x00000080,
0xca8, 0x00000000,
0xcac, 0x00000000,
0xcb0, 0x00000000,
0xcb4, 0x00000000,
0xcb8, 0x00000000,
0xcbc, 0x28000000,
0xcc0, 0x00000000,
0xcc4, 0x00000000,
0xcc8, 0x00000000,
0xccc, 0x00000000,
0xcd0, 0x00000000,
0xcd4, 0x00000000,
0xcd8, 0x64b22427,
0xcdc, 0x00766932,
0xce0, 0x00222222,
0xce4, 0x00000000,
0xce8, 0x37644302,
0xcec, 0x2f97d40c,
0xd00, 0x00080740,
0xd04, 0x00020401,
0xd08, 0x0000907f,
0xd0c, 0x20010201,
0xd10, 0xa0633333,
0xd14, 0x3333bc43,
0xd18, 0x7a8f5b6b,
0xd2c, 0xcc979975,
0xd30, 0x00000000,
0xd34, 0x80608000,
0xd38, 0x00000000,
0xd3c, 0x00027293,
0xd40, 0x00000000,
0xd44, 0x00000000,
0xd48, 0x00000000,
0xd4c, 0x00000000,
0xd50, 0x6437140a,
0xd54, 0x00000000,
0xd58, 0x00000000,
0xd5c, 0x30032064,
0xd60, 0x4653de68,
0xd64, 0x04518a3c,
0xd68, 0x00002101,
0xd6c, 0x2a201c16,
0xd70, 0x1812362e,
0xd74, 0x322c2220,
0xd78, 0x000e3c24,
0xe00, 0x24242424,
0xe04, 0x24242424,
0xe08, 0x03902024,
0xe10, 0x24242424,
0xe14, 0x24242424,
0xe18, 0x24242424,
0xe1c, 0x24242424,
0xe28, 0x00000000,
0xe30, 0x1000dc1f,
0xe34, 0x10008c1f,
0xe38, 0x02140102,
0xe3c, 0x681604c2,
0xe40, 0x01007c00,
0xe44, 0x01004800,
0xe48, 0xfb000000,
0xe4c, 0x000028d1,
0xe50, 0x1000dc1f,
0xe54, 0x10008c1f,
0xe58, 0x02140102,
0xe5c, 0x28160d05,
0xe60, 0x00000008,
0xe68, 0x001b25a4,
0xe6c, 0x631b25a0,
0xe70, 0x631b25a0,
0xe74, 0x081b25a0,
0xe78, 0x081b25a0,
0xe7c, 0x081b25a0,
0xe80, 0x081b25a0,
0xe84, 0x631b25a0,
0xe88, 0x081b25a0,
0xe8c, 0x631b25a0,
0xed0, 0x631b25a0,
0xed4, 0x631b25a0,
0xed8, 0x631b25a0,
0xedc, 0x001b25a0,
0xee0, 0x001b25a0,
0xeec, 0x6b1b25a0,
0xee8, 0x31555448,
0xf14, 0x00000003,
0xf4c, 0x00000000,
0xf00, 0x00000300,
};
u32 RTL8192CUPHY_REG_Array_PG_HP[RTL8192CUPHY_REG_Array_PG_HPLength] = {
0xe00, 0xffffffff, 0x06080808,
0xe04, 0xffffffff, 0x00040406,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x04060608,
0xe14, 0xffffffff, 0x00020204,
0xe18, 0xffffffff, 0x04060608,
0xe1c, 0xffffffff, 0x00020204,
0x830, 0xffffffff, 0x06080808,
0x834, 0xffffffff, 0x00040406,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x04060608,
0x848, 0xffffffff, 0x00020204,
0x84c, 0xffffffff, 0x04060608,
0x868, 0xffffffff, 0x00020204,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
0xe00, 0xffffffff, 0x00000000,
0xe04, 0xffffffff, 0x00000000,
0xe08, 0x0000ff00, 0x00000000,
0x86c, 0xffffff00, 0x00000000,
0xe10, 0xffffffff, 0x00000000,
0xe14, 0xffffffff, 0x00000000,
0xe18, 0xffffffff, 0x00000000,
0xe1c, 0xffffffff, 0x00000000,
0x830, 0xffffffff, 0x00000000,
0x834, 0xffffffff, 0x00000000,
0x838, 0xffffff00, 0x00000000,
0x86c, 0x000000ff, 0x00000000,
0x83c, 0xffffffff, 0x00000000,
0x848, 0xffffffff, 0x00000000,
0x84c, 0xffffffff, 0x00000000,
0x868, 0xffffffff, 0x00000000,
};
u32 RTL8192CURadioA_1T_HPArray[RTL8192CURadioA_1T_HPArrayLength] = {
0x000, 0x00030159,
0x001, 0x00031284,
0x002, 0x00098000,
0x003, 0x00018c63,
0x004, 0x000210e7,
0x009, 0x0002044f,
0x00a, 0x0001adb0,
0x00b, 0x00054867,
0x00c, 0x0008992e,
0x00d, 0x0000e529,
0x00e, 0x00039ce7,
0x00f, 0x00000451,
0x019, 0x00000000,
0x01a, 0x00000255,
0x01b, 0x00060a00,
0x01c, 0x000fc378,
0x01d, 0x000a1250,
0x01e, 0x0004445f,
0x01f, 0x00080001,
0x020, 0x0000b614,
0x021, 0x0006c000,
0x022, 0x0000083c,
0x023, 0x00001558,
0x024, 0x00000060,
0x025, 0x00000483,
0x026, 0x0004f000,
0x027, 0x000ec7d9,
0x028, 0x000977c0,
0x029, 0x00004783,
0x02a, 0x00000001,
0x02b, 0x00021334,
0x02a, 0x00000000,
0x02b, 0x00000054,
0x02a, 0x00000001,
0x02b, 0x00000808,
0x02b, 0x00053333,
0x02c, 0x0000000c,
0x02a, 0x00000002,
0x02b, 0x00000808,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000003,
0x02b, 0x00000808,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000004,
0x02b, 0x00000808,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x00000005,
0x02b, 0x00000808,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x00000006,
0x02b, 0x00000709,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x00000007,
0x02b, 0x00000709,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x00000008,
0x02b, 0x0000060a,
0x02b, 0x0004b333,
0x02c, 0x0000000d,
0x02a, 0x00000009,
0x02b, 0x0000060a,
0x02b, 0x00053333,
0x02c, 0x0000000d,
0x02a, 0x0000000a,
0x02b, 0x0000060a,
0x02b, 0x0005b333,
0x02c, 0x0000000d,
0x02a, 0x0000000b,
0x02b, 0x0000060a,
0x02b, 0x00063333,
0x02c, 0x0000000d,
0x02a, 0x0000000c,
0x02b, 0x0000060a,
0x02b, 0x0006b333,
0x02c, 0x0000000d,
0x02a, 0x0000000d,
0x02b, 0x0000060a,
0x02b, 0x00073333,
0x02c, 0x0000000d,
0x02a, 0x0000000e,
0x02b, 0x0000050b,
0x02b, 0x00066666,
0x02c, 0x0000001a,
0x02a, 0x000e0000,
0x010, 0x0004000f,
0x011, 0x000e31fc,
0x010, 0x0006000f,
0x011, 0x000ff9f8,
0x010, 0x0002000f,
0x011, 0x000203f9,
0x010, 0x0003000f,
0x011, 0x000ff500,
0x010, 0x00000000,
0x011, 0x00000000,
0x010, 0x0008000f,
0x011, 0x0003f100,
0x010, 0x0009000f,
0x011, 0x00023100,
0x012, 0x000d8000,
0x012, 0x00090000,
0x012, 0x00051000,
0x012, 0x00012000,
0x013, 0x00028fb4,
0x013, 0x00024fa8,
0x013, 0x000207a4,
0x013, 0x0001c798,
0x013, 0x000183a4,
0x013, 0x00014398,
0x013, 0x000101a4,
0x013, 0x0000c198,
0x013, 0x000080a4,
0x013, 0x00004098,
0x013, 0x00000000,
0x014, 0x0001944c,
0x014, 0x00059444,
0x014, 0x0009944c,
0x014, 0x000d9444,
0x015, 0x0000f405,
0x015, 0x0004f405,
0x015, 0x0008f405,
0x015, 0x000cf405,
0x016, 0x000e0330,
0x016, 0x000a0330,
0x016, 0x00060330,
0x016, 0x00020330,
0x000, 0x00010159,
0x018, 0x0000f401,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01f, 0x00080003,
0x0fe, 0x00000000,
0x0fe, 0x00000000,
0x01e, 0x00044457,
0x01f, 0x00080000,
0x000, 0x00030159,
};
u32 Rtl8192CUAGCTAB_1T_HPArray[RTL8192CUAGCTAB_1T_HPArrayLength] = {
0xc78, 0x7b000001,
0xc78, 0x7b010001,
0xc78, 0x7b020001,
0xc78, 0x7b030001,
0xc78, 0x7b040001,
0xc78, 0x7b050001,
0xc78, 0x7b060001,
0xc78, 0x7b070001,
0xc78, 0x7b080001,
0xc78, 0x7a090001,
0xc78, 0x790a0001,
0xc78, 0x780b0001,
0xc78, 0x770c0001,
0xc78, 0x760d0001,
0xc78, 0x750e0001,
0xc78, 0x740f0001,
0xc78, 0x73100001,
0xc78, 0x72110001,
0xc78, 0x71120001,
0xc78, 0x70130001,
0xc78, 0x6f140001,
0xc78, 0x6e150001,
0xc78, 0x6d160001,
0xc78, 0x6c170001,
0xc78, 0x6b180001,
0xc78, 0x6a190001,
0xc78, 0x691a0001,
0xc78, 0x681b0001,
0xc78, 0x671c0001,
0xc78, 0x661d0001,
0xc78, 0x651e0001,
0xc78, 0x641f0001,
0xc78, 0x63200001,
0xc78, 0x62210001,
0xc78, 0x61220001,
0xc78, 0x60230001,
0xc78, 0x46240001,
0xc78, 0x45250001,
0xc78, 0x44260001,
0xc78, 0x43270001,
0xc78, 0x42280001,
0xc78, 0x41290001,
0xc78, 0x402a0001,
0xc78, 0x262b0001,
0xc78, 0x252c0001,
0xc78, 0x242d0001,
0xc78, 0x232e0001,
0xc78, 0x222f0001,
0xc78, 0x21300001,
0xc78, 0x20310001,
0xc78, 0x06320001,
0xc78, 0x05330001,
0xc78, 0x04340001,
0xc78, 0x03350001,
0xc78, 0x02360001,
0xc78, 0x01370001,
0xc78, 0x00380001,
0xc78, 0x00390001,
0xc78, 0x003a0001,
0xc78, 0x003b0001,
0xc78, 0x003c0001,
0xc78, 0x003d0001,
0xc78, 0x003e0001,
0xc78, 0x003f0001,
0xc78, 0x7b400001,
0xc78, 0x7b410001,
0xc78, 0x7b420001,
0xc78, 0x7b430001,
0xc78, 0x7b440001,
0xc78, 0x7b450001,
0xc78, 0x7b460001,
0xc78, 0x7b470001,
0xc78, 0x7b480001,
0xc78, 0x7a490001,
0xc78, 0x794a0001,
0xc78, 0x784b0001,
0xc78, 0x774c0001,
0xc78, 0x764d0001,
0xc78, 0x754e0001,
0xc78, 0x744f0001,
0xc78, 0x73500001,
0xc78, 0x72510001,
0xc78, 0x71520001,
0xc78, 0x70530001,
0xc78, 0x6f540001,
0xc78, 0x6e550001,
0xc78, 0x6d560001,
0xc78, 0x6c570001,
0xc78, 0x6b580001,
0xc78, 0x6a590001,
0xc78, 0x695a0001,
0xc78, 0x685b0001,
0xc78, 0x675c0001,
0xc78, 0x665d0001,
0xc78, 0x655e0001,
0xc78, 0x645f0001,
0xc78, 0x63600001,
0xc78, 0x62610001,
0xc78, 0x61620001,
0xc78, 0x60630001,
0xc78, 0x46640001,
0xc78, 0x45650001,
0xc78, 0x44660001,
0xc78, 0x43670001,
0xc78, 0x42680001,
0xc78, 0x41690001,
0xc78, 0x406a0001,
0xc78, 0x266b0001,
0xc78, 0x256c0001,
0xc78, 0x246d0001,
0xc78, 0x236e0001,
0xc78, 0x226f0001,
0xc78, 0x21700001,
0xc78, 0x20710001,
0xc78, 0x06720001,
0xc78, 0x05730001,
0xc78, 0x04740001,
0xc78, 0x03750001,
0xc78, 0x02760001,
0xc78, 0x01770001,
0xc78, 0x00780001,
0xc78, 0x00790001,
0xc78, 0x007a0001,
0xc78, 0x007b0001,
0xc78, 0x007c0001,
0xc78, 0x007d0001,
0xc78, 0x007e0001,
0xc78, 0x007f0001,
0xc78, 0x3800001e,
0xc78, 0x3801001e,
0xc78, 0x3802001e,
0xc78, 0x3803001e,
0xc78, 0x3804001e,
0xc78, 0x3805001e,
0xc78, 0x3806001e,
0xc78, 0x3807001e,
0xc78, 0x3808001e,
0xc78, 0x3c09001e,
0xc78, 0x3e0a001e,
0xc78, 0x400b001e,
0xc78, 0x440c001e,
0xc78, 0x480d001e,
0xc78, 0x4c0e001e,
0xc78, 0x500f001e,
0xc78, 0x5210001e,
0xc78, 0x5611001e,
0xc78, 0x5a12001e,
0xc78, 0x5e13001e,
0xc78, 0x6014001e,
0xc78, 0x6015001e,
0xc78, 0x6016001e,
0xc78, 0x6217001e,
0xc78, 0x6218001e,
0xc78, 0x6219001e,
0xc78, 0x621a001e,
0xc78, 0x621b001e,
0xc78, 0x621c001e,
0xc78, 0x621d001e,
0xc78, 0x621e001e,
0xc78, 0x621f001e,
};
| gpl-2.0 |
sicknemesis/stock_kernel_hammerhead | tools/testing/selftests/breakpoints/breakpoint_test.c | 8325 | 7343 | /*
* Copyright (C) 2011 Red Hat, Inc., Frederic Weisbecker <fweisbec@redhat.com>
*
* Licensed under the terms of the GNU GPL License version 2
*
* Selftests for breakpoints (and more generally the do_debug() path) in x86.
*/
#include <sys/ptrace.h>
#include <unistd.h>
#include <stddef.h>
#include <sys/user.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
/* Breakpoint access modes */
enum {
BP_X = 1,
BP_RW = 2,
BP_W = 4,
};
static pid_t child_pid;
/*
* Ensures the child and parent are always "talking" about
* the same test sequence. (ie: that we haven't forgotten
* to call check_trapped() somewhere).
*/
static int nr_tests;
static void set_breakpoint_addr(void *addr, int n)
{
int ret;
ret = ptrace(PTRACE_POKEUSER, child_pid,
offsetof(struct user, u_debugreg[n]), addr);
if (ret) {
perror("Can't set breakpoint addr\n");
exit(-1);
}
}
static void toggle_breakpoint(int n, int type, int len,
int local, int global, int set)
{
int ret;
int xtype, xlen;
unsigned long vdr7, dr7;
switch (type) {
case BP_X:
xtype = 0;
break;
case BP_W:
xtype = 1;
break;
case BP_RW:
xtype = 3;
break;
}
switch (len) {
case 1:
xlen = 0;
break;
case 2:
xlen = 4;
break;
case 4:
xlen = 0xc;
break;
case 8:
xlen = 8;
break;
}
dr7 = ptrace(PTRACE_PEEKUSER, child_pid,
offsetof(struct user, u_debugreg[7]), 0);
vdr7 = (xlen | xtype) << 16;
vdr7 <<= 4 * n;
if (local) {
vdr7 |= 1 << (2 * n);
vdr7 |= 1 << 8;
}
if (global) {
vdr7 |= 2 << (2 * n);
vdr7 |= 1 << 9;
}
if (set)
dr7 |= vdr7;
else
dr7 &= ~vdr7;
ret = ptrace(PTRACE_POKEUSER, child_pid,
offsetof(struct user, u_debugreg[7]), dr7);
if (ret) {
perror("Can't set dr7");
exit(-1);
}
}
/* Dummy variables to test read/write accesses */
static unsigned long long dummy_var[4];
/* Dummy functions to test execution accesses */
static void dummy_func(void) { }
static void dummy_func1(void) { }
static void dummy_func2(void) { }
static void dummy_func3(void) { }
static void (*dummy_funcs[])(void) = {
dummy_func,
dummy_func1,
dummy_func2,
dummy_func3,
};
static int trapped;
static void check_trapped(void)
{
/*
* If we haven't trapped, wake up the parent
* so that it notices the failure.
*/
if (!trapped)
kill(getpid(), SIGUSR1);
trapped = 0;
nr_tests++;
}
static void write_var(int len)
{
char *pcval; short *psval; int *pival; long long *plval;
int i;
for (i = 0; i < 4; i++) {
switch (len) {
case 1:
pcval = (char *)&dummy_var[i];
*pcval = 0xff;
break;
case 2:
psval = (short *)&dummy_var[i];
*psval = 0xffff;
break;
case 4:
pival = (int *)&dummy_var[i];
*pival = 0xffffffff;
break;
case 8:
plval = (long long *)&dummy_var[i];
*plval = 0xffffffffffffffffLL;
break;
}
check_trapped();
}
}
static void read_var(int len)
{
char cval; short sval; int ival; long long lval;
int i;
for (i = 0; i < 4; i++) {
switch (len) {
case 1:
cval = *(char *)&dummy_var[i];
break;
case 2:
sval = *(short *)&dummy_var[i];
break;
case 4:
ival = *(int *)&dummy_var[i];
break;
case 8:
lval = *(long long *)&dummy_var[i];
break;
}
check_trapped();
}
}
/*
* Do the r/w/x accesses to trigger the breakpoints. And run
* the usual traps.
*/
static void trigger_tests(void)
{
int len, local, global, i;
char val;
int ret;
ret = ptrace(PTRACE_TRACEME, 0, NULL, 0);
if (ret) {
perror("Can't be traced?\n");
return;
}
/* Wake up father so that it sets up the first test */
kill(getpid(), SIGUSR1);
/* Test instruction breakpoints */
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
for (i = 0; i < 4; i++) {
dummy_funcs[i]();
check_trapped();
}
}
}
/* Test write watchpoints */
for (len = 1; len <= sizeof(long); len <<= 1) {
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
write_var(len);
}
}
}
/* Test read/write watchpoints (on read accesses) */
for (len = 1; len <= sizeof(long); len <<= 1) {
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
read_var(len);
}
}
}
/* Icebp trap */
asm(".byte 0xf1\n");
check_trapped();
/* Int 3 trap */
asm("int $3\n");
check_trapped();
kill(getpid(), SIGUSR1);
}
static void check_success(const char *msg)
{
const char *msg2;
int child_nr_tests;
int status;
/* Wait for the child to SIGTRAP */
wait(&status);
msg2 = "Failed";
if (WSTOPSIG(status) == SIGTRAP) {
child_nr_tests = ptrace(PTRACE_PEEKDATA, child_pid,
&nr_tests, 0);
if (child_nr_tests == nr_tests)
msg2 = "Ok";
if (ptrace(PTRACE_POKEDATA, child_pid, &trapped, 1)) {
perror("Can't poke\n");
exit(-1);
}
}
nr_tests++;
printf("%s [%s]\n", msg, msg2);
}
static void launch_instruction_breakpoints(char *buf, int local, int global)
{
int i;
for (i = 0; i < 4; i++) {
set_breakpoint_addr(dummy_funcs[i], i);
toggle_breakpoint(i, BP_X, 1, local, global, 1);
ptrace(PTRACE_CONT, child_pid, NULL, 0);
sprintf(buf, "Test breakpoint %d with local: %d global: %d",
i, local, global);
check_success(buf);
toggle_breakpoint(i, BP_X, 1, local, global, 0);
}
}
static void launch_watchpoints(char *buf, int mode, int len,
int local, int global)
{
const char *mode_str;
int i;
if (mode == BP_W)
mode_str = "write";
else
mode_str = "read";
for (i = 0; i < 4; i++) {
set_breakpoint_addr(&dummy_var[i], i);
toggle_breakpoint(i, mode, len, local, global, 1);
ptrace(PTRACE_CONT, child_pid, NULL, 0);
sprintf(buf, "Test %s watchpoint %d with len: %d local: "
"%d global: %d", mode_str, i, len, local, global);
check_success(buf);
toggle_breakpoint(i, mode, len, local, global, 0);
}
}
/* Set the breakpoints and check the child successfully trigger them */
static void launch_tests(void)
{
char buf[1024];
int len, local, global, i;
/* Instruction breakpoints */
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
launch_instruction_breakpoints(buf, local, global);
}
}
/* Write watchpoint */
for (len = 1; len <= sizeof(long); len <<= 1) {
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
launch_watchpoints(buf, BP_W, len,
local, global);
}
}
}
/* Read-Write watchpoint */
for (len = 1; len <= sizeof(long); len <<= 1) {
for (local = 0; local < 2; local++) {
for (global = 0; global < 2; global++) {
if (!local && !global)
continue;
launch_watchpoints(buf, BP_RW, len,
local, global);
}
}
}
/* Icebp traps */
ptrace(PTRACE_CONT, child_pid, NULL, 0);
check_success("Test icebp");
/* Int 3 traps */
ptrace(PTRACE_CONT, child_pid, NULL, 0);
check_success("Test int 3 trap");
ptrace(PTRACE_CONT, child_pid, NULL, 0);
}
int main(int argc, char **argv)
{
pid_t pid;
int ret;
pid = fork();
if (!pid) {
trigger_tests();
return 0;
}
child_pid = pid;
wait(NULL);
launch_tests();
wait(NULL);
return 0;
}
| gpl-2.0 |
eagleeyetom/android_kernel_oppo_msm8974 | net/sctp/inqueue.c | 8325 | 7168 | /* SCTP kernel implementation
* Copyright (c) 1999-2000 Cisco, Inc.
* Copyright (c) 1999-2001 Motorola, Inc.
* Copyright (c) 2002 International Business Machines, Corp.
*
* This file is part of the SCTP kernel implementation
*
* These functions are the methods for accessing the SCTP inqueue.
*
* An SCTP inqueue is a queue into which you push SCTP packets
* (which might be bundles or fragments of chunks) and out of which you
* pop SCTP whole chunks.
*
* This SCTP implementation 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 SCTP implementation is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* ************************
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* La Monte H.P. Yarroll <piggy@acm.org>
* Karl Knutson <karl@athena.chicago.il.us>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
/* Initialize an SCTP inqueue. */
void sctp_inq_init(struct sctp_inq *queue)
{
INIT_LIST_HEAD(&queue->in_chunk_list);
queue->in_progress = NULL;
/* Create a task for delivering data. */
INIT_WORK(&queue->immediate, NULL);
queue->malloced = 0;
}
/* Release the memory associated with an SCTP inqueue. */
void sctp_inq_free(struct sctp_inq *queue)
{
struct sctp_chunk *chunk, *tmp;
/* Empty the queue. */
list_for_each_entry_safe(chunk, tmp, &queue->in_chunk_list, list) {
list_del_init(&chunk->list);
sctp_chunk_free(chunk);
}
/* If there is a packet which is currently being worked on,
* free it as well.
*/
if (queue->in_progress) {
sctp_chunk_free(queue->in_progress);
queue->in_progress = NULL;
}
if (queue->malloced) {
/* Dump the master memory segment. */
kfree(queue);
}
}
/* Put a new packet in an SCTP inqueue.
* We assume that packet->sctp_hdr is set and in host byte order.
*/
void sctp_inq_push(struct sctp_inq *q, struct sctp_chunk *chunk)
{
/* Directly call the packet handling routine. */
if (chunk->rcvr->dead) {
sctp_chunk_free(chunk);
return;
}
/* We are now calling this either from the soft interrupt
* or from the backlog processing.
* Eventually, we should clean up inqueue to not rely
* on the BH related data structures.
*/
list_add_tail(&chunk->list, &q->in_chunk_list);
q->immediate.func(&q->immediate);
}
/* Peek at the next chunk on the inqeue. */
struct sctp_chunkhdr *sctp_inq_peek(struct sctp_inq *queue)
{
struct sctp_chunk *chunk;
sctp_chunkhdr_t *ch = NULL;
chunk = queue->in_progress;
/* If there is no more chunks in this packet, say so */
if (chunk->singleton ||
chunk->end_of_packet ||
chunk->pdiscard)
return NULL;
ch = (sctp_chunkhdr_t *)chunk->chunk_end;
return ch;
}
/* Extract a chunk from an SCTP inqueue.
*
* WARNING: If you need to put the chunk on another queue, you need to
* make a shallow copy (clone) of it.
*/
struct sctp_chunk *sctp_inq_pop(struct sctp_inq *queue)
{
struct sctp_chunk *chunk;
sctp_chunkhdr_t *ch = NULL;
/* The assumption is that we are safe to process the chunks
* at this time.
*/
if ((chunk = queue->in_progress)) {
/* There is a packet that we have been working on.
* Any post processing work to do before we move on?
*/
if (chunk->singleton ||
chunk->end_of_packet ||
chunk->pdiscard) {
sctp_chunk_free(chunk);
chunk = queue->in_progress = NULL;
} else {
/* Nothing to do. Next chunk in the packet, please. */
ch = (sctp_chunkhdr_t *) chunk->chunk_end;
/* Force chunk->skb->data to chunk->chunk_end. */
skb_pull(chunk->skb,
chunk->chunk_end - chunk->skb->data);
/* Verify that we have at least chunk headers
* worth of buffer left.
*/
if (skb_headlen(chunk->skb) < sizeof(sctp_chunkhdr_t)) {
sctp_chunk_free(chunk);
chunk = queue->in_progress = NULL;
}
}
}
/* Do we need to take the next packet out of the queue to process? */
if (!chunk) {
struct list_head *entry;
/* Is the queue empty? */
if (list_empty(&queue->in_chunk_list))
return NULL;
entry = queue->in_chunk_list.next;
chunk = queue->in_progress =
list_entry(entry, struct sctp_chunk, list);
list_del_init(entry);
/* This is the first chunk in the packet. */
chunk->singleton = 1;
ch = (sctp_chunkhdr_t *) chunk->skb->data;
chunk->data_accepted = 0;
}
chunk->chunk_hdr = ch;
chunk->chunk_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length));
/* In the unlikely case of an IP reassembly, the skb could be
* non-linear. If so, update chunk_end so that it doesn't go past
* the skb->tail.
*/
if (unlikely(skb_is_nonlinear(chunk->skb))) {
if (chunk->chunk_end > skb_tail_pointer(chunk->skb))
chunk->chunk_end = skb_tail_pointer(chunk->skb);
}
skb_pull(chunk->skb, sizeof(sctp_chunkhdr_t));
chunk->subh.v = NULL; /* Subheader is no longer valid. */
if (chunk->chunk_end < skb_tail_pointer(chunk->skb)) {
/* This is not a singleton */
chunk->singleton = 0;
} else if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) {
/* RFC 2960, Section 6.10 Bundling
*
* Partial chunks MUST NOT be placed in an SCTP packet.
* If the receiver detects a partial chunk, it MUST drop
* the chunk.
*
* Since the end of the chunk is past the end of our buffer
* (which contains the whole packet, we can freely discard
* the whole packet.
*/
sctp_chunk_free(chunk);
chunk = queue->in_progress = NULL;
return NULL;
} else {
/* We are at the end of the packet, so mark the chunk
* in case we need to send a SACK.
*/
chunk->end_of_packet = 1;
}
SCTP_DEBUG_PRINTK("+++sctp_inq_pop+++ chunk %p[%s],"
" length %d, skb->len %d\n",chunk,
sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)),
ntohs(chunk->chunk_hdr->length), chunk->skb->len);
return chunk;
}
/* Set a top-half handler.
*
* Originally, we the top-half handler was scheduled as a BH. We now
* call the handler directly in sctp_inq_push() at a time that
* we know we are lock safe.
* The intent is that this routine will pull stuff out of the
* inqueue and process it.
*/
void sctp_inq_set_th_handler(struct sctp_inq *q, work_func_t callback)
{
INIT_WORK(&q->immediate, callback);
}
| gpl-2.0 |
varchild/SebastianFM-kernel | drivers/staging/comedi/range.c | 9093 | 4431 | /*
module/range.c
comedi routines for voltage ranges
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 1997-8 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/uaccess.h>
#include "comedidev.h"
#include "internal.h"
const struct comedi_lrange range_bipolar10 = { 1, {BIP_RANGE(10)} };
EXPORT_SYMBOL(range_bipolar10);
const struct comedi_lrange range_bipolar5 = { 1, {BIP_RANGE(5)} };
EXPORT_SYMBOL(range_bipolar5);
const struct comedi_lrange range_bipolar2_5 = { 1, {BIP_RANGE(2.5)} };
EXPORT_SYMBOL(range_bipolar2_5);
const struct comedi_lrange range_unipolar10 = { 1, {UNI_RANGE(10)} };
EXPORT_SYMBOL(range_unipolar10);
const struct comedi_lrange range_unipolar5 = { 1, {UNI_RANGE(5)} };
EXPORT_SYMBOL(range_unipolar5);
const struct comedi_lrange range_unknown = { 1, {{0, 1000000, UNIT_none} } };
EXPORT_SYMBOL(range_unknown);
/*
COMEDI_RANGEINFO
range information ioctl
arg:
pointer to rangeinfo structure
reads:
range info structure
writes:
n struct comedi_krange structures to rangeinfo->range_ptr
*/
int do_rangeinfo_ioctl(struct comedi_device *dev,
struct comedi_rangeinfo __user *arg)
{
struct comedi_rangeinfo it;
int subd, chan;
const struct comedi_lrange *lr;
struct comedi_subdevice *s;
if (copy_from_user(&it, arg, sizeof(struct comedi_rangeinfo)))
return -EFAULT;
subd = (it.range_type >> 24) & 0xf;
chan = (it.range_type >> 16) & 0xff;
if (!dev->attached)
return -EINVAL;
if (subd >= dev->n_subdevices)
return -EINVAL;
s = dev->subdevices + subd;
if (s->range_table) {
lr = s->range_table;
} else if (s->range_table_list) {
if (chan >= s->n_chan)
return -EINVAL;
lr = s->range_table_list[chan];
} else {
return -EINVAL;
}
if (RANGE_LENGTH(it.range_type) != lr->length) {
DPRINTK("wrong length %d should be %d (0x%08x)\n",
RANGE_LENGTH(it.range_type), lr->length, it.range_type);
return -EINVAL;
}
if (copy_to_user(it.range_ptr, lr->range,
sizeof(struct comedi_krange) * lr->length))
return -EFAULT;
return 0;
}
static int aref_invalid(struct comedi_subdevice *s, unsigned int chanspec)
{
unsigned int aref;
/* disable reporting invalid arefs... maybe someday */
return 0;
aref = CR_AREF(chanspec);
switch (aref) {
case AREF_DIFF:
if (s->subdev_flags & SDF_DIFF)
return 0;
break;
case AREF_COMMON:
if (s->subdev_flags & SDF_COMMON)
return 0;
break;
case AREF_GROUND:
if (s->subdev_flags & SDF_GROUND)
return 0;
break;
case AREF_OTHER:
if (s->subdev_flags & SDF_OTHER)
return 0;
break;
default:
break;
}
DPRINTK("subdevice does not support aref %i", aref);
return 1;
}
/*
This function checks each element in a channel/gain list to make
make sure it is valid.
*/
int comedi_check_chanlist(struct comedi_subdevice *s, int n,
unsigned int *chanlist)
{
int i;
int chan;
if (s->range_table) {
for (i = 0; i < n; i++)
if (CR_CHAN(chanlist[i]) >= s->n_chan ||
CR_RANGE(chanlist[i]) >= s->range_table->length
|| aref_invalid(s, chanlist[i])) {
printk(KERN_ERR "bad chanlist[%d]=0x%08x "
"in_chan=%d range length=%d\n", i,
chanlist[i], s->n_chan,
s->range_table->length);
return -EINVAL;
}
} else if (s->range_table_list) {
for (i = 0; i < n; i++) {
chan = CR_CHAN(chanlist[i]);
if (chan >= s->n_chan ||
CR_RANGE(chanlist[i]) >=
s->range_table_list[chan]->length
|| aref_invalid(s, chanlist[i])) {
printk(KERN_ERR "bad chanlist[%d]=0x%08x\n",
i, chanlist[i]);
return -EINVAL;
}
}
} else {
printk(KERN_ERR "comedi: (bug) no range type list!\n");
return -EINVAL;
}
return 0;
}
EXPORT_SYMBOL(comedi_check_chanlist);
| gpl-2.0 |
CyanogenMod/android_kernel_google_msm | drivers/input/joystick/iforce/iforce-main.c | 9093 | 13366 | /*
* Copyright (c) 2000-2002 Vojtech Pavlik <vojtech@ucw.cz>
* Copyright (c) 2001-2002, 2007 Johann Deneux <johann.deneux@gmail.com>
*
* USB/RS232 I-Force joysticks and wheels.
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Should you need to contact me, the author, you can do so either by
* e-mail - mail your message to <vojtech@ucw.cz>, or by paper mail:
* Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic
*/
#include "iforce.h"
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>, Johann Deneux <johann.deneux@gmail.com>");
MODULE_DESCRIPTION("USB/RS232 I-Force joysticks and wheels driver");
MODULE_LICENSE("GPL");
static signed short btn_joystick[] =
{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_BASE5, BTN_A, BTN_B, BTN_C, -1 };
static signed short btn_avb_pegasus[] =
{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, -1 };
static signed short btn_wheel[] =
{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_BASE5, BTN_A, BTN_B, BTN_C, -1 };
static signed short btn_avb_tw[] =
{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, -1 };
static signed short btn_avb_wheel[] =
{ BTN_GEAR_DOWN, BTN_GEAR_UP, BTN_BASE, BTN_BASE2, BTN_BASE3,
BTN_BASE4, BTN_BASE5, BTN_BASE6, -1 };
static signed short abs_joystick[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y, -1 };
static signed short abs_joystick_rudder[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER, ABS_HAT0X, ABS_HAT0Y, -1 };
static signed short abs_avb_pegasus[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER, ABS_HAT0X, ABS_HAT0Y,
ABS_HAT1X, ABS_HAT1Y, -1 };
static signed short abs_wheel[] =
{ ABS_WHEEL, ABS_GAS, ABS_BRAKE, ABS_HAT0X, ABS_HAT0Y, -1 };
static signed short ff_iforce[] =
{ FF_PERIODIC, FF_CONSTANT, FF_SPRING, FF_DAMPER,
FF_SQUARE, FF_TRIANGLE, FF_SINE, FF_SAW_UP, FF_SAW_DOWN, FF_GAIN,
FF_AUTOCENTER, -1 };
static struct iforce_device iforce_device[] = {
{ 0x044f, 0xa01c, "Thrustmaster Motor Sport GT", btn_wheel, abs_wheel, ff_iforce },
{ 0x046d, 0xc281, "Logitech WingMan Force", btn_joystick, abs_joystick, ff_iforce },
{ 0x046d, 0xc291, "Logitech WingMan Formula Force", btn_wheel, abs_wheel, ff_iforce },
{ 0x05ef, 0x020a, "AVB Top Shot Pegasus", btn_avb_pegasus, abs_avb_pegasus, ff_iforce },
{ 0x05ef, 0x8884, "AVB Mag Turbo Force", btn_avb_wheel, abs_wheel, ff_iforce },
{ 0x05ef, 0x8888, "AVB Top Shot Force Feedback Racing Wheel", btn_avb_tw, abs_wheel, ff_iforce }, //?
{ 0x061c, 0xc0a4, "ACT LABS Force RS", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x061c, 0xc084, "ACT LABS Force RS", btn_wheel, abs_wheel, ff_iforce },
{ 0x06f8, 0x0001, "Guillemot Race Leader Force Feedback", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x06f8, 0x0001, "Guillemot Jet Leader Force Feedback", btn_joystick, abs_joystick_rudder, ff_iforce },
{ 0x06f8, 0x0004, "Guillemot Force Feedback Racing Wheel", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x06f8, 0xa302, "Guillemot Jet Leader 3D", btn_joystick, abs_joystick, ff_iforce }, //?
{ 0x06d6, 0x29bc, "Trust Force Feedback Race Master", btn_wheel, abs_wheel, ff_iforce },
{ 0x0000, 0x0000, "Unknown I-Force Device [%04x:%04x]", btn_joystick, abs_joystick, ff_iforce }
};
static int iforce_playback(struct input_dev *dev, int effect_id, int value)
{
struct iforce *iforce = input_get_drvdata(dev);
struct iforce_core_effect *core_effect = &iforce->core_effects[effect_id];
if (value > 0)
set_bit(FF_CORE_SHOULD_PLAY, core_effect->flags);
else
clear_bit(FF_CORE_SHOULD_PLAY, core_effect->flags);
iforce_control_playback(iforce, effect_id, value);
return 0;
}
static void iforce_set_gain(struct input_dev *dev, u16 gain)
{
struct iforce *iforce = input_get_drvdata(dev);
unsigned char data[3];
data[0] = gain >> 9;
iforce_send_packet(iforce, FF_CMD_GAIN, data);
}
static void iforce_set_autocenter(struct input_dev *dev, u16 magnitude)
{
struct iforce *iforce = input_get_drvdata(dev);
unsigned char data[3];
data[0] = 0x03;
data[1] = magnitude >> 9;
iforce_send_packet(iforce, FF_CMD_AUTOCENTER, data);
data[0] = 0x04;
data[1] = 0x01;
iforce_send_packet(iforce, FF_CMD_AUTOCENTER, data);
}
/*
* Function called when an ioctl is performed on the event dev entry.
* It uploads an effect to the device
*/
static int iforce_upload_effect(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old)
{
struct iforce *iforce = input_get_drvdata(dev);
struct iforce_core_effect *core_effect = &iforce->core_effects[effect->id];
int ret;
if (__test_and_set_bit(FF_CORE_IS_USED, core_effect->flags)) {
/* Check the effect is not already being updated */
if (test_bit(FF_CORE_UPDATE, core_effect->flags))
return -EAGAIN;
}
/*
* Upload the effect
*/
switch (effect->type) {
case FF_PERIODIC:
ret = iforce_upload_periodic(iforce, effect, old);
break;
case FF_CONSTANT:
ret = iforce_upload_constant(iforce, effect, old);
break;
case FF_SPRING:
case FF_DAMPER:
ret = iforce_upload_condition(iforce, effect, old);
break;
default:
return -EINVAL;
}
if (ret == 0) {
/* A packet was sent, forbid new updates until we are notified
* that the packet was updated
*/
set_bit(FF_CORE_UPDATE, core_effect->flags);
}
return ret;
}
/*
* Erases an effect: it frees the effect id and mark as unused the memory
* allocated for the parameters
*/
static int iforce_erase_effect(struct input_dev *dev, int effect_id)
{
struct iforce *iforce = input_get_drvdata(dev);
struct iforce_core_effect *core_effect = &iforce->core_effects[effect_id];
int err = 0;
if (test_bit(FF_MOD1_IS_USED, core_effect->flags))
err = release_resource(&core_effect->mod1_chunk);
if (!err && test_bit(FF_MOD2_IS_USED, core_effect->flags))
err = release_resource(&core_effect->mod2_chunk);
/* TODO: remember to change that if more FF_MOD* bits are added */
core_effect->flags[0] = 0;
return err;
}
static int iforce_open(struct input_dev *dev)
{
struct iforce *iforce = input_get_drvdata(dev);
switch (iforce->bus) {
#ifdef CONFIG_JOYSTICK_IFORCE_USB
case IFORCE_USB:
iforce->irq->dev = iforce->usbdev;
if (usb_submit_urb(iforce->irq, GFP_KERNEL))
return -EIO;
break;
#endif
}
if (test_bit(EV_FF, dev->evbit)) {
/* Enable force feedback */
iforce_send_packet(iforce, FF_CMD_ENABLE, "\004");
}
return 0;
}
static void iforce_close(struct input_dev *dev)
{
struct iforce *iforce = input_get_drvdata(dev);
int i;
if (test_bit(EV_FF, dev->evbit)) {
/* Check: no effects should be present in memory */
for (i = 0; i < dev->ff->max_effects; i++) {
if (test_bit(FF_CORE_IS_USED, iforce->core_effects[i].flags)) {
dev_warn(&dev->dev,
"%s: Device still owns effects\n",
__func__);
break;
}
}
/* Disable force feedback playback */
iforce_send_packet(iforce, FF_CMD_ENABLE, "\001");
/* Wait for the command to complete */
wait_event_interruptible(iforce->wait,
!test_bit(IFORCE_XMIT_RUNNING, iforce->xmit_flags));
}
switch (iforce->bus) {
#ifdef CONFIG_JOYSTICK_IFORCE_USB
case IFORCE_USB:
usb_kill_urb(iforce->irq);
usb_kill_urb(iforce->out);
usb_kill_urb(iforce->ctrl);
break;
#endif
#ifdef CONFIG_JOYSTICK_IFORCE_232
case IFORCE_232:
//TODO: Wait for the last packets to be sent
break;
#endif
}
}
int iforce_init_device(struct iforce *iforce)
{
struct input_dev *input_dev;
struct ff_device *ff;
unsigned char c[] = "CEOV";
int i, error;
int ff_effects = 0;
input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
init_waitqueue_head(&iforce->wait);
spin_lock_init(&iforce->xmit_lock);
mutex_init(&iforce->mem_mutex);
iforce->xmit.buf = iforce->xmit_data;
iforce->dev = input_dev;
/*
* Input device fields.
*/
switch (iforce->bus) {
#ifdef CONFIG_JOYSTICK_IFORCE_USB
case IFORCE_USB:
input_dev->id.bustype = BUS_USB;
input_dev->dev.parent = &iforce->usbdev->dev;
break;
#endif
#ifdef CONFIG_JOYSTICK_IFORCE_232
case IFORCE_232:
input_dev->id.bustype = BUS_RS232;
input_dev->dev.parent = &iforce->serio->dev;
break;
#endif
}
input_set_drvdata(input_dev, iforce);
input_dev->name = "Unknown I-Force device";
input_dev->open = iforce_open;
input_dev->close = iforce_close;
/*
* On-device memory allocation.
*/
iforce->device_memory.name = "I-Force device effect memory";
iforce->device_memory.start = 0;
iforce->device_memory.end = 200;
iforce->device_memory.flags = IORESOURCE_MEM;
iforce->device_memory.parent = NULL;
iforce->device_memory.child = NULL;
iforce->device_memory.sibling = NULL;
/*
* Wait until device ready - until it sends its first response.
*/
for (i = 0; i < 20; i++)
if (!iforce_get_id_packet(iforce, "O"))
break;
if (i == 20) { /* 5 seconds */
err("Timeout waiting for response from device.");
error = -ENODEV;
goto fail;
}
/*
* Get device info.
*/
if (!iforce_get_id_packet(iforce, "M"))
input_dev->id.vendor = (iforce->edata[2] << 8) | iforce->edata[1];
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet M\n");
if (!iforce_get_id_packet(iforce, "P"))
input_dev->id.product = (iforce->edata[2] << 8) | iforce->edata[1];
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet P\n");
if (!iforce_get_id_packet(iforce, "B"))
iforce->device_memory.end = (iforce->edata[2] << 8) | iforce->edata[1];
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet B\n");
if (!iforce_get_id_packet(iforce, "N"))
ff_effects = iforce->edata[1];
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet N\n");
/* Check if the device can store more effects than the driver can really handle */
if (ff_effects > IFORCE_EFFECTS_MAX) {
dev_warn(&iforce->dev->dev, "Limiting number of effects to %d (device reports %d)\n",
IFORCE_EFFECTS_MAX, ff_effects);
ff_effects = IFORCE_EFFECTS_MAX;
}
/*
* Display additional info.
*/
for (i = 0; c[i]; i++)
if (!iforce_get_id_packet(iforce, c + i))
iforce_dump_packet("info", iforce->ecmd, iforce->edata);
/*
* Disable spring, enable force feedback.
*/
iforce_set_autocenter(input_dev, 0);
/*
* Find appropriate device entry
*/
for (i = 0; iforce_device[i].idvendor; i++)
if (iforce_device[i].idvendor == input_dev->id.vendor &&
iforce_device[i].idproduct == input_dev->id.product)
break;
iforce->type = iforce_device + i;
input_dev->name = iforce->type->name;
/*
* Set input device bitfields and ranges.
*/
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) |
BIT_MASK(EV_FF_STATUS);
for (i = 0; iforce->type->btn[i] >= 0; i++)
set_bit(iforce->type->btn[i], input_dev->keybit);
set_bit(BTN_DEAD, input_dev->keybit);
for (i = 0; iforce->type->abs[i] >= 0; i++) {
signed short t = iforce->type->abs[i];
switch (t) {
case ABS_X:
case ABS_Y:
case ABS_WHEEL:
input_set_abs_params(input_dev, t, -1920, 1920, 16, 128);
set_bit(t, input_dev->ffbit);
break;
case ABS_THROTTLE:
case ABS_GAS:
case ABS_BRAKE:
input_set_abs_params(input_dev, t, 0, 255, 0, 0);
break;
case ABS_RUDDER:
input_set_abs_params(input_dev, t, -128, 127, 0, 0);
break;
case ABS_HAT0X:
case ABS_HAT0Y:
case ABS_HAT1X:
case ABS_HAT1Y:
input_set_abs_params(input_dev, t, -1, 1, 0, 0);
break;
}
}
if (ff_effects) {
for (i = 0; iforce->type->ff[i] >= 0; i++)
set_bit(iforce->type->ff[i], input_dev->ffbit);
error = input_ff_create(input_dev, ff_effects);
if (error)
goto fail;
ff = input_dev->ff;
ff->upload = iforce_upload_effect;
ff->erase = iforce_erase_effect;
ff->set_gain = iforce_set_gain;
ff->set_autocenter = iforce_set_autocenter;
ff->playback = iforce_playback;
}
/*
* Register input device.
*/
error = input_register_device(iforce->dev);
if (error)
goto fail;
return 0;
fail: input_free_device(input_dev);
return error;
}
static int __init iforce_init(void)
{
int err = 0;
#ifdef CONFIG_JOYSTICK_IFORCE_USB
err = usb_register(&iforce_usb_driver);
if (err)
return err;
#endif
#ifdef CONFIG_JOYSTICK_IFORCE_232
err = serio_register_driver(&iforce_serio_drv);
#ifdef CONFIG_JOYSTICK_IFORCE_USB
if (err)
usb_deregister(&iforce_usb_driver);
#endif
#endif
return err;
}
static void __exit iforce_exit(void)
{
#ifdef CONFIG_JOYSTICK_IFORCE_USB
usb_deregister(&iforce_usb_driver);
#endif
#ifdef CONFIG_JOYSTICK_IFORCE_232
serio_unregister_driver(&iforce_serio_drv);
#endif
}
module_init(iforce_init);
module_exit(iforce_exit);
| gpl-2.0 |
anak1n/hercules_kerenl_jugs | drivers/staging/rtl8192u/r8192U_dm.c | 9093 | 130478 | /*++
Copyright-c Realtek Semiconductor Corp. All rights reserved.
Module Name:
r8192U_dm.c
Abstract:
HW dynamic mechanism.
Major Change History:
When Who What
---------- --------------- -------------------------------
2008-05-14 amy create version 0 porting from windows code.
--*/
#include "r8192U.h"
#include "r8192U_dm.h"
#include "r8192U_hw.h"
#include "r819xU_phy.h"
#include "r819xU_phyreg.h"
#include "r8190_rtl8256.h"
#include "r819xU_cmdpkt.h"
/*---------------------------Define Local Constant---------------------------*/
//
// Indicate different AP vendor for IOT issue.
//
static u32 edca_setting_DL[HT_IOT_PEER_MAX] =
{ 0x5e4322, 0x5e4322, 0x5e4322, 0x604322, 0xa44f, 0x5ea44f};
static u32 edca_setting_UL[HT_IOT_PEER_MAX] =
{ 0x5e4322, 0xa44f, 0x5e4322, 0x604322, 0x5ea44f, 0x5ea44f};
#define RTK_UL_EDCA 0xa44f
#define RTK_DL_EDCA 0x5e4322
/*---------------------------Define Local Constant---------------------------*/
/*------------------------Define global variable-----------------------------*/
// Debug variable ?
dig_t dm_digtable;
// Store current shoftware write register content for MAC PHY.
u8 dm_shadow[16][256] = {{0}};
// For Dynamic Rx Path Selection by Signal Strength
DRxPathSel DM_RxPathSelTable;
/*------------------------Define global variable-----------------------------*/
/*------------------------Define local variable------------------------------*/
/*------------------------Define local variable------------------------------*/
/*--------------------Define export function prototype-----------------------*/
extern void init_hal_dm(struct net_device *dev);
extern void deinit_hal_dm(struct net_device *dev);
extern void hal_dm_watchdog(struct net_device *dev);
extern void init_rate_adaptive(struct net_device *dev);
extern void dm_txpower_trackingcallback(struct work_struct *work);
extern void dm_cck_txpower_adjust(struct net_device *dev,bool binch14);
extern void dm_restore_dynamic_mechanism_state(struct net_device *dev);
extern void dm_backup_dynamic_mechanism_state(struct net_device *dev);
extern void dm_change_dynamic_initgain_thresh(struct net_device *dev,
u32 dm_type,
u32 dm_value);
extern void DM_ChangeFsyncSetting(struct net_device *dev,
s32 DM_Type,
s32 DM_Value);
extern void dm_force_tx_fw_info(struct net_device *dev,
u32 force_type,
u32 force_value);
extern void dm_init_edca_turbo(struct net_device *dev);
extern void dm_rf_operation_test_callback(unsigned long data);
extern void dm_rf_pathcheck_workitemcallback(struct work_struct *work);
extern void dm_fsync_timer_callback(unsigned long data);
extern void dm_check_fsync(struct net_device *dev);
extern void dm_shadow_init(struct net_device *dev);
/*--------------------Define export function prototype-----------------------*/
/*---------------------Define local function prototype-----------------------*/
// DM --> Rate Adaptive
static void dm_check_rate_adaptive(struct net_device *dev);
// DM --> Bandwidth switch
static void dm_init_bandwidth_autoswitch(struct net_device *dev);
static void dm_bandwidth_autoswitch( struct net_device *dev);
// DM --> TX power control
//static void dm_initialize_txpower_tracking(struct net_device *dev);
static void dm_check_txpower_tracking(struct net_device *dev);
//static void dm_txpower_reset_recovery(struct net_device *dev);
// DM --> BB init gain restore
#ifndef RTL8192U
static void dm_bb_initialgain_restore(struct net_device *dev);
// DM --> BB init gain backup
static void dm_bb_initialgain_backup(struct net_device *dev);
#endif
// DM --> Dynamic Init Gain by RSSI
static void dm_dig_init(struct net_device *dev);
static void dm_ctrl_initgain_byrssi(struct net_device *dev);
static void dm_ctrl_initgain_byrssi_highpwr(struct net_device *dev);
static void dm_ctrl_initgain_byrssi_by_driverrssi( struct net_device *dev);
static void dm_ctrl_initgain_byrssi_by_fwfalse_alarm(struct net_device *dev);
static void dm_initial_gain(struct net_device *dev);
static void dm_pd_th(struct net_device *dev);
static void dm_cs_ratio(struct net_device *dev);
static void dm_init_ctstoself(struct net_device *dev);
// DM --> EDCA turboe mode control
static void dm_check_edca_turbo(struct net_device *dev);
// DM --> HW RF control
static void dm_check_rfctrl_gpio(struct net_device *dev);
#ifndef RTL8190P
//static void dm_gpio_change_rf(struct net_device *dev);
#endif
// DM --> Check PBC
static void dm_check_pbc_gpio(struct net_device *dev);
// DM --> Check current RX RF path state
static void dm_check_rx_path_selection(struct net_device *dev);
static void dm_init_rxpath_selection(struct net_device *dev);
static void dm_rxpath_sel_byrssi(struct net_device *dev);
// DM --> Fsync for broadcom ap
static void dm_init_fsync(struct net_device *dev);
static void dm_deInit_fsync(struct net_device *dev);
//Added by vivi, 20080522
static void dm_check_txrateandretrycount(struct net_device *dev);
/*---------------------Define local function prototype-----------------------*/
/*---------------------Define of Tx Power Control For Near/Far Range --------*/ //Add by Jacken 2008/02/18
static void dm_init_dynamic_txpower(struct net_device *dev);
static void dm_dynamic_txpower(struct net_device *dev);
// DM --> For rate adaptive and DIG, we must send RSSI to firmware
static void dm_send_rssi_tofw(struct net_device *dev);
static void dm_ctstoself(struct net_device *dev);
/*---------------------------Define function prototype------------------------*/
//================================================================================
// HW Dynamic mechanism interface.
//================================================================================
//
// Description:
// Prepare SW resource for HW dynamic mechanism.
//
// Assumption:
// This function is only invoked at driver intialization once.
//
//
extern void
init_hal_dm(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
// Undecorated Smoothed Signal Strength, it can utilized to dynamic mechanism.
priv->undecorated_smoothed_pwdb = -1;
//Initial TX Power Control for near/far range , add by amy 2008/05/15, porting from windows code.
dm_init_dynamic_txpower(dev);
init_rate_adaptive(dev);
//dm_initialize_txpower_tracking(dev);
dm_dig_init(dev);
dm_init_edca_turbo(dev);
dm_init_bandwidth_autoswitch(dev);
dm_init_fsync(dev);
dm_init_rxpath_selection(dev);
dm_init_ctstoself(dev);
} // InitHalDm
extern void deinit_hal_dm(struct net_device *dev)
{
dm_deInit_fsync(dev);
}
#ifdef USB_RX_AGGREGATION_SUPPORT
void dm_CheckRxAggregation(struct net_device *dev) {
struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
PRT_HIGH_THROUGHPUT pHTInfo = priv->ieee80211->pHTInfo;
static unsigned long lastTxOkCnt = 0;
static unsigned long lastRxOkCnt = 0;
unsigned long curTxOkCnt = 0;
unsigned long curRxOkCnt = 0;
/*
if (pHalData->bForcedUsbRxAggr) {
if (pHalData->ForcedUsbRxAggrInfo == 0) {
if (pHalData->bCurrentRxAggrEnable) {
Adapter->HalFunc.HalUsbRxAggrHandler(Adapter, FALSE);
}
} else {
if (!pHalData->bCurrentRxAggrEnable || (pHalData->ForcedUsbRxAggrInfo != pHalData->LastUsbRxAggrInfoSetting)) {
Adapter->HalFunc.HalUsbRxAggrHandler(Adapter, TRUE);
}
}
return;
}
*/
curTxOkCnt = priv->stats.txbytesunicast - lastTxOkCnt;
curRxOkCnt = priv->stats.rxbytesunicast - lastRxOkCnt;
if((curTxOkCnt + curRxOkCnt) < 15000000) {
return;
}
if(curTxOkCnt > 4*curRxOkCnt) {
if (priv->bCurrentRxAggrEnable) {
write_nic_dword(dev, 0x1a8, 0);
priv->bCurrentRxAggrEnable = false;
}
}else{
if (!priv->bCurrentRxAggrEnable && !pHTInfo->bCurrentRT2RTAggregation) {
u32 ulValue;
ulValue = (pHTInfo->UsbRxFwAggrEn<<24) | (pHTInfo->UsbRxFwAggrPageNum<<16) |
(pHTInfo->UsbRxFwAggrPacketNum<<8) | (pHTInfo->UsbRxFwAggrTimeout);
/*
* If usb rx firmware aggregation is enabled,
* when anyone of three threshold conditions above is reached,
* firmware will send aggregated packet to driver.
*/
write_nic_dword(dev, 0x1a8, ulValue);
priv->bCurrentRxAggrEnable = true;
}
}
lastTxOkCnt = priv->stats.txbytesunicast;
lastRxOkCnt = priv->stats.rxbytesunicast;
} // dm_CheckEdcaTurbo
#endif
extern void hal_dm_watchdog(struct net_device *dev)
{
//struct r8192_priv *priv = ieee80211_priv(dev);
//static u8 previous_bssid[6] ={0};
/*Add by amy 2008/05/15 ,porting from windows code.*/
dm_check_rate_adaptive(dev);
dm_dynamic_txpower(dev);
dm_check_txrateandretrycount(dev);
dm_check_txpower_tracking(dev);
dm_ctrl_initgain_byrssi(dev);
dm_check_edca_turbo(dev);
dm_bandwidth_autoswitch(dev);
dm_check_rfctrl_gpio(dev);
dm_check_rx_path_selection(dev);
dm_check_fsync(dev);
// Add by amy 2008-05-15 porting from windows code.
dm_check_pbc_gpio(dev);
dm_send_rssi_tofw(dev);
dm_ctstoself(dev);
#ifdef USB_RX_AGGREGATION_SUPPORT
dm_CheckRxAggregation(dev);
#endif
} //HalDmWatchDog
/*
* Decide Rate Adaptive Set according to distance (signal strength)
* 01/11/2008 MHC Modify input arguments and RATR table level.
* 01/16/2008 MHC RF_Type is assigned in ReadAdapterInfo(). We must call
* the function after making sure RF_Type.
*/
extern void init_rate_adaptive(struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
prate_adaptive pra = (prate_adaptive)&priv->rate_adaptive;
pra->ratr_state = DM_RATR_STA_MAX;
pra->high2low_rssi_thresh_for_ra = RateAdaptiveTH_High;
pra->low2high_rssi_thresh_for_ra20M = RateAdaptiveTH_Low_20M+5;
pra->low2high_rssi_thresh_for_ra40M = RateAdaptiveTH_Low_40M+5;
pra->high_rssi_thresh_for_ra = RateAdaptiveTH_High+5;
pra->low_rssi_thresh_for_ra20M = RateAdaptiveTH_Low_20M;
pra->low_rssi_thresh_for_ra40M = RateAdaptiveTH_Low_40M;
if(priv->CustomerID == RT_CID_819x_Netcore)
pra->ping_rssi_enable = 1;
else
pra->ping_rssi_enable = 0;
pra->ping_rssi_thresh_for_ra = 15;
if (priv->rf_type == RF_2T4R)
{
// 07/10/08 MH Modify for RA smooth scheme.
/* 2008/01/11 MH Modify 2T RATR table for different RSSI. 080515 porting by amy from windows code.*/
pra->upper_rssi_threshold_ratr = 0x8f0f0000;
pra->middle_rssi_threshold_ratr = 0x8f0ff000;
pra->low_rssi_threshold_ratr = 0x8f0ff001;
pra->low_rssi_threshold_ratr_40M = 0x8f0ff005;
pra->low_rssi_threshold_ratr_20M = 0x8f0ff001;
pra->ping_rssi_ratr = 0x0000000d;//cosa add for test
}
else if (priv->rf_type == RF_1T2R)
{
pra->upper_rssi_threshold_ratr = 0x000f0000;
pra->middle_rssi_threshold_ratr = 0x000ff000;
pra->low_rssi_threshold_ratr = 0x000ff001;
pra->low_rssi_threshold_ratr_40M = 0x000ff005;
pra->low_rssi_threshold_ratr_20M = 0x000ff001;
pra->ping_rssi_ratr = 0x0000000d;//cosa add for test
}
} // InitRateAdaptive
/*-----------------------------------------------------------------------------
* Function: dm_check_rate_adaptive()
*
* Overview:
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 05/26/08 amy Create version 0 proting from windows code.
*
*---------------------------------------------------------------------------*/
static void dm_check_rate_adaptive(struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
PRT_HIGH_THROUGHPUT pHTInfo = priv->ieee80211->pHTInfo;
prate_adaptive pra = (prate_adaptive)&priv->rate_adaptive;
u32 currentRATR, targetRATR = 0;
u32 LowRSSIThreshForRA = 0, HighRSSIThreshForRA = 0;
bool bshort_gi_enabled = false;
static u8 ping_rssi_state=0;
if(!priv->up)
{
RT_TRACE(COMP_RATE, "<---- dm_check_rate_adaptive(): driver is going to unload\n");
return;
}
if(pra->rate_adaptive_disabled)//this variable is set by ioctl.
return;
// TODO: Only 11n mode is implemented currently,
if( !(priv->ieee80211->mode == WIRELESS_MODE_N_24G ||
priv->ieee80211->mode == WIRELESS_MODE_N_5G))
return;
if( priv->ieee80211->state == IEEE80211_LINKED )
{
// RT_TRACE(COMP_RATE, "dm_CheckRateAdaptive(): \t");
//
// Check whether Short GI is enabled
//
bshort_gi_enabled = (pHTInfo->bCurTxBW40MHz && pHTInfo->bCurShortGI40MHz) ||
(!pHTInfo->bCurTxBW40MHz && pHTInfo->bCurShortGI20MHz);
pra->upper_rssi_threshold_ratr =
(pra->upper_rssi_threshold_ratr & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
pra->middle_rssi_threshold_ratr =
(pra->middle_rssi_threshold_ratr & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
{
pra->low_rssi_threshold_ratr =
(pra->low_rssi_threshold_ratr_40M & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
}
else
{
pra->low_rssi_threshold_ratr =
(pra->low_rssi_threshold_ratr_20M & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
}
//cosa add for test
pra->ping_rssi_ratr =
(pra->ping_rssi_ratr & (~BIT31)) | ((bshort_gi_enabled)? BIT31:0) ;
/* 2007/10/08 MH We support RA smooth scheme now. When it is the first
time to link with AP. We will not change upper/lower threshold. If
STA stay in high or low level, we must change two different threshold
to prevent jumping frequently. */
if (pra->ratr_state == DM_RATR_STA_HIGH)
{
HighRSSIThreshForRA = pra->high2low_rssi_thresh_for_ra;
LowRSSIThreshForRA = (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)?
(pra->low_rssi_thresh_for_ra40M):(pra->low_rssi_thresh_for_ra20M);
}
else if (pra->ratr_state == DM_RATR_STA_LOW)
{
HighRSSIThreshForRA = pra->high_rssi_thresh_for_ra;
LowRSSIThreshForRA = (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)?
(pra->low2high_rssi_thresh_for_ra40M):(pra->low2high_rssi_thresh_for_ra20M);
}
else
{
HighRSSIThreshForRA = pra->high_rssi_thresh_for_ra;
LowRSSIThreshForRA = (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)?
(pra->low_rssi_thresh_for_ra40M):(pra->low_rssi_thresh_for_ra20M);
}
//DbgPrint("[DM] THresh H/L=%d/%d\n\r", RATR.HighRSSIThreshForRA, RATR.LowRSSIThreshForRA);
if(priv->undecorated_smoothed_pwdb >= (long)HighRSSIThreshForRA)
{
//DbgPrint("[DM] RSSI=%d STA=HIGH\n\r", pHalData->UndecoratedSmoothedPWDB);
pra->ratr_state = DM_RATR_STA_HIGH;
targetRATR = pra->upper_rssi_threshold_ratr;
}else if(priv->undecorated_smoothed_pwdb >= (long)LowRSSIThreshForRA)
{
//DbgPrint("[DM] RSSI=%d STA=Middle\n\r", pHalData->UndecoratedSmoothedPWDB);
pra->ratr_state = DM_RATR_STA_MIDDLE;
targetRATR = pra->middle_rssi_threshold_ratr;
}else
{
//DbgPrint("[DM] RSSI=%d STA=LOW\n\r", pHalData->UndecoratedSmoothedPWDB);
pra->ratr_state = DM_RATR_STA_LOW;
targetRATR = pra->low_rssi_threshold_ratr;
}
//cosa add for test
if(pra->ping_rssi_enable)
{
//pHalData->UndecoratedSmoothedPWDB = 19;
if(priv->undecorated_smoothed_pwdb < (long)(pra->ping_rssi_thresh_for_ra+5))
{
if( (priv->undecorated_smoothed_pwdb < (long)pra->ping_rssi_thresh_for_ra) ||
ping_rssi_state )
{
//DbgPrint("TestRSSI = %d, set RATR to 0x%x \n", pHalData->UndecoratedSmoothedPWDB, pRA->TestRSSIRATR);
pra->ratr_state = DM_RATR_STA_LOW;
targetRATR = pra->ping_rssi_ratr;
ping_rssi_state = 1;
}
//else
// DbgPrint("TestRSSI is between the range. \n");
}
else
{
//DbgPrint("TestRSSI Recover to 0x%x \n", targetRATR);
ping_rssi_state = 0;
}
}
// 2008.04.01
// For RTL819X, if pairwisekey = wep/tkip, we support only MCS0~7.
if(priv->ieee80211->GetHalfNmodeSupportByAPsHandler(dev))
targetRATR &= 0xf00fffff;
//
// Check whether updating of RATR0 is required
//
currentRATR = read_nic_dword(dev, RATR0);
if( targetRATR != currentRATR )
{
u32 ratr_value;
ratr_value = targetRATR;
RT_TRACE(COMP_RATE,"currentRATR = %x, targetRATR = %x\n", currentRATR, targetRATR);
if(priv->rf_type == RF_1T2R)
{
ratr_value &= ~(RATE_ALL_OFDM_2SS);
}
write_nic_dword(dev, RATR0, ratr_value);
write_nic_byte(dev, UFWP, 1);
pra->last_ratr = targetRATR;
}
}
else
{
pra->ratr_state = DM_RATR_STA_MAX;
}
} // dm_CheckRateAdaptive
static void dm_init_bandwidth_autoswitch(struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
priv->ieee80211->bandwidth_auto_switch.threshold_20Mhzto40Mhz = BW_AUTO_SWITCH_LOW_HIGH;
priv->ieee80211->bandwidth_auto_switch.threshold_40Mhzto20Mhz = BW_AUTO_SWITCH_HIGH_LOW;
priv->ieee80211->bandwidth_auto_switch.bforced_tx20Mhz = false;
priv->ieee80211->bandwidth_auto_switch.bautoswitch_enable = false;
} // dm_init_bandwidth_autoswitch
static void dm_bandwidth_autoswitch(struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20 ||!priv->ieee80211->bandwidth_auto_switch.bautoswitch_enable){
return;
}else{
if(priv->ieee80211->bandwidth_auto_switch.bforced_tx20Mhz == false){//If send packets in 40 Mhz in 20/40
if(priv->undecorated_smoothed_pwdb <= priv->ieee80211->bandwidth_auto_switch.threshold_40Mhzto20Mhz)
priv->ieee80211->bandwidth_auto_switch.bforced_tx20Mhz = true;
}else{//in force send packets in 20 Mhz in 20/40
if(priv->undecorated_smoothed_pwdb >= priv->ieee80211->bandwidth_auto_switch.threshold_20Mhzto40Mhz)
priv->ieee80211->bandwidth_auto_switch.bforced_tx20Mhz = false;
}
}
} // dm_BandwidthAutoSwitch
//OFDM default at 0db, index=6.
static u32 OFDMSwingTable[OFDM_Table_Length] = {
0x7f8001fe, // 0, +6db
0x71c001c7, // 1, +5db
0x65400195, // 2, +4db
0x5a400169, // 3, +3db
0x50800142, // 4, +2db
0x47c0011f, // 5, +1db
0x40000100, // 6, +0db ===> default, upper for higher temprature, lower for low temprature
0x390000e4, // 7, -1db
0x32c000cb, // 8, -2db
0x2d4000b5, // 9, -3db
0x288000a2, // 10, -4db
0x24000090, // 11, -5db
0x20000080, // 12, -6db
0x1c800072, // 13, -7db
0x19800066, // 14, -8db
0x26c0005b, // 15, -9db
0x24400051, // 16, -10db
0x12000048, // 17, -11db
0x10000040 // 18, -12db
};
static u8 CCKSwingTable_Ch1_Ch13[CCK_Table_length][8] = {
{0x36, 0x35, 0x2e, 0x25, 0x1c, 0x12, 0x09, 0x04}, // 0, +0db ===> CCK40M default
{0x30, 0x2f, 0x29, 0x21, 0x19, 0x10, 0x08, 0x03}, // 1, -1db
{0x2b, 0x2a, 0x25, 0x1e, 0x16, 0x0e, 0x07, 0x03}, // 2, -2db
{0x26, 0x25, 0x21, 0x1b, 0x14, 0x0d, 0x06, 0x03}, // 3, -3db
{0x22, 0x21, 0x1d, 0x18, 0x11, 0x0b, 0x06, 0x02}, // 4, -4db
{0x1f, 0x1e, 0x1a, 0x15, 0x10, 0x0a, 0x05, 0x02}, // 5, -5db
{0x1b, 0x1a, 0x17, 0x13, 0x0e, 0x09, 0x04, 0x02}, // 6, -6db ===> CCK20M default
{0x18, 0x17, 0x15, 0x11, 0x0c, 0x08, 0x04, 0x02}, // 7, -7db
{0x16, 0x15, 0x12, 0x0f, 0x0b, 0x07, 0x04, 0x01}, // 8, -8db
{0x13, 0x13, 0x10, 0x0d, 0x0a, 0x06, 0x03, 0x01}, // 9, -9db
{0x11, 0x11, 0x0f, 0x0c, 0x09, 0x06, 0x03, 0x01}, // 10, -10db
{0x0f, 0x0f, 0x0d, 0x0b, 0x08, 0x05, 0x03, 0x01} // 11, -11db
};
static u8 CCKSwingTable_Ch14[CCK_Table_length][8] = {
{0x36, 0x35, 0x2e, 0x1b, 0x00, 0x00, 0x00, 0x00}, // 0, +0db ===> CCK40M default
{0x30, 0x2f, 0x29, 0x18, 0x00, 0x00, 0x00, 0x00}, // 1, -1db
{0x2b, 0x2a, 0x25, 0x15, 0x00, 0x00, 0x00, 0x00}, // 2, -2db
{0x26, 0x25, 0x21, 0x13, 0x00, 0x00, 0x00, 0x00}, // 3, -3db
{0x22, 0x21, 0x1d, 0x11, 0x00, 0x00, 0x00, 0x00}, // 4, -4db
{0x1f, 0x1e, 0x1a, 0x0f, 0x00, 0x00, 0x00, 0x00}, // 5, -5db
{0x1b, 0x1a, 0x17, 0x0e, 0x00, 0x00, 0x00, 0x00}, // 6, -6db ===> CCK20M default
{0x18, 0x17, 0x15, 0x0c, 0x00, 0x00, 0x00, 0x00}, // 7, -7db
{0x16, 0x15, 0x12, 0x0b, 0x00, 0x00, 0x00, 0x00}, // 8, -8db
{0x13, 0x13, 0x10, 0x0a, 0x00, 0x00, 0x00, 0x00}, // 9, -9db
{0x11, 0x11, 0x0f, 0x09, 0x00, 0x00, 0x00, 0x00}, // 10, -10db
{0x0f, 0x0f, 0x0d, 0x08, 0x00, 0x00, 0x00, 0x00} // 11, -11db
};
static void dm_TXPowerTrackingCallback_TSSI(struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
bool bHighpowerstate, viviflag = FALSE;
DCMD_TXCMD_T tx_cmd;
u8 powerlevelOFDM24G;
int i =0, j = 0, k = 0;
u8 RF_Type, tmp_report[5]={0, 0, 0, 0, 0};
u32 Value;
u8 Pwr_Flag;
u16 Avg_TSSI_Meas, TSSI_13dBm, Avg_TSSI_Meas_from_driver=0;
//RT_STATUS rtStatus = RT_STATUS_SUCCESS;
bool rtStatus = true;
u32 delta=0;
write_nic_byte(dev, 0x1ba, 0);
priv->ieee80211->bdynamic_txpower_enable = false;
bHighpowerstate = priv->bDynamicTxHighPower;
powerlevelOFDM24G = (u8)(priv->Pwr_Track>>24);
RF_Type = priv->rf_type;
Value = (RF_Type<<8) | powerlevelOFDM24G;
RT_TRACE(COMP_POWER_TRACKING, "powerlevelOFDM24G = %x\n", powerlevelOFDM24G);
for(j = 0; j<=30; j++)
{ //fill tx_cmd
tx_cmd.Op = TXCMD_SET_TX_PWR_TRACKING;
tx_cmd.Length = 4;
tx_cmd.Value = Value;
#ifdef RTL8192U
rtStatus = SendTxCommandPacket(dev, &tx_cmd, 12);
if (rtStatus == RT_STATUS_FAILURE)
{
RT_TRACE(COMP_POWER_TRACKING, "Set configuration with tx cmd queue fail!\n");
}
#else
cmpk_message_handle_tx(dev, (u8*)&tx_cmd,
DESC_PACKET_TYPE_INIT, sizeof(DCMD_TXCMD_T));
#endif
mdelay(1);
//DbgPrint("hi, vivi, strange\n");
for(i = 0;i <= 30; i++)
{
Pwr_Flag = read_nic_byte(dev, 0x1ba);
if (Pwr_Flag == 0)
{
mdelay(1);
continue;
}
#ifdef RTL8190P
Avg_TSSI_Meas = read_nic_word(dev, 0x1bc);
#else
Avg_TSSI_Meas = read_nic_word(dev, 0x13c);
#endif
if(Avg_TSSI_Meas == 0)
{
write_nic_byte(dev, 0x1ba, 0);
break;
}
for(k = 0;k < 5; k++)
{
#ifdef RTL8190P
tmp_report[k] = read_nic_byte(dev, 0x1d8+k);
#else
if(k !=4)
tmp_report[k] = read_nic_byte(dev, 0x134+k);
else
tmp_report[k] = read_nic_byte(dev, 0x13e);
#endif
RT_TRACE(COMP_POWER_TRACKING, "TSSI_report_value = %d\n", tmp_report[k]);
}
//check if the report value is right
for(k = 0;k < 5; k++)
{
if(tmp_report[k] <= 20)
{
viviflag =TRUE;
break;
}
}
if(viviflag ==TRUE)
{
write_nic_byte(dev, 0x1ba, 0);
viviflag = FALSE;
RT_TRACE(COMP_POWER_TRACKING, "we filted this data\n");
for(k = 0;k < 5; k++)
tmp_report[k] = 0;
break;
}
for(k = 0;k < 5; k++)
{
Avg_TSSI_Meas_from_driver += tmp_report[k];
}
Avg_TSSI_Meas_from_driver = Avg_TSSI_Meas_from_driver*100/5;
RT_TRACE(COMP_POWER_TRACKING, "Avg_TSSI_Meas_from_driver = %d\n", Avg_TSSI_Meas_from_driver);
TSSI_13dBm = priv->TSSI_13dBm;
RT_TRACE(COMP_POWER_TRACKING, "TSSI_13dBm = %d\n", TSSI_13dBm);
//if(abs(Avg_TSSI_Meas_from_driver - TSSI_13dBm) <= E_FOR_TX_POWER_TRACK)
// For MacOS-compatible
if(Avg_TSSI_Meas_from_driver > TSSI_13dBm)
delta = Avg_TSSI_Meas_from_driver - TSSI_13dBm;
else
delta = TSSI_13dBm - Avg_TSSI_Meas_from_driver;
if(delta <= E_FOR_TX_POWER_TRACK)
{
priv->ieee80211->bdynamic_txpower_enable = TRUE;
write_nic_byte(dev, 0x1ba, 0);
RT_TRACE(COMP_POWER_TRACKING, "tx power track is done\n");
RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex = %d\n", priv->rfa_txpowertrackingindex);
RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex_real = %d\n", priv->rfa_txpowertrackingindex_real);
#ifdef RTL8190P
RT_TRACE(COMP_POWER_TRACKING, "priv->rfc_txpowertrackingindex = %d\n", priv->rfc_txpowertrackingindex);
RT_TRACE(COMP_POWER_TRACKING, "priv->rfc_txpowertrackingindex_real = %d\n", priv->rfc_txpowertrackingindex_real);
#endif
RT_TRACE(COMP_POWER_TRACKING, "priv->cck_present_attentuation_difference = %d\n", priv->cck_present_attentuation_difference);
RT_TRACE(COMP_POWER_TRACKING, "priv->cck_present_attentuation = %d\n", priv->cck_present_attentuation);
return;
}
else
{
if(Avg_TSSI_Meas_from_driver < TSSI_13dBm - E_FOR_TX_POWER_TRACK)
{
if((priv->rfa_txpowertrackingindex > 0)
#ifdef RTL8190P
&&(priv->rfc_txpowertrackingindex > 0)
#endif
)
{
priv->rfa_txpowertrackingindex--;
if(priv->rfa_txpowertrackingindex_real > 4)
{
priv->rfa_txpowertrackingindex_real--;
rtl8192_setBBreg(dev, rOFDM0_XATxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfa_txpowertrackingindex_real].txbbgain_value);
}
#ifdef RTL8190P
priv->rfc_txpowertrackingindex--;
if(priv->rfc_txpowertrackingindex_real > 4)
{
priv->rfc_txpowertrackingindex_real--;
rtl8192_setBBreg(dev, rOFDM0_XCTxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfc_txpowertrackingindex_real].txbbgain_value);
}
#endif
}
}
else
{
if((priv->rfa_txpowertrackingindex < 36)
#ifdef RTL8190P
&&(priv->rfc_txpowertrackingindex < 36)
#endif
)
{
priv->rfa_txpowertrackingindex++;
priv->rfa_txpowertrackingindex_real++;
rtl8192_setBBreg(dev, rOFDM0_XATxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfa_txpowertrackingindex_real].txbbgain_value);
#ifdef RTL8190P
priv->rfc_txpowertrackingindex++;
priv->rfc_txpowertrackingindex_real++;
rtl8192_setBBreg(dev, rOFDM0_XCTxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfc_txpowertrackingindex_real].txbbgain_value);
#endif
}
}
priv->cck_present_attentuation_difference
= priv->rfa_txpowertrackingindex - priv->rfa_txpowertracking_default;
if(priv->CurrentChannelBW == HT_CHANNEL_WIDTH_20)
priv->cck_present_attentuation
= priv->cck_present_attentuation_20Mdefault + priv->cck_present_attentuation_difference;
else
priv->cck_present_attentuation
= priv->cck_present_attentuation_40Mdefault + priv->cck_present_attentuation_difference;
if(priv->cck_present_attentuation > -1&&priv->cck_present_attentuation <23)
{
if(priv->ieee80211->current_network.channel == 14 && !priv->bcck_in_ch14)
{
priv->bcck_in_ch14 = TRUE;
dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
}
else if(priv->ieee80211->current_network.channel != 14 && priv->bcck_in_ch14)
{
priv->bcck_in_ch14 = FALSE;
dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
}
else
dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
}
RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex = %d\n", priv->rfa_txpowertrackingindex);
RT_TRACE(COMP_POWER_TRACKING, "priv->rfa_txpowertrackingindex_real = %d\n", priv->rfa_txpowertrackingindex_real);
#ifdef RTL8190P
RT_TRACE(COMP_POWER_TRACKING, "priv->rfc_txpowertrackingindex = %d\n", priv->rfc_txpowertrackingindex);
RT_TRACE(COMP_POWER_TRACKING, "priv->rfc_txpowertrackingindex_real = %d\n", priv->rfc_txpowertrackingindex_real);
#endif
RT_TRACE(COMP_POWER_TRACKING, "priv->cck_present_attentuation_difference = %d\n", priv->cck_present_attentuation_difference);
RT_TRACE(COMP_POWER_TRACKING, "priv->cck_present_attentuation = %d\n", priv->cck_present_attentuation);
if (priv->cck_present_attentuation_difference <= -12||priv->cck_present_attentuation_difference >= 24)
{
priv->ieee80211->bdynamic_txpower_enable = TRUE;
write_nic_byte(dev, 0x1ba, 0);
RT_TRACE(COMP_POWER_TRACKING, "tx power track--->limited\n");
return;
}
}
write_nic_byte(dev, 0x1ba, 0);
Avg_TSSI_Meas_from_driver = 0;
for(k = 0;k < 5; k++)
tmp_report[k] = 0;
break;
}
}
priv->ieee80211->bdynamic_txpower_enable = TRUE;
write_nic_byte(dev, 0x1ba, 0);
}
static void dm_TXPowerTrackingCallback_ThermalMeter(struct net_device * dev)
{
#define ThermalMeterVal 9
struct r8192_priv *priv = ieee80211_priv(dev);
u32 tmpRegA, TempCCk;
u8 tmpOFDMindex, tmpCCKindex, tmpCCK20Mindex, tmpCCK40Mindex, tmpval;
int i =0, CCKSwingNeedUpdate=0;
if(!priv->btxpower_trackingInit)
{
//Query OFDM default setting
tmpRegA= rtl8192_QueryBBReg(dev, rOFDM0_XATxIQImbalance, bMaskDWord);
for(i=0; i<OFDM_Table_Length; i++) //find the index
{
if(tmpRegA == OFDMSwingTable[i])
{
priv->OFDM_index= (u8)i;
RT_TRACE(COMP_POWER_TRACKING, "Initial reg0x%x = 0x%x, OFDM_index=0x%x\n",
rOFDM0_XATxIQImbalance, tmpRegA, priv->OFDM_index);
}
}
//Query CCK default setting From 0xa22
TempCCk = rtl8192_QueryBBReg(dev, rCCK0_TxFilter1, bMaskByte2);
for(i=0 ; i<CCK_Table_length ; i++)
{
if(TempCCk == (u32)CCKSwingTable_Ch1_Ch13[i][0])
{
priv->CCK_index =(u8) i;
RT_TRACE(COMP_POWER_TRACKING, "Initial reg0x%x = 0x%x, CCK_index=0x%x\n",
rCCK0_TxFilter1, TempCCk, priv->CCK_index);
break;
}
}
priv->btxpower_trackingInit = TRUE;
//pHalData->TXPowercount = 0;
return;
}
//==========================
// this is only for test, should be masked
//==========================
// read and filter out unreasonable value
tmpRegA = rtl8192_phy_QueryRFReg(dev, RF90_PATH_A, 0x12, 0x078); // 0x12: RF Reg[10:7]
RT_TRACE(COMP_POWER_TRACKING, "Readback ThermalMeterA = %d \n", tmpRegA);
if(tmpRegA < 3 || tmpRegA > 13)
return;
if(tmpRegA >= 12) // if over 12, TP will be bad when high temprature
tmpRegA = 12;
RT_TRACE(COMP_POWER_TRACKING, "Valid ThermalMeterA = %d \n", tmpRegA);
priv->ThermalMeter[0] = ThermalMeterVal; //We use fixed value by Bryant's suggestion
priv->ThermalMeter[1] = ThermalMeterVal; //We use fixed value by Bryant's suggestion
//Get current RF-A temprature index
if(priv->ThermalMeter[0] >= (u8)tmpRegA) //lower temprature
{
tmpOFDMindex = tmpCCK20Mindex = 6+(priv->ThermalMeter[0]-(u8)tmpRegA);
tmpCCK40Mindex = tmpCCK20Mindex - 6;
if(tmpOFDMindex >= OFDM_Table_Length)
tmpOFDMindex = OFDM_Table_Length-1;
if(tmpCCK20Mindex >= CCK_Table_length)
tmpCCK20Mindex = CCK_Table_length-1;
if(tmpCCK40Mindex >= CCK_Table_length)
tmpCCK40Mindex = CCK_Table_length-1;
}
else
{
tmpval = ((u8)tmpRegA - priv->ThermalMeter[0]);
if(tmpval >= 6) // higher temprature
tmpOFDMindex = tmpCCK20Mindex = 0; // max to +6dB
else
tmpOFDMindex = tmpCCK20Mindex = 6 - tmpval;
tmpCCK40Mindex = 0;
}
//DbgPrint("%ddb, tmpOFDMindex = %d, tmpCCK20Mindex = %d, tmpCCK40Mindex = %d",
//((u1Byte)tmpRegA - pHalData->ThermalMeter[0]),
//tmpOFDMindex, tmpCCK20Mindex, tmpCCK40Mindex);
if(priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20) //40M
tmpCCKindex = tmpCCK40Mindex;
else
tmpCCKindex = tmpCCK20Mindex;
if(priv->ieee80211->current_network.channel == 14 && !priv->bcck_in_ch14)
{
priv->bcck_in_ch14 = TRUE;
CCKSwingNeedUpdate = 1;
}
else if(priv->ieee80211->current_network.channel != 14 && priv->bcck_in_ch14)
{
priv->bcck_in_ch14 = FALSE;
CCKSwingNeedUpdate = 1;
}
if(priv->CCK_index != tmpCCKindex)
{
priv->CCK_index = tmpCCKindex;
CCKSwingNeedUpdate = 1;
}
if(CCKSwingNeedUpdate)
{
//DbgPrint("Update CCK Swing, CCK_index = %d\n", pHalData->CCK_index);
dm_cck_txpower_adjust(dev, priv->bcck_in_ch14);
}
if(priv->OFDM_index != tmpOFDMindex)
{
priv->OFDM_index = tmpOFDMindex;
rtl8192_setBBreg(dev, rOFDM0_XATxIQImbalance, bMaskDWord, OFDMSwingTable[priv->OFDM_index]);
RT_TRACE(COMP_POWER_TRACKING, "Update OFDMSwing[%d] = 0x%x\n",
priv->OFDM_index, OFDMSwingTable[priv->OFDM_index]);
}
priv->txpower_count = 0;
}
extern void dm_txpower_trackingcallback(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work,struct delayed_work,work);
struct r8192_priv *priv = container_of(dwork,struct r8192_priv,txpower_tracking_wq);
struct net_device *dev = priv->ieee80211->dev;
#ifdef RTL8190P
dm_TXPowerTrackingCallback_TSSI(dev);
#else
if(priv->bDcut == TRUE)
dm_TXPowerTrackingCallback_TSSI(dev);
else
dm_TXPowerTrackingCallback_ThermalMeter(dev);
#endif
}
static void dm_InitializeTXPowerTracking_TSSI(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
//Initial the Tx BB index and mapping value
priv->txbbgain_table[0].txbb_iq_amplifygain = 12;
priv->txbbgain_table[0].txbbgain_value=0x7f8001fe;
priv->txbbgain_table[1].txbb_iq_amplifygain = 11;
priv->txbbgain_table[1].txbbgain_value=0x788001e2;
priv->txbbgain_table[2].txbb_iq_amplifygain = 10;
priv->txbbgain_table[2].txbbgain_value=0x71c001c7;
priv->txbbgain_table[3].txbb_iq_amplifygain = 9;
priv->txbbgain_table[3].txbbgain_value=0x6b8001ae;
priv->txbbgain_table[4].txbb_iq_amplifygain = 8;
priv->txbbgain_table[4].txbbgain_value=0x65400195;
priv->txbbgain_table[5].txbb_iq_amplifygain = 7;
priv->txbbgain_table[5].txbbgain_value=0x5fc0017f;
priv->txbbgain_table[6].txbb_iq_amplifygain = 6;
priv->txbbgain_table[6].txbbgain_value=0x5a400169;
priv->txbbgain_table[7].txbb_iq_amplifygain = 5;
priv->txbbgain_table[7].txbbgain_value=0x55400155;
priv->txbbgain_table[8].txbb_iq_amplifygain = 4;
priv->txbbgain_table[8].txbbgain_value=0x50800142;
priv->txbbgain_table[9].txbb_iq_amplifygain = 3;
priv->txbbgain_table[9].txbbgain_value=0x4c000130;
priv->txbbgain_table[10].txbb_iq_amplifygain = 2;
priv->txbbgain_table[10].txbbgain_value=0x47c0011f;
priv->txbbgain_table[11].txbb_iq_amplifygain = 1;
priv->txbbgain_table[11].txbbgain_value=0x43c0010f;
priv->txbbgain_table[12].txbb_iq_amplifygain = 0;
priv->txbbgain_table[12].txbbgain_value=0x40000100;
priv->txbbgain_table[13].txbb_iq_amplifygain = -1;
priv->txbbgain_table[13].txbbgain_value=0x3c8000f2;
priv->txbbgain_table[14].txbb_iq_amplifygain = -2;
priv->txbbgain_table[14].txbbgain_value=0x390000e4;
priv->txbbgain_table[15].txbb_iq_amplifygain = -3;
priv->txbbgain_table[15].txbbgain_value=0x35c000d7;
priv->txbbgain_table[16].txbb_iq_amplifygain = -4;
priv->txbbgain_table[16].txbbgain_value=0x32c000cb;
priv->txbbgain_table[17].txbb_iq_amplifygain = -5;
priv->txbbgain_table[17].txbbgain_value=0x300000c0;
priv->txbbgain_table[18].txbb_iq_amplifygain = -6;
priv->txbbgain_table[18].txbbgain_value=0x2d4000b5;
priv->txbbgain_table[19].txbb_iq_amplifygain = -7;
priv->txbbgain_table[19].txbbgain_value=0x2ac000ab;
priv->txbbgain_table[20].txbb_iq_amplifygain = -8;
priv->txbbgain_table[20].txbbgain_value=0x288000a2;
priv->txbbgain_table[21].txbb_iq_amplifygain = -9;
priv->txbbgain_table[21].txbbgain_value=0x26000098;
priv->txbbgain_table[22].txbb_iq_amplifygain = -10;
priv->txbbgain_table[22].txbbgain_value=0x24000090;
priv->txbbgain_table[23].txbb_iq_amplifygain = -11;
priv->txbbgain_table[23].txbbgain_value=0x22000088;
priv->txbbgain_table[24].txbb_iq_amplifygain = -12;
priv->txbbgain_table[24].txbbgain_value=0x20000080;
priv->txbbgain_table[25].txbb_iq_amplifygain = -13;
priv->txbbgain_table[25].txbbgain_value=0x1a00006c;
priv->txbbgain_table[26].txbb_iq_amplifygain = -14;
priv->txbbgain_table[26].txbbgain_value=0x1c800072;
priv->txbbgain_table[27].txbb_iq_amplifygain = -15;
priv->txbbgain_table[27].txbbgain_value=0x18000060;
priv->txbbgain_table[28].txbb_iq_amplifygain = -16;
priv->txbbgain_table[28].txbbgain_value=0x19800066;
priv->txbbgain_table[29].txbb_iq_amplifygain = -17;
priv->txbbgain_table[29].txbbgain_value=0x15800056;
priv->txbbgain_table[30].txbb_iq_amplifygain = -18;
priv->txbbgain_table[30].txbbgain_value=0x26c0005b;
priv->txbbgain_table[31].txbb_iq_amplifygain = -19;
priv->txbbgain_table[31].txbbgain_value=0x14400051;
priv->txbbgain_table[32].txbb_iq_amplifygain = -20;
priv->txbbgain_table[32].txbbgain_value=0x24400051;
priv->txbbgain_table[33].txbb_iq_amplifygain = -21;
priv->txbbgain_table[33].txbbgain_value=0x1300004c;
priv->txbbgain_table[34].txbb_iq_amplifygain = -22;
priv->txbbgain_table[34].txbbgain_value=0x12000048;
priv->txbbgain_table[35].txbb_iq_amplifygain = -23;
priv->txbbgain_table[35].txbbgain_value=0x11000044;
priv->txbbgain_table[36].txbb_iq_amplifygain = -24;
priv->txbbgain_table[36].txbbgain_value=0x10000040;
//ccktxbb_valuearray[0] is 0xA22 [1] is 0xA24 ...[7] is 0xA29
//This Table is for CH1~CH13
priv->cck_txbbgain_table[0].ccktxbb_valuearray[0] = 0x36;
priv->cck_txbbgain_table[0].ccktxbb_valuearray[1] = 0x35;
priv->cck_txbbgain_table[0].ccktxbb_valuearray[2] = 0x2e;
priv->cck_txbbgain_table[0].ccktxbb_valuearray[3] = 0x25;
priv->cck_txbbgain_table[0].ccktxbb_valuearray[4] = 0x1c;
priv->cck_txbbgain_table[0].ccktxbb_valuearray[5] = 0x12;
priv->cck_txbbgain_table[0].ccktxbb_valuearray[6] = 0x09;
priv->cck_txbbgain_table[0].ccktxbb_valuearray[7] = 0x04;
priv->cck_txbbgain_table[1].ccktxbb_valuearray[0] = 0x33;
priv->cck_txbbgain_table[1].ccktxbb_valuearray[1] = 0x32;
priv->cck_txbbgain_table[1].ccktxbb_valuearray[2] = 0x2b;
priv->cck_txbbgain_table[1].ccktxbb_valuearray[3] = 0x23;
priv->cck_txbbgain_table[1].ccktxbb_valuearray[4] = 0x1a;
priv->cck_txbbgain_table[1].ccktxbb_valuearray[5] = 0x11;
priv->cck_txbbgain_table[1].ccktxbb_valuearray[6] = 0x08;
priv->cck_txbbgain_table[1].ccktxbb_valuearray[7] = 0x04;
priv->cck_txbbgain_table[2].ccktxbb_valuearray[0] = 0x30;
priv->cck_txbbgain_table[2].ccktxbb_valuearray[1] = 0x2f;
priv->cck_txbbgain_table[2].ccktxbb_valuearray[2] = 0x29;
priv->cck_txbbgain_table[2].ccktxbb_valuearray[3] = 0x21;
priv->cck_txbbgain_table[2].ccktxbb_valuearray[4] = 0x19;
priv->cck_txbbgain_table[2].ccktxbb_valuearray[5] = 0x10;
priv->cck_txbbgain_table[2].ccktxbb_valuearray[6] = 0x08;
priv->cck_txbbgain_table[2].ccktxbb_valuearray[7] = 0x03;
priv->cck_txbbgain_table[3].ccktxbb_valuearray[0] = 0x2d;
priv->cck_txbbgain_table[3].ccktxbb_valuearray[1] = 0x2d;
priv->cck_txbbgain_table[3].ccktxbb_valuearray[2] = 0x27;
priv->cck_txbbgain_table[3].ccktxbb_valuearray[3] = 0x1f;
priv->cck_txbbgain_table[3].ccktxbb_valuearray[4] = 0x18;
priv->cck_txbbgain_table[3].ccktxbb_valuearray[5] = 0x0f;
priv->cck_txbbgain_table[3].ccktxbb_valuearray[6] = 0x08;
priv->cck_txbbgain_table[3].ccktxbb_valuearray[7] = 0x03;
priv->cck_txbbgain_table[4].ccktxbb_valuearray[0] = 0x2b;
priv->cck_txbbgain_table[4].ccktxbb_valuearray[1] = 0x2a;
priv->cck_txbbgain_table[4].ccktxbb_valuearray[2] = 0x25;
priv->cck_txbbgain_table[4].ccktxbb_valuearray[3] = 0x1e;
priv->cck_txbbgain_table[4].ccktxbb_valuearray[4] = 0x16;
priv->cck_txbbgain_table[4].ccktxbb_valuearray[5] = 0x0e;
priv->cck_txbbgain_table[4].ccktxbb_valuearray[6] = 0x07;
priv->cck_txbbgain_table[4].ccktxbb_valuearray[7] = 0x03;
priv->cck_txbbgain_table[5].ccktxbb_valuearray[0] = 0x28;
priv->cck_txbbgain_table[5].ccktxbb_valuearray[1] = 0x28;
priv->cck_txbbgain_table[5].ccktxbb_valuearray[2] = 0x22;
priv->cck_txbbgain_table[5].ccktxbb_valuearray[3] = 0x1c;
priv->cck_txbbgain_table[5].ccktxbb_valuearray[4] = 0x15;
priv->cck_txbbgain_table[5].ccktxbb_valuearray[5] = 0x0d;
priv->cck_txbbgain_table[5].ccktxbb_valuearray[6] = 0x07;
priv->cck_txbbgain_table[5].ccktxbb_valuearray[7] = 0x03;
priv->cck_txbbgain_table[6].ccktxbb_valuearray[0] = 0x26;
priv->cck_txbbgain_table[6].ccktxbb_valuearray[1] = 0x25;
priv->cck_txbbgain_table[6].ccktxbb_valuearray[2] = 0x21;
priv->cck_txbbgain_table[6].ccktxbb_valuearray[3] = 0x1b;
priv->cck_txbbgain_table[6].ccktxbb_valuearray[4] = 0x14;
priv->cck_txbbgain_table[6].ccktxbb_valuearray[5] = 0x0d;
priv->cck_txbbgain_table[6].ccktxbb_valuearray[6] = 0x06;
priv->cck_txbbgain_table[6].ccktxbb_valuearray[7] = 0x03;
priv->cck_txbbgain_table[7].ccktxbb_valuearray[0] = 0x24;
priv->cck_txbbgain_table[7].ccktxbb_valuearray[1] = 0x23;
priv->cck_txbbgain_table[7].ccktxbb_valuearray[2] = 0x1f;
priv->cck_txbbgain_table[7].ccktxbb_valuearray[3] = 0x19;
priv->cck_txbbgain_table[7].ccktxbb_valuearray[4] = 0x13;
priv->cck_txbbgain_table[7].ccktxbb_valuearray[5] = 0x0c;
priv->cck_txbbgain_table[7].ccktxbb_valuearray[6] = 0x06;
priv->cck_txbbgain_table[7].ccktxbb_valuearray[7] = 0x03;
priv->cck_txbbgain_table[8].ccktxbb_valuearray[0] = 0x22;
priv->cck_txbbgain_table[8].ccktxbb_valuearray[1] = 0x21;
priv->cck_txbbgain_table[8].ccktxbb_valuearray[2] = 0x1d;
priv->cck_txbbgain_table[8].ccktxbb_valuearray[3] = 0x18;
priv->cck_txbbgain_table[8].ccktxbb_valuearray[4] = 0x11;
priv->cck_txbbgain_table[8].ccktxbb_valuearray[5] = 0x0b;
priv->cck_txbbgain_table[8].ccktxbb_valuearray[6] = 0x06;
priv->cck_txbbgain_table[8].ccktxbb_valuearray[7] = 0x02;
priv->cck_txbbgain_table[9].ccktxbb_valuearray[0] = 0x20;
priv->cck_txbbgain_table[9].ccktxbb_valuearray[1] = 0x20;
priv->cck_txbbgain_table[9].ccktxbb_valuearray[2] = 0x1b;
priv->cck_txbbgain_table[9].ccktxbb_valuearray[3] = 0x16;
priv->cck_txbbgain_table[9].ccktxbb_valuearray[4] = 0x11;
priv->cck_txbbgain_table[9].ccktxbb_valuearray[5] = 0x08;
priv->cck_txbbgain_table[9].ccktxbb_valuearray[6] = 0x05;
priv->cck_txbbgain_table[9].ccktxbb_valuearray[7] = 0x02;
priv->cck_txbbgain_table[10].ccktxbb_valuearray[0] = 0x1f;
priv->cck_txbbgain_table[10].ccktxbb_valuearray[1] = 0x1e;
priv->cck_txbbgain_table[10].ccktxbb_valuearray[2] = 0x1a;
priv->cck_txbbgain_table[10].ccktxbb_valuearray[3] = 0x15;
priv->cck_txbbgain_table[10].ccktxbb_valuearray[4] = 0x10;
priv->cck_txbbgain_table[10].ccktxbb_valuearray[5] = 0x0a;
priv->cck_txbbgain_table[10].ccktxbb_valuearray[6] = 0x05;
priv->cck_txbbgain_table[10].ccktxbb_valuearray[7] = 0x02;
priv->cck_txbbgain_table[11].ccktxbb_valuearray[0] = 0x1d;
priv->cck_txbbgain_table[11].ccktxbb_valuearray[1] = 0x1c;
priv->cck_txbbgain_table[11].ccktxbb_valuearray[2] = 0x18;
priv->cck_txbbgain_table[11].ccktxbb_valuearray[3] = 0x14;
priv->cck_txbbgain_table[11].ccktxbb_valuearray[4] = 0x0f;
priv->cck_txbbgain_table[11].ccktxbb_valuearray[5] = 0x0a;
priv->cck_txbbgain_table[11].ccktxbb_valuearray[6] = 0x05;
priv->cck_txbbgain_table[11].ccktxbb_valuearray[7] = 0x02;
priv->cck_txbbgain_table[12].ccktxbb_valuearray[0] = 0x1b;
priv->cck_txbbgain_table[12].ccktxbb_valuearray[1] = 0x1a;
priv->cck_txbbgain_table[12].ccktxbb_valuearray[2] = 0x17;
priv->cck_txbbgain_table[12].ccktxbb_valuearray[3] = 0x13;
priv->cck_txbbgain_table[12].ccktxbb_valuearray[4] = 0x0e;
priv->cck_txbbgain_table[12].ccktxbb_valuearray[5] = 0x09;
priv->cck_txbbgain_table[12].ccktxbb_valuearray[6] = 0x04;
priv->cck_txbbgain_table[12].ccktxbb_valuearray[7] = 0x02;
priv->cck_txbbgain_table[13].ccktxbb_valuearray[0] = 0x1a;
priv->cck_txbbgain_table[13].ccktxbb_valuearray[1] = 0x19;
priv->cck_txbbgain_table[13].ccktxbb_valuearray[2] = 0x16;
priv->cck_txbbgain_table[13].ccktxbb_valuearray[3] = 0x12;
priv->cck_txbbgain_table[13].ccktxbb_valuearray[4] = 0x0d;
priv->cck_txbbgain_table[13].ccktxbb_valuearray[5] = 0x09;
priv->cck_txbbgain_table[13].ccktxbb_valuearray[6] = 0x04;
priv->cck_txbbgain_table[13].ccktxbb_valuearray[7] = 0x02;
priv->cck_txbbgain_table[14].ccktxbb_valuearray[0] = 0x18;
priv->cck_txbbgain_table[14].ccktxbb_valuearray[1] = 0x17;
priv->cck_txbbgain_table[14].ccktxbb_valuearray[2] = 0x15;
priv->cck_txbbgain_table[14].ccktxbb_valuearray[3] = 0x11;
priv->cck_txbbgain_table[14].ccktxbb_valuearray[4] = 0x0c;
priv->cck_txbbgain_table[14].ccktxbb_valuearray[5] = 0x08;
priv->cck_txbbgain_table[14].ccktxbb_valuearray[6] = 0x04;
priv->cck_txbbgain_table[14].ccktxbb_valuearray[7] = 0x02;
priv->cck_txbbgain_table[15].ccktxbb_valuearray[0] = 0x17;
priv->cck_txbbgain_table[15].ccktxbb_valuearray[1] = 0x16;
priv->cck_txbbgain_table[15].ccktxbb_valuearray[2] = 0x13;
priv->cck_txbbgain_table[15].ccktxbb_valuearray[3] = 0x10;
priv->cck_txbbgain_table[15].ccktxbb_valuearray[4] = 0x0c;
priv->cck_txbbgain_table[15].ccktxbb_valuearray[5] = 0x08;
priv->cck_txbbgain_table[15].ccktxbb_valuearray[6] = 0x04;
priv->cck_txbbgain_table[15].ccktxbb_valuearray[7] = 0x02;
priv->cck_txbbgain_table[16].ccktxbb_valuearray[0] = 0x16;
priv->cck_txbbgain_table[16].ccktxbb_valuearray[1] = 0x15;
priv->cck_txbbgain_table[16].ccktxbb_valuearray[2] = 0x12;
priv->cck_txbbgain_table[16].ccktxbb_valuearray[3] = 0x0f;
priv->cck_txbbgain_table[16].ccktxbb_valuearray[4] = 0x0b;
priv->cck_txbbgain_table[16].ccktxbb_valuearray[5] = 0x07;
priv->cck_txbbgain_table[16].ccktxbb_valuearray[6] = 0x04;
priv->cck_txbbgain_table[16].ccktxbb_valuearray[7] = 0x01;
priv->cck_txbbgain_table[17].ccktxbb_valuearray[0] = 0x14;
priv->cck_txbbgain_table[17].ccktxbb_valuearray[1] = 0x14;
priv->cck_txbbgain_table[17].ccktxbb_valuearray[2] = 0x11;
priv->cck_txbbgain_table[17].ccktxbb_valuearray[3] = 0x0e;
priv->cck_txbbgain_table[17].ccktxbb_valuearray[4] = 0x0b;
priv->cck_txbbgain_table[17].ccktxbb_valuearray[5] = 0x07;
priv->cck_txbbgain_table[17].ccktxbb_valuearray[6] = 0x03;
priv->cck_txbbgain_table[17].ccktxbb_valuearray[7] = 0x02;
priv->cck_txbbgain_table[18].ccktxbb_valuearray[0] = 0x13;
priv->cck_txbbgain_table[18].ccktxbb_valuearray[1] = 0x13;
priv->cck_txbbgain_table[18].ccktxbb_valuearray[2] = 0x10;
priv->cck_txbbgain_table[18].ccktxbb_valuearray[3] = 0x0d;
priv->cck_txbbgain_table[18].ccktxbb_valuearray[4] = 0x0a;
priv->cck_txbbgain_table[18].ccktxbb_valuearray[5] = 0x06;
priv->cck_txbbgain_table[18].ccktxbb_valuearray[6] = 0x03;
priv->cck_txbbgain_table[18].ccktxbb_valuearray[7] = 0x01;
priv->cck_txbbgain_table[19].ccktxbb_valuearray[0] = 0x12;
priv->cck_txbbgain_table[19].ccktxbb_valuearray[1] = 0x12;
priv->cck_txbbgain_table[19].ccktxbb_valuearray[2] = 0x0f;
priv->cck_txbbgain_table[19].ccktxbb_valuearray[3] = 0x0c;
priv->cck_txbbgain_table[19].ccktxbb_valuearray[4] = 0x09;
priv->cck_txbbgain_table[19].ccktxbb_valuearray[5] = 0x06;
priv->cck_txbbgain_table[19].ccktxbb_valuearray[6] = 0x03;
priv->cck_txbbgain_table[19].ccktxbb_valuearray[7] = 0x01;
priv->cck_txbbgain_table[20].ccktxbb_valuearray[0] = 0x11;
priv->cck_txbbgain_table[20].ccktxbb_valuearray[1] = 0x11;
priv->cck_txbbgain_table[20].ccktxbb_valuearray[2] = 0x0f;
priv->cck_txbbgain_table[20].ccktxbb_valuearray[3] = 0x0c;
priv->cck_txbbgain_table[20].ccktxbb_valuearray[4] = 0x09;
priv->cck_txbbgain_table[20].ccktxbb_valuearray[5] = 0x06;
priv->cck_txbbgain_table[20].ccktxbb_valuearray[6] = 0x03;
priv->cck_txbbgain_table[20].ccktxbb_valuearray[7] = 0x01;
priv->cck_txbbgain_table[21].ccktxbb_valuearray[0] = 0x10;
priv->cck_txbbgain_table[21].ccktxbb_valuearray[1] = 0x10;
priv->cck_txbbgain_table[21].ccktxbb_valuearray[2] = 0x0e;
priv->cck_txbbgain_table[21].ccktxbb_valuearray[3] = 0x0b;
priv->cck_txbbgain_table[21].ccktxbb_valuearray[4] = 0x08;
priv->cck_txbbgain_table[21].ccktxbb_valuearray[5] = 0x05;
priv->cck_txbbgain_table[21].ccktxbb_valuearray[6] = 0x03;
priv->cck_txbbgain_table[21].ccktxbb_valuearray[7] = 0x01;
priv->cck_txbbgain_table[22].ccktxbb_valuearray[0] = 0x0f;
priv->cck_txbbgain_table[22].ccktxbb_valuearray[1] = 0x0f;
priv->cck_txbbgain_table[22].ccktxbb_valuearray[2] = 0x0d;
priv->cck_txbbgain_table[22].ccktxbb_valuearray[3] = 0x0b;
priv->cck_txbbgain_table[22].ccktxbb_valuearray[4] = 0x08;
priv->cck_txbbgain_table[22].ccktxbb_valuearray[5] = 0x05;
priv->cck_txbbgain_table[22].ccktxbb_valuearray[6] = 0x03;
priv->cck_txbbgain_table[22].ccktxbb_valuearray[7] = 0x01;
//ccktxbb_valuearray[0] is 0xA22 [1] is 0xA24 ...[7] is 0xA29
//This Table is for CH14
priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[0] = 0x36;
priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[1] = 0x35;
priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[2] = 0x2e;
priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[3] = 0x1b;
priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[0].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[0] = 0x33;
priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[1] = 0x32;
priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[2] = 0x2b;
priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[3] = 0x19;
priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[1].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[0] = 0x30;
priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[1] = 0x2f;
priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[2] = 0x29;
priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[3] = 0x18;
priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[2].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[0] = 0x2d;
priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[1] = 0x2d;
priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[2] = 0x27;
priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[3] = 0x17;
priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[3].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[0] = 0x2b;
priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[1] = 0x2a;
priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[2] = 0x25;
priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[3] = 0x15;
priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[4].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[0] = 0x28;
priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[1] = 0x28;
priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[2] = 0x22;
priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[3] = 0x14;
priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[5].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[0] = 0x26;
priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[1] = 0x25;
priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[2] = 0x21;
priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[3] = 0x13;
priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[6].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[0] = 0x24;
priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[1] = 0x23;
priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[2] = 0x1f;
priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[3] = 0x12;
priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[7].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[0] = 0x22;
priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[1] = 0x21;
priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[2] = 0x1d;
priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[3] = 0x11;
priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[8].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[0] = 0x20;
priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[1] = 0x20;
priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[2] = 0x1b;
priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[3] = 0x10;
priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[9].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[0] = 0x1f;
priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[1] = 0x1e;
priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[2] = 0x1a;
priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[3] = 0x0f;
priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[10].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[0] = 0x1d;
priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[1] = 0x1c;
priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[2] = 0x18;
priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[3] = 0x0e;
priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[11].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[0] = 0x1b;
priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[1] = 0x1a;
priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[2] = 0x17;
priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[3] = 0x0e;
priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[12].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[0] = 0x1a;
priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[1] = 0x19;
priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[2] = 0x16;
priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[3] = 0x0d;
priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[13].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[0] = 0x18;
priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[1] = 0x17;
priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[2] = 0x15;
priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[3] = 0x0c;
priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[14].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[0] = 0x17;
priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[1] = 0x16;
priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[2] = 0x13;
priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[3] = 0x0b;
priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[15].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[0] = 0x16;
priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[1] = 0x15;
priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[2] = 0x12;
priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[3] = 0x0b;
priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[16].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[0] = 0x14;
priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[1] = 0x14;
priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[2] = 0x11;
priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[3] = 0x0a;
priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[17].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[0] = 0x13;
priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[1] = 0x13;
priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[2] = 0x10;
priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[3] = 0x0a;
priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[18].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[0] = 0x12;
priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[1] = 0x12;
priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[2] = 0x0f;
priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[3] = 0x09;
priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[19].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[0] = 0x11;
priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[1] = 0x11;
priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[2] = 0x0f;
priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[3] = 0x09;
priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[20].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[0] = 0x10;
priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[1] = 0x10;
priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[2] = 0x0e;
priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[3] = 0x08;
priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[21].ccktxbb_valuearray[7] = 0x00;
priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[0] = 0x0f;
priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[1] = 0x0f;
priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[2] = 0x0d;
priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[3] = 0x08;
priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[4] = 0x00;
priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[5] = 0x00;
priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[6] = 0x00;
priv->cck_txbbgain_ch14_table[22].ccktxbb_valuearray[7] = 0x00;
priv->btxpower_tracking = TRUE;
priv->txpower_count = 0;
priv->btxpower_trackingInit = FALSE;
}
static void dm_InitializeTXPowerTracking_ThermalMeter(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
// Tx Power tracking by Theremal Meter require Firmware R/W 3-wire. This mechanism
// can be enabled only when Firmware R/W 3-wire is enabled. Otherwise, frequent r/w
// 3-wire by driver cause RF goes into wrong state.
if(priv->ieee80211->FwRWRF)
priv->btxpower_tracking = TRUE;
else
priv->btxpower_tracking = FALSE;
priv->txpower_count = 0;
priv->btxpower_trackingInit = FALSE;
}
void dm_initialize_txpower_tracking(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
#ifdef RTL8190P
dm_InitializeTXPowerTracking_TSSI(dev);
#else
if(priv->bDcut == TRUE)
dm_InitializeTXPowerTracking_TSSI(dev);
else
dm_InitializeTXPowerTracking_ThermalMeter(dev);
#endif
}// dm_InitializeTXPowerTracking
static void dm_CheckTXPowerTracking_TSSI(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
static u32 tx_power_track_counter = 0;
if(!priv->btxpower_tracking)
return;
else
{
if((tx_power_track_counter % 30 == 0)&&(tx_power_track_counter != 0))
{
queue_delayed_work(priv->priv_wq,&priv->txpower_tracking_wq,0);
}
tx_power_track_counter++;
}
}
static void dm_CheckTXPowerTracking_ThermalMeter(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
static u8 TM_Trigger=0;
//DbgPrint("dm_CheckTXPowerTracking() \n");
if(!priv->btxpower_tracking)
return;
else
{
if(priv->txpower_count <= 2)
{
priv->txpower_count++;
return;
}
}
if(!TM_Trigger)
{
//Attention!! You have to wirte all 12bits data to RF, or it may cause RF to crash
//actually write reg0x02 bit1=0, then bit1=1.
//DbgPrint("Trigger ThermalMeter, write RF reg0x2 = 0x4d to 0x4f\n");
rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bMask12Bits, 0x4d);
rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bMask12Bits, 0x4f);
rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bMask12Bits, 0x4d);
rtl8192_phy_SetRFReg(dev, RF90_PATH_A, 0x02, bMask12Bits, 0x4f);
TM_Trigger = 1;
return;
}
else
{
//DbgPrint("Schedule TxPowerTrackingWorkItem\n");
queue_delayed_work(priv->priv_wq,&priv->txpower_tracking_wq,0);
TM_Trigger = 0;
}
}
static void dm_check_txpower_tracking(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
//static u32 tx_power_track_counter = 0;
#ifdef RTL8190P
dm_CheckTXPowerTracking_TSSI(dev);
#else
if(priv->bDcut == TRUE)
dm_CheckTXPowerTracking_TSSI(dev);
else
dm_CheckTXPowerTracking_ThermalMeter(dev);
#endif
} // dm_CheckTXPowerTracking
static void dm_CCKTxPowerAdjust_TSSI(struct net_device *dev, bool bInCH14)
{
u32 TempVal;
struct r8192_priv *priv = ieee80211_priv(dev);
//Write 0xa22 0xa23
TempVal = 0;
if(!bInCH14){
//Write 0xa22 0xa23
TempVal = priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[0] +
(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[1]<<8) ;
rtl8192_setBBreg(dev, rCCK0_TxFilter1,bMaskHWord, TempVal);
//Write 0xa24 ~ 0xa27
TempVal = 0;
TempVal = priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[2] +
(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[3]<<8) +
(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[4]<<16 )+
(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[5]<<24);
rtl8192_setBBreg(dev, rCCK0_TxFilter2,bMaskDWord, TempVal);
//Write 0xa28 0xa29
TempVal = 0;
TempVal = priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[6] +
(priv->cck_txbbgain_table[priv->cck_present_attentuation].ccktxbb_valuearray[7]<<8) ;
rtl8192_setBBreg(dev, rCCK0_DebugPort,bMaskLWord, TempVal);
}
else
{
TempVal = priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[0] +
(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[1]<<8) ;
rtl8192_setBBreg(dev, rCCK0_TxFilter1,bMaskHWord, TempVal);
//Write 0xa24 ~ 0xa27
TempVal = 0;
TempVal = priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[2] +
(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[3]<<8) +
(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[4]<<16 )+
(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[5]<<24);
rtl8192_setBBreg(dev, rCCK0_TxFilter2,bMaskDWord, TempVal);
//Write 0xa28 0xa29
TempVal = 0;
TempVal = priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[6] +
(priv->cck_txbbgain_ch14_table[priv->cck_present_attentuation].ccktxbb_valuearray[7]<<8) ;
rtl8192_setBBreg(dev, rCCK0_DebugPort,bMaskLWord, TempVal);
}
}
static void dm_CCKTxPowerAdjust_ThermalMeter(struct net_device *dev, bool bInCH14)
{
u32 TempVal;
struct r8192_priv *priv = ieee80211_priv(dev);
TempVal = 0;
if(!bInCH14)
{
//Write 0xa22 0xa23
TempVal = CCKSwingTable_Ch1_Ch13[priv->CCK_index][0] +
(CCKSwingTable_Ch1_Ch13[priv->CCK_index][1]<<8) ;
rtl8192_setBBreg(dev, rCCK0_TxFilter1, bMaskHWord, TempVal);
RT_TRACE(COMP_POWER_TRACKING, "CCK not chnl 14, reg 0x%x = 0x%x\n",
rCCK0_TxFilter1, TempVal);
//Write 0xa24 ~ 0xa27
TempVal = 0;
TempVal = CCKSwingTable_Ch1_Ch13[priv->CCK_index][2] +
(CCKSwingTable_Ch1_Ch13[priv->CCK_index][3]<<8) +
(CCKSwingTable_Ch1_Ch13[priv->CCK_index][4]<<16 )+
(CCKSwingTable_Ch1_Ch13[priv->CCK_index][5]<<24);
rtl8192_setBBreg(dev, rCCK0_TxFilter2, bMaskDWord, TempVal);
RT_TRACE(COMP_POWER_TRACKING, "CCK not chnl 14, reg 0x%x = 0x%x\n",
rCCK0_TxFilter2, TempVal);
//Write 0xa28 0xa29
TempVal = 0;
TempVal = CCKSwingTable_Ch1_Ch13[priv->CCK_index][6] +
(CCKSwingTable_Ch1_Ch13[priv->CCK_index][7]<<8) ;
rtl8192_setBBreg(dev, rCCK0_DebugPort, bMaskLWord, TempVal);
RT_TRACE(COMP_POWER_TRACKING, "CCK not chnl 14, reg 0x%x = 0x%x\n",
rCCK0_DebugPort, TempVal);
}
else
{
// priv->CCKTxPowerAdjustCntNotCh14++; //cosa add for debug.
//Write 0xa22 0xa23
TempVal = CCKSwingTable_Ch14[priv->CCK_index][0] +
(CCKSwingTable_Ch14[priv->CCK_index][1]<<8) ;
rtl8192_setBBreg(dev, rCCK0_TxFilter1, bMaskHWord, TempVal);
RT_TRACE(COMP_POWER_TRACKING, "CCK chnl 14, reg 0x%x = 0x%x\n",
rCCK0_TxFilter1, TempVal);
//Write 0xa24 ~ 0xa27
TempVal = 0;
TempVal = CCKSwingTable_Ch14[priv->CCK_index][2] +
(CCKSwingTable_Ch14[priv->CCK_index][3]<<8) +
(CCKSwingTable_Ch14[priv->CCK_index][4]<<16 )+
(CCKSwingTable_Ch14[priv->CCK_index][5]<<24);
rtl8192_setBBreg(dev, rCCK0_TxFilter2, bMaskDWord, TempVal);
RT_TRACE(COMP_POWER_TRACKING, "CCK chnl 14, reg 0x%x = 0x%x\n",
rCCK0_TxFilter2, TempVal);
//Write 0xa28 0xa29
TempVal = 0;
TempVal = CCKSwingTable_Ch14[priv->CCK_index][6] +
(CCKSwingTable_Ch14[priv->CCK_index][7]<<8) ;
rtl8192_setBBreg(dev, rCCK0_DebugPort, bMaskLWord, TempVal);
RT_TRACE(COMP_POWER_TRACKING,"CCK chnl 14, reg 0x%x = 0x%x\n",
rCCK0_DebugPort, TempVal);
}
}
extern void dm_cck_txpower_adjust(
struct net_device *dev,
bool binch14
)
{ // dm_CCKTxPowerAdjust
struct r8192_priv *priv = ieee80211_priv(dev);
#ifdef RTL8190P
dm_CCKTxPowerAdjust_TSSI(dev, binch14);
#else
if(priv->bDcut == TRUE)
dm_CCKTxPowerAdjust_TSSI(dev, binch14);
else
dm_CCKTxPowerAdjust_ThermalMeter(dev, binch14);
#endif
}
#ifndef RTL8192U
static void dm_txpower_reset_recovery(
struct net_device *dev
)
{
struct r8192_priv *priv = ieee80211_priv(dev);
RT_TRACE(COMP_POWER_TRACKING, "Start Reset Recovery ==>\n");
rtl8192_setBBreg(dev, rOFDM0_XATxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfa_txpowertrackingindex].txbbgain_value);
RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: Fill in 0xc80 is %08x\n",priv->txbbgain_table[priv->rfa_txpowertrackingindex].txbbgain_value);
RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: Fill in RFA_txPowerTrackingIndex is %x\n",priv->rfa_txpowertrackingindex);
RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery : RF A I/Q Amplify Gain is %ld\n",priv->txbbgain_table[priv->rfa_txpowertrackingindex].txbb_iq_amplifygain);
RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: CCK Attenuation is %d dB\n",priv->cck_present_attentuation);
dm_cck_txpower_adjust(dev,priv->bcck_in_ch14);
rtl8192_setBBreg(dev, rOFDM0_XCTxIQImbalance, bMaskDWord, priv->txbbgain_table[priv->rfc_txpowertrackingindex].txbbgain_value);
RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: Fill in 0xc90 is %08x\n",priv->txbbgain_table[priv->rfc_txpowertrackingindex].txbbgain_value);
RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery: Fill in RFC_txPowerTrackingIndex is %x\n",priv->rfc_txpowertrackingindex);
RT_TRACE(COMP_POWER_TRACKING, "Reset Recovery : RF C I/Q Amplify Gain is %ld\n",priv->txbbgain_table[priv->rfc_txpowertrackingindex].txbb_iq_amplifygain);
} // dm_TXPowerResetRecovery
extern void dm_restore_dynamic_mechanism_state(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
u32 reg_ratr = priv->rate_adaptive.last_ratr;
if(!priv->up)
{
RT_TRACE(COMP_RATE, "<---- dm_restore_dynamic_mechanism_state(): driver is going to unload\n");
return;
}
//
// Restore previous state for rate adaptive
//
if(priv->rate_adaptive.rate_adaptive_disabled)
return;
// TODO: Only 11n mode is implemented currently,
if( !(priv->ieee80211->mode==WIRELESS_MODE_N_24G ||
priv->ieee80211->mode==WIRELESS_MODE_N_5G))
return;
{
/* 2007/11/15 MH Copy from 8190PCI. */
u32 ratr_value;
ratr_value = reg_ratr;
if(priv->rf_type == RF_1T2R) // 1T2R, Spatial Stream 2 should be disabled
{
ratr_value &=~ (RATE_ALL_OFDM_2SS);
//DbgPrint("HW_VAR_TATR_0 from 0x%x ==> 0x%x\n", ((pu4Byte)(val))[0], ratr_value);
}
//DbgPrint("set HW_VAR_TATR_0 = 0x%x\n", ratr_value);
//cosa PlatformEFIOWrite4Byte(Adapter, RATR0, ((pu4Byte)(val))[0]);
write_nic_dword(dev, RATR0, ratr_value);
write_nic_byte(dev, UFWP, 1);
}
//Resore TX Power Tracking Index
if(priv->btxpower_trackingInit && priv->btxpower_tracking){
dm_txpower_reset_recovery(dev);
}
//
//Restore BB Initial Gain
//
dm_bb_initialgain_restore(dev);
} // DM_RestoreDynamicMechanismState
static void dm_bb_initialgain_restore(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
u32 bit_mask = 0x7f; //Bit0~ Bit6
if(dm_digtable.dig_algorithm == DIG_ALGO_BY_RSSI)
return;
//Disable Initial Gain
//PHY_SetBBReg(Adapter, UFWP, bMaskLWord, 0x800);
rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8); // Only clear byte 1 and rewrite.
rtl8192_setBBreg(dev, rOFDM0_XAAGCCore1, bit_mask, (u32)priv->initgain_backup.xaagccore1);
rtl8192_setBBreg(dev, rOFDM0_XBAGCCore1, bit_mask, (u32)priv->initgain_backup.xbagccore1);
rtl8192_setBBreg(dev, rOFDM0_XCAGCCore1, bit_mask, (u32)priv->initgain_backup.xcagccore1);
rtl8192_setBBreg(dev, rOFDM0_XDAGCCore1, bit_mask, (u32)priv->initgain_backup.xdagccore1);
bit_mask = bMaskByte2;
rtl8192_setBBreg(dev, rCCK0_CCA, bit_mask, (u32)priv->initgain_backup.cca);
RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xc50 is %x\n",priv->initgain_backup.xaagccore1);
RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xc58 is %x\n",priv->initgain_backup.xbagccore1);
RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xc60 is %x\n",priv->initgain_backup.xcagccore1);
RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xc68 is %x\n",priv->initgain_backup.xdagccore1);
RT_TRACE(COMP_DIG, "dm_BBInitialGainRestore 0xa0a is %x\n",priv->initgain_backup.cca);
//Enable Initial Gain
//PHY_SetBBReg(Adapter, UFWP, bMaskLWord, 0x100);
rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x1); // Only clear byte 1 and rewrite.
} // dm_BBInitialGainRestore
extern void dm_backup_dynamic_mechanism_state(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
// Fsync to avoid reset
priv->bswitch_fsync = false;
priv->bfsync_processing = false;
//Backup BB InitialGain
dm_bb_initialgain_backup(dev);
} // DM_BackupDynamicMechanismState
static void dm_bb_initialgain_backup(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
u32 bit_mask = bMaskByte0; //Bit0~ Bit6
if(dm_digtable.dig_algorithm == DIG_ALGO_BY_RSSI)
return;
//PHY_SetBBReg(Adapter, UFWP, bMaskLWord, 0x800);
rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8); // Only clear byte 1 and rewrite.
priv->initgain_backup.xaagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XAAGCCore1, bit_mask);
priv->initgain_backup.xbagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XBAGCCore1, bit_mask);
priv->initgain_backup.xcagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XCAGCCore1, bit_mask);
priv->initgain_backup.xdagccore1 = (u8)rtl8192_QueryBBReg(dev, rOFDM0_XDAGCCore1, bit_mask);
bit_mask = bMaskByte2;
priv->initgain_backup.cca = (u8)rtl8192_QueryBBReg(dev, rCCK0_CCA, bit_mask);
RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xc50 is %x\n",priv->initgain_backup.xaagccore1);
RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xc58 is %x\n",priv->initgain_backup.xbagccore1);
RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xc60 is %x\n",priv->initgain_backup.xcagccore1);
RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xc68 is %x\n",priv->initgain_backup.xdagccore1);
RT_TRACE(COMP_DIG, "BBInitialGainBackup 0xa0a is %x\n",priv->initgain_backup.cca);
} // dm_BBInitialGainBakcup
#endif
/*-----------------------------------------------------------------------------
* Function: dm_change_dynamic_initgain_thresh()
*
* Overview:
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 05/29/2008 amy Create Version 0 porting from windows code.
*
*---------------------------------------------------------------------------*/
extern void dm_change_dynamic_initgain_thresh(struct net_device *dev,
u32 dm_type,
u32 dm_value)
{
if (dm_type == DIG_TYPE_THRESH_HIGH)
{
dm_digtable.rssi_high_thresh = dm_value;
}
else if (dm_type == DIG_TYPE_THRESH_LOW)
{
dm_digtable.rssi_low_thresh = dm_value;
}
else if (dm_type == DIG_TYPE_THRESH_HIGHPWR_HIGH)
{
dm_digtable.rssi_high_power_highthresh = dm_value;
}
else if (dm_type == DIG_TYPE_THRESH_HIGHPWR_HIGH)
{
dm_digtable.rssi_high_power_highthresh = dm_value;
}
else if (dm_type == DIG_TYPE_ENABLE)
{
dm_digtable.dig_state = DM_STA_DIG_MAX;
dm_digtable.dig_enable_flag = true;
}
else if (dm_type == DIG_TYPE_DISABLE)
{
dm_digtable.dig_state = DM_STA_DIG_MAX;
dm_digtable.dig_enable_flag = false;
}
else if (dm_type == DIG_TYPE_DBG_MODE)
{
if(dm_value >= DM_DBG_MAX)
dm_value = DM_DBG_OFF;
dm_digtable.dbg_mode = (u8)dm_value;
}
else if (dm_type == DIG_TYPE_RSSI)
{
if(dm_value > 100)
dm_value = 30;
dm_digtable.rssi_val = (long)dm_value;
}
else if (dm_type == DIG_TYPE_ALGORITHM)
{
if (dm_value >= DIG_ALGO_MAX)
dm_value = DIG_ALGO_BY_FALSE_ALARM;
if(dm_digtable.dig_algorithm != (u8)dm_value)
dm_digtable.dig_algorithm_switch = 1;
dm_digtable.dig_algorithm = (u8)dm_value;
}
else if (dm_type == DIG_TYPE_BACKOFF)
{
if(dm_value > 30)
dm_value = 30;
dm_digtable.backoff_val = (u8)dm_value;
}
else if(dm_type == DIG_TYPE_RX_GAIN_MIN)
{
if(dm_value == 0)
dm_value = 0x1;
dm_digtable.rx_gain_range_min = (u8)dm_value;
}
else if(dm_type == DIG_TYPE_RX_GAIN_MAX)
{
if(dm_value > 0x50)
dm_value = 0x50;
dm_digtable.rx_gain_range_max = (u8)dm_value;
}
} /* DM_ChangeDynamicInitGainThresh */
extern void
dm_change_fsync_setting(
struct net_device *dev,
s32 DM_Type,
s32 DM_Value)
{
struct r8192_priv *priv = ieee80211_priv(dev);
if (DM_Type == 0) // monitor 0xc38 register
{
if(DM_Value > 1)
DM_Value = 1;
priv->framesyncMonitor = (u8)DM_Value;
//DbgPrint("pHalData->framesyncMonitor = %d", pHalData->framesyncMonitor);
}
}
extern void
dm_change_rxpath_selection_setting(
struct net_device *dev,
s32 DM_Type,
s32 DM_Value)
{
struct r8192_priv *priv = ieee80211_priv(dev);
prate_adaptive pRA = (prate_adaptive)&(priv->rate_adaptive);
if(DM_Type == 0)
{
if(DM_Value > 1)
DM_Value = 1;
DM_RxPathSelTable.Enable = (u8)DM_Value;
}
else if(DM_Type == 1)
{
if(DM_Value > 1)
DM_Value = 1;
DM_RxPathSelTable.DbgMode = (u8)DM_Value;
}
else if(DM_Type == 2)
{
if(DM_Value > 40)
DM_Value = 40;
DM_RxPathSelTable.SS_TH_low = (u8)DM_Value;
}
else if(DM_Type == 3)
{
if(DM_Value > 25)
DM_Value = 25;
DM_RxPathSelTable.diff_TH = (u8)DM_Value;
}
else if(DM_Type == 4)
{
if(DM_Value >= CCK_Rx_Version_MAX)
DM_Value = CCK_Rx_Version_1;
DM_RxPathSelTable.cck_method= (u8)DM_Value;
}
else if(DM_Type == 10)
{
if(DM_Value > 100)
DM_Value = 50;
DM_RxPathSelTable.rf_rssi[0] = (u8)DM_Value;
}
else if(DM_Type == 11)
{
if(DM_Value > 100)
DM_Value = 50;
DM_RxPathSelTable.rf_rssi[1] = (u8)DM_Value;
}
else if(DM_Type == 12)
{
if(DM_Value > 100)
DM_Value = 50;
DM_RxPathSelTable.rf_rssi[2] = (u8)DM_Value;
}
else if(DM_Type == 13)
{
if(DM_Value > 100)
DM_Value = 50;
DM_RxPathSelTable.rf_rssi[3] = (u8)DM_Value;
}
else if(DM_Type == 20)
{
if(DM_Value > 1)
DM_Value = 1;
pRA->ping_rssi_enable = (u8)DM_Value;
}
else if(DM_Type == 21)
{
if(DM_Value > 30)
DM_Value = 30;
pRA->ping_rssi_thresh_for_ra = DM_Value;
}
}
/*-----------------------------------------------------------------------------
* Function: dm_dig_init()
*
* Overview: Set DIG scheme init value.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 05/15/2008 amy Create Version 0 porting from windows code.
*
*---------------------------------------------------------------------------*/
static void dm_dig_init(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
/* 2007/10/05 MH Disable DIG scheme now. Not tested. */
dm_digtable.dig_enable_flag = true;
dm_digtable.dig_algorithm = DIG_ALGO_BY_RSSI;
dm_digtable.dbg_mode = DM_DBG_OFF; //off=by real rssi value, on=by DM_DigTable.Rssi_val for new dig
dm_digtable.dig_algorithm_switch = 0;
/* 2007/10/04 MH Define init gain threshol. */
dm_digtable.dig_state = DM_STA_DIG_MAX;
dm_digtable.dig_highpwr_state = DM_STA_DIG_MAX;
dm_digtable.initialgain_lowerbound_state = false;
dm_digtable.rssi_low_thresh = DM_DIG_THRESH_LOW;
dm_digtable.rssi_high_thresh = DM_DIG_THRESH_HIGH;
dm_digtable.rssi_high_power_lowthresh = DM_DIG_HIGH_PWR_THRESH_LOW;
dm_digtable.rssi_high_power_highthresh = DM_DIG_HIGH_PWR_THRESH_HIGH;
dm_digtable.rssi_val = 50; //for new dig debug rssi value
dm_digtable.backoff_val = DM_DIG_BACKOFF;
dm_digtable.rx_gain_range_max = DM_DIG_MAX;
if(priv->CustomerID == RT_CID_819x_Netcore)
dm_digtable.rx_gain_range_min = DM_DIG_MIN_Netcore;
else
dm_digtable.rx_gain_range_min = DM_DIG_MIN;
} /* dm_dig_init */
/*-----------------------------------------------------------------------------
* Function: dm_ctrl_initgain_byrssi()
*
* Overview: Driver must monitor RSSI and notify firmware to change initial
* gain according to different threshold. BB team provide the
* suggested solution.
*
* Input: struct net_device *dev
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 05/27/2008 amy Create Version 0 porting from windows code.
*---------------------------------------------------------------------------*/
static void dm_ctrl_initgain_byrssi(struct net_device *dev)
{
if (dm_digtable.dig_enable_flag == false)
return;
if(dm_digtable.dig_algorithm == DIG_ALGO_BY_FALSE_ALARM)
dm_ctrl_initgain_byrssi_by_fwfalse_alarm(dev);
else if(dm_digtable.dig_algorithm == DIG_ALGO_BY_RSSI)
dm_ctrl_initgain_byrssi_by_driverrssi(dev);
// ;
else
return;
}
static void dm_ctrl_initgain_byrssi_by_driverrssi(
struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
u8 i;
static u8 fw_dig=0;
if (dm_digtable.dig_enable_flag == false)
return;
//DbgPrint("Dig by Sw Rssi \n");
if(dm_digtable.dig_algorithm_switch) // if swithed algorithm, we have to disable FW Dig.
fw_dig = 0;
if(fw_dig <= 3) // execute several times to make sure the FW Dig is disabled
{// FW DIG Off
for(i=0; i<3; i++)
rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8); // Only clear byte 1 and rewrite.
fw_dig++;
dm_digtable.dig_state = DM_STA_DIG_OFF; //fw dig off.
}
if(priv->ieee80211->state == IEEE80211_LINKED)
dm_digtable.cur_connect_state = DIG_CONNECT;
else
dm_digtable.cur_connect_state = DIG_DISCONNECT;
//DbgPrint("DM_DigTable.PreConnectState = %d, DM_DigTable.CurConnectState = %d \n",
//DM_DigTable.PreConnectState, DM_DigTable.CurConnectState);
if(dm_digtable.dbg_mode == DM_DBG_OFF)
dm_digtable.rssi_val = priv->undecorated_smoothed_pwdb;
//DbgPrint("DM_DigTable.Rssi_val = %d \n", DM_DigTable.Rssi_val);
dm_initial_gain(dev);
dm_pd_th(dev);
dm_cs_ratio(dev);
if(dm_digtable.dig_algorithm_switch)
dm_digtable.dig_algorithm_switch = 0;
dm_digtable.pre_connect_state = dm_digtable.cur_connect_state;
} /* dm_CtrlInitGainByRssi */
static void dm_ctrl_initgain_byrssi_by_fwfalse_alarm(
struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
static u32 reset_cnt = 0;
u8 i;
if (dm_digtable.dig_enable_flag == false)
return;
if(dm_digtable.dig_algorithm_switch)
{
dm_digtable.dig_state = DM_STA_DIG_MAX;
// Fw DIG On.
for(i=0; i<3; i++)
rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x1); // Only clear byte 1 and rewrite.
dm_digtable.dig_algorithm_switch = 0;
}
if (priv->ieee80211->state != IEEE80211_LINKED)
return;
// For smooth, we can not change DIG state.
if ((priv->undecorated_smoothed_pwdb > dm_digtable.rssi_low_thresh) &&
(priv->undecorated_smoothed_pwdb < dm_digtable.rssi_high_thresh))
{
return;
}
//DbgPrint("Dig by Fw False Alarm\n");
//if (DM_DigTable.Dig_State == DM_STA_DIG_OFF)
/*DbgPrint("DIG Check\n\r RSSI=%d LOW=%d HIGH=%d STATE=%d",
pHalData->UndecoratedSmoothedPWDB, DM_DigTable.RssiLowThresh,
DM_DigTable.RssiHighThresh, DM_DigTable.Dig_State);*/
/* 1. When RSSI decrease, We have to judge if it is smaller than a treshold
and then execute below step. */
if ((priv->undecorated_smoothed_pwdb <= dm_digtable.rssi_low_thresh))
{
/* 2008/02/05 MH When we execute silent reset, the DIG PHY parameters
will be reset to init value. We must prevent the condition. */
if (dm_digtable.dig_state == DM_STA_DIG_OFF &&
(priv->reset_count == reset_cnt))
{
return;
}
else
{
reset_cnt = priv->reset_count;
}
// If DIG is off, DIG high power state must reset.
dm_digtable.dig_highpwr_state = DM_STA_DIG_MAX;
dm_digtable.dig_state = DM_STA_DIG_OFF;
// 1.1 DIG Off.
rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x8); // Only clear byte 1 and rewrite.
// 1.2 Set initial gain.
write_nic_byte(dev, rOFDM0_XAAGCCore1, 0x17);
write_nic_byte(dev, rOFDM0_XBAGCCore1, 0x17);
write_nic_byte(dev, rOFDM0_XCAGCCore1, 0x17);
write_nic_byte(dev, rOFDM0_XDAGCCore1, 0x17);
// 1.3 Lower PD_TH for OFDM.
if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
{
/* 2008/01/11 MH 40MHZ 90/92 register are not the same. */
// 2008/02/05 MH SD3-Jerry 92U/92E PD_TH are the same.
#ifdef RTL8190P
write_nic_byte(dev, rOFDM0_RxDetector1, 0x40);
#else
write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x00);
#endif
/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
write_nic_byte(pAdapter, rOFDM0_RxDetector1, 0x40);
*/
//else if (pAdapter->HardwareType == HARDWARE_TYPE_RTL8192E)
//else
//PlatformEFIOWrite1Byte(pAdapter, rOFDM0_RxDetector1, 0x40);
}
else
write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
// 1.4 Lower CS ratio for CCK.
write_nic_byte(dev, 0xa0a, 0x08);
// 1.5 Higher EDCCA.
//PlatformEFIOWrite4Byte(pAdapter, rOFDM0_ECCAThreshold, 0x325);
return;
}
/* 2. When RSSI increase, We have to judge if it is larger than a treshold
and then execute below step. */
if ((priv->undecorated_smoothed_pwdb >= dm_digtable.rssi_high_thresh) )
{
u8 reset_flag = 0;
if (dm_digtable.dig_state == DM_STA_DIG_ON &&
(priv->reset_count == reset_cnt))
{
dm_ctrl_initgain_byrssi_highpwr(dev);
return;
}
else
{
if (priv->reset_count != reset_cnt)
reset_flag = 1;
reset_cnt = priv->reset_count;
}
dm_digtable.dig_state = DM_STA_DIG_ON;
//DbgPrint("DIG ON\n\r");
// 2.1 Set initial gain.
// 2008/02/26 MH SD3-Jerry suggest to prevent dirty environment.
if (reset_flag == 1)
{
write_nic_byte(dev, rOFDM0_XAAGCCore1, 0x2c);
write_nic_byte(dev, rOFDM0_XBAGCCore1, 0x2c);
write_nic_byte(dev, rOFDM0_XCAGCCore1, 0x2c);
write_nic_byte(dev, rOFDM0_XDAGCCore1, 0x2c);
}
else
{
write_nic_byte(dev, rOFDM0_XAAGCCore1, 0x20);
write_nic_byte(dev, rOFDM0_XBAGCCore1, 0x20);
write_nic_byte(dev, rOFDM0_XCAGCCore1, 0x20);
write_nic_byte(dev, rOFDM0_XDAGCCore1, 0x20);
}
// 2.2 Higher PD_TH for OFDM.
if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
{
/* 2008/01/11 MH 40MHZ 90/92 register are not the same. */
// 2008/02/05 MH SD3-Jerry 92U/92E PD_TH are the same.
#ifdef RTL8190P
write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
#else
write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x20);
#endif
/*
else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
*/
//else if (pAdapter->HardwareType == HARDWARE_TYPE_RTL8192E)
//else
//PlatformEFIOWrite1Byte(pAdapter, rOFDM0_RxDetector1, 0x42);
}
else
write_nic_byte(dev, rOFDM0_RxDetector1, 0x44);
// 2.3 Higher CS ratio for CCK.
write_nic_byte(dev, 0xa0a, 0xcd);
// 2.4 Lower EDCCA.
/* 2008/01/11 MH 90/92 series are the same. */
//PlatformEFIOWrite4Byte(pAdapter, rOFDM0_ECCAThreshold, 0x346);
// 2.5 DIG On.
rtl8192_setBBreg(dev, UFWP, bMaskByte1, 0x1); // Only clear byte 1 and rewrite.
}
dm_ctrl_initgain_byrssi_highpwr(dev);
} /* dm_CtrlInitGainByRssi */
/*-----------------------------------------------------------------------------
* Function: dm_ctrl_initgain_byrssi_highpwr()
*
* Overview:
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 05/28/2008 amy Create Version 0 porting from windows code.
*
*---------------------------------------------------------------------------*/
static void dm_ctrl_initgain_byrssi_highpwr(
struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
static u32 reset_cnt_highpwr = 0;
// For smooth, we can not change high power DIG state in the range.
if ((priv->undecorated_smoothed_pwdb > dm_digtable.rssi_high_power_lowthresh) &&
(priv->undecorated_smoothed_pwdb < dm_digtable.rssi_high_power_highthresh))
{
return;
}
/* 3. When RSSI >75% or <70%, it is a high power issue. We have to judge if
it is larger than a treshold and then execute below step. */
// 2008/02/05 MH SD3-Jerry Modify PD_TH for high power issue.
if (priv->undecorated_smoothed_pwdb >= dm_digtable.rssi_high_power_highthresh)
{
if (dm_digtable.dig_highpwr_state == DM_STA_DIG_ON &&
(priv->reset_count == reset_cnt_highpwr))
return;
else
dm_digtable.dig_highpwr_state = DM_STA_DIG_ON;
// 3.1 Higher PD_TH for OFDM for high power state.
if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
{
#ifdef RTL8190P
write_nic_byte(dev, rOFDM0_RxDetector1, 0x41);
#else
write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x10);
#endif
/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
write_nic_byte(dev, rOFDM0_RxDetector1, 0x41);
*/
}
else
write_nic_byte(dev, rOFDM0_RxDetector1, 0x43);
}
else
{
if (dm_digtable.dig_highpwr_state == DM_STA_DIG_OFF&&
(priv->reset_count == reset_cnt_highpwr))
return;
else
dm_digtable.dig_highpwr_state = DM_STA_DIG_OFF;
if (priv->undecorated_smoothed_pwdb < dm_digtable.rssi_high_power_lowthresh &&
priv->undecorated_smoothed_pwdb >= dm_digtable.rssi_high_thresh)
{
// 3.2 Recover PD_TH for OFDM for normal power region.
if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
{
#ifdef RTL8190P
write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
#else
write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x20);
#endif
/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
*/
}
else
write_nic_byte(dev, rOFDM0_RxDetector1, 0x44);
}
}
reset_cnt_highpwr = priv->reset_count;
} /* dm_CtrlInitGainByRssiHighPwr */
static void dm_initial_gain(
struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
u8 initial_gain=0;
static u8 initialized=0, force_write=0;
static u32 reset_cnt=0;
if(dm_digtable.dig_algorithm_switch)
{
initialized = 0;
reset_cnt = 0;
}
if(dm_digtable.pre_connect_state == dm_digtable.cur_connect_state)
{
if(dm_digtable.cur_connect_state == DIG_CONNECT)
{
if((dm_digtable.rssi_val+10-dm_digtable.backoff_val) > dm_digtable.rx_gain_range_max)
dm_digtable.cur_ig_value = dm_digtable.rx_gain_range_max;
else if((dm_digtable.rssi_val+10-dm_digtable.backoff_val) < dm_digtable.rx_gain_range_min)
dm_digtable.cur_ig_value = dm_digtable.rx_gain_range_min;
else
dm_digtable.cur_ig_value = dm_digtable.rssi_val+10-dm_digtable.backoff_val;
}
else //current state is disconnected
{
if(dm_digtable.cur_ig_value == 0)
dm_digtable.cur_ig_value = priv->DefaultInitialGain[0];
else
dm_digtable.cur_ig_value = dm_digtable.pre_ig_value;
}
}
else // disconnected -> connected or connected -> disconnected
{
dm_digtable.cur_ig_value = priv->DefaultInitialGain[0];
dm_digtable.pre_ig_value = 0;
}
//DbgPrint("DM_DigTable.CurIGValue = 0x%x, DM_DigTable.PreIGValue = 0x%x\n", DM_DigTable.CurIGValue, DM_DigTable.PreIGValue);
// if silent reset happened, we should rewrite the values back
if(priv->reset_count != reset_cnt)
{
force_write = 1;
reset_cnt = priv->reset_count;
}
if(dm_digtable.pre_ig_value != read_nic_byte(dev, rOFDM0_XAAGCCore1))
force_write = 1;
{
if((dm_digtable.pre_ig_value != dm_digtable.cur_ig_value)
|| !initialized || force_write)
{
initial_gain = (u8)dm_digtable.cur_ig_value;
//DbgPrint("Write initial gain = 0x%x\n", initial_gain);
// Set initial gain.
write_nic_byte(dev, rOFDM0_XAAGCCore1, initial_gain);
write_nic_byte(dev, rOFDM0_XBAGCCore1, initial_gain);
write_nic_byte(dev, rOFDM0_XCAGCCore1, initial_gain);
write_nic_byte(dev, rOFDM0_XDAGCCore1, initial_gain);
dm_digtable.pre_ig_value = dm_digtable.cur_ig_value;
initialized = 1;
force_write = 0;
}
}
}
static void dm_pd_th(
struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
static u8 initialized=0, force_write=0;
static u32 reset_cnt = 0;
if(dm_digtable.dig_algorithm_switch)
{
initialized = 0;
reset_cnt = 0;
}
if(dm_digtable.pre_connect_state == dm_digtable.cur_connect_state)
{
if(dm_digtable.cur_connect_state == DIG_CONNECT)
{
if (dm_digtable.rssi_val >= dm_digtable.rssi_high_power_highthresh)
dm_digtable.curpd_thstate = DIG_PD_AT_HIGH_POWER;
else if ((dm_digtable.rssi_val <= dm_digtable.rssi_low_thresh))
dm_digtable.curpd_thstate = DIG_PD_AT_LOW_POWER;
else if ((dm_digtable.rssi_val >= dm_digtable.rssi_high_thresh) &&
(dm_digtable.rssi_val < dm_digtable.rssi_high_power_lowthresh))
dm_digtable.curpd_thstate = DIG_PD_AT_NORMAL_POWER;
else
dm_digtable.curpd_thstate = dm_digtable.prepd_thstate;
}
else
{
dm_digtable.curpd_thstate = DIG_PD_AT_LOW_POWER;
}
}
else // disconnected -> connected or connected -> disconnected
{
dm_digtable.curpd_thstate = DIG_PD_AT_LOW_POWER;
}
// if silent reset happened, we should rewrite the values back
if(priv->reset_count != reset_cnt)
{
force_write = 1;
reset_cnt = priv->reset_count;
}
{
if((dm_digtable.prepd_thstate != dm_digtable.curpd_thstate) ||
(initialized<=3) || force_write)
{
//DbgPrint("Write PD_TH state = %d\n", DM_DigTable.CurPD_THState);
if(dm_digtable.curpd_thstate == DIG_PD_AT_LOW_POWER)
{
// Lower PD_TH for OFDM.
if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
{
/* 2008/01/11 MH 40MHZ 90/92 register are not the same. */
// 2008/02/05 MH SD3-Jerry 92U/92E PD_TH are the same.
#ifdef RTL8190P
write_nic_byte(dev, rOFDM0_RxDetector1, 0x40);
#else
write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x00);
#endif
/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
write_nic_byte(dev, rOFDM0_RxDetector1, 0x40);
*/
}
else
write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
}
else if(dm_digtable.curpd_thstate == DIG_PD_AT_NORMAL_POWER)
{
// Higher PD_TH for OFDM.
if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
{
/* 2008/01/11 MH 40MHZ 90/92 register are not the same. */
// 2008/02/05 MH SD3-Jerry 92U/92E PD_TH are the same.
#ifdef RTL8190P
write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
#else
write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x20);
#endif
/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
write_nic_byte(dev, rOFDM0_RxDetector1, 0x42);
*/
}
else
write_nic_byte(dev, rOFDM0_RxDetector1, 0x44);
}
else if(dm_digtable.curpd_thstate == DIG_PD_AT_HIGH_POWER)
{
// Higher PD_TH for OFDM for high power state.
if (priv->CurrentChannelBW != HT_CHANNEL_WIDTH_20)
{
#ifdef RTL8190P
write_nic_byte(dev, rOFDM0_RxDetector1, 0x41);
#else
write_nic_byte(dev, (rOFDM0_XATxAFE+3), 0x10);
#endif
/*else if (priv->card_8192 == HARDWARE_TYPE_RTL8190P)
write_nic_byte(dev, rOFDM0_RxDetector1, 0x41);
*/
}
else
write_nic_byte(dev, rOFDM0_RxDetector1, 0x43);
}
dm_digtable.prepd_thstate = dm_digtable.curpd_thstate;
if(initialized <= 3)
initialized++;
force_write = 0;
}
}
}
static void dm_cs_ratio(
struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
static u8 initialized=0,force_write=0;
static u32 reset_cnt = 0;
if(dm_digtable.dig_algorithm_switch)
{
initialized = 0;
reset_cnt = 0;
}
if(dm_digtable.pre_connect_state == dm_digtable.cur_connect_state)
{
if(dm_digtable.cur_connect_state == DIG_CONNECT)
{
if ((dm_digtable.rssi_val <= dm_digtable.rssi_low_thresh))
dm_digtable.curcs_ratio_state = DIG_CS_RATIO_LOWER;
else if ((dm_digtable.rssi_val >= dm_digtable.rssi_high_thresh) )
dm_digtable.curcs_ratio_state = DIG_CS_RATIO_HIGHER;
else
dm_digtable.curcs_ratio_state = dm_digtable.precs_ratio_state;
}
else
{
dm_digtable.curcs_ratio_state = DIG_CS_RATIO_LOWER;
}
}
else // disconnected -> connected or connected -> disconnected
{
dm_digtable.curcs_ratio_state = DIG_CS_RATIO_LOWER;
}
// if silent reset happened, we should rewrite the values back
if(priv->reset_count != reset_cnt)
{
force_write = 1;
reset_cnt = priv->reset_count;
}
{
if((dm_digtable.precs_ratio_state != dm_digtable.curcs_ratio_state) ||
!initialized || force_write)
{
//DbgPrint("Write CS_ratio state = %d\n", DM_DigTable.CurCS_ratioState);
if(dm_digtable.curcs_ratio_state == DIG_CS_RATIO_LOWER)
{
// Lower CS ratio for CCK.
write_nic_byte(dev, 0xa0a, 0x08);
}
else if(dm_digtable.curcs_ratio_state == DIG_CS_RATIO_HIGHER)
{
// Higher CS ratio for CCK.
write_nic_byte(dev, 0xa0a, 0xcd);
}
dm_digtable.precs_ratio_state = dm_digtable.curcs_ratio_state;
initialized = 1;
force_write = 0;
}
}
}
extern void dm_init_edca_turbo(struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
priv->bcurrent_turbo_EDCA = false;
priv->ieee80211->bis_any_nonbepkts = false;
priv->bis_cur_rdlstate = false;
} // dm_init_edca_turbo
static void dm_check_edca_turbo(
struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
PRT_HIGH_THROUGHPUT pHTInfo = priv->ieee80211->pHTInfo;
//PSTA_QOS pStaQos = pMgntInfo->pStaQos;
// Keep past Tx/Rx packet count for RT-to-RT EDCA turbo.
static unsigned long lastTxOkCnt = 0;
static unsigned long lastRxOkCnt = 0;
unsigned long curTxOkCnt = 0;
unsigned long curRxOkCnt = 0;
//
// Do not be Turbo if it's under WiFi config and Qos Enabled, because the EDCA parameters
// should follow the settings from QAP. By Bruce, 2007-12-07.
//
if(priv->ieee80211->state != IEEE80211_LINKED)
goto dm_CheckEdcaTurbo_EXIT;
// We do not turn on EDCA turbo mode for some AP that has IOT issue
if(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_DISABLE_EDCA_TURBO)
goto dm_CheckEdcaTurbo_EXIT;
// printk("========>%s():bis_any_nonbepkts is %d\n",__FUNCTION__,priv->bis_any_nonbepkts);
// Check the status for current condition.
if(!priv->ieee80211->bis_any_nonbepkts)
{
curTxOkCnt = priv->stats.txbytesunicast - lastTxOkCnt;
curRxOkCnt = priv->stats.rxbytesunicast - lastRxOkCnt;
// For RT-AP, we needs to turn it on when Rx>Tx
if(curRxOkCnt > 4*curTxOkCnt)
{
//printk("%s():curRxOkCnt > 4*curTxOkCnt\n");
if(!priv->bis_cur_rdlstate || !priv->bcurrent_turbo_EDCA)
{
write_nic_dword(dev, EDCAPARA_BE, edca_setting_DL[pHTInfo->IOTPeer]);
priv->bis_cur_rdlstate = true;
}
}
else
{
//printk("%s():curRxOkCnt < 4*curTxOkCnt\n");
if(priv->bis_cur_rdlstate || !priv->bcurrent_turbo_EDCA)
{
write_nic_dword(dev, EDCAPARA_BE, edca_setting_UL[pHTInfo->IOTPeer]);
priv->bis_cur_rdlstate = false;
}
}
priv->bcurrent_turbo_EDCA = true;
}
else
{
//
// Turn Off EDCA turbo here.
// Restore original EDCA according to the declaration of AP.
//
if(priv->bcurrent_turbo_EDCA)
{
{
u8 u1bAIFS;
u32 u4bAcParam;
struct ieee80211_qos_parameters *qos_parameters = &priv->ieee80211->current_network.qos_data.parameters;
u8 mode = priv->ieee80211->mode;
// For Each time updating EDCA parameter, reset EDCA turbo mode status.
dm_init_edca_turbo(dev);
u1bAIFS = qos_parameters->aifs[0] * ((mode&(IEEE_G|IEEE_N_24G)) ?9:20) + aSifsTime;
u4bAcParam = ((((u32)(qos_parameters->tx_op_limit[0]))<< AC_PARAM_TXOP_LIMIT_OFFSET)|
(((u32)(qos_parameters->cw_max[0]))<< AC_PARAM_ECW_MAX_OFFSET)|
(((u32)(qos_parameters->cw_min[0]))<< AC_PARAM_ECW_MIN_OFFSET)|
((u32)u1bAIFS << AC_PARAM_AIFS_OFFSET));
//write_nic_dword(dev, WDCAPARA_ADD[i], u4bAcParam);
write_nic_dword(dev, EDCAPARA_BE, u4bAcParam);
// Check ACM bit.
// If it is set, immediately set ACM control bit to downgrading AC for passing WMM testplan. Annie, 2005-12-13.
{
// TODO: Modified this part and try to set acm control in only 1 IO processing!!
PACI_AIFSN pAciAifsn = (PACI_AIFSN)&(qos_parameters->aifs[0]);
u8 AcmCtrl = read_nic_byte( dev, AcmHwCtrl );
if( pAciAifsn->f.ACM )
{ // ACM bit is 1.
AcmCtrl |= AcmHw_BeqEn;
}
else
{ // ACM bit is 0.
AcmCtrl &= (~AcmHw_BeqEn);
}
RT_TRACE( COMP_QOS,"SetHwReg8190pci(): [HW_VAR_ACM_CTRL] Write 0x%X\n", AcmCtrl ) ;
write_nic_byte(dev, AcmHwCtrl, AcmCtrl );
}
}
priv->bcurrent_turbo_EDCA = false;
}
}
dm_CheckEdcaTurbo_EXIT:
// Set variables for next time.
priv->ieee80211->bis_any_nonbepkts = false;
lastTxOkCnt = priv->stats.txbytesunicast;
lastRxOkCnt = priv->stats.rxbytesunicast;
} // dm_CheckEdcaTurbo
extern void DM_CTSToSelfSetting(struct net_device * dev,u32 DM_Type, u32 DM_Value)
{
struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
if (DM_Type == 0) // CTS to self disable/enable
{
if(DM_Value > 1)
DM_Value = 1;
priv->ieee80211->bCTSToSelfEnable = (bool)DM_Value;
//DbgPrint("pMgntInfo->bCTSToSelfEnable = %d\n", pMgntInfo->bCTSToSelfEnable);
}
else if(DM_Type == 1) //CTS to self Th
{
if(DM_Value >= 50)
DM_Value = 50;
priv->ieee80211->CTSToSelfTH = (u8)DM_Value;
//DbgPrint("pMgntInfo->CTSToSelfTH = %d\n", pMgntInfo->CTSToSelfTH);
}
}
static void dm_init_ctstoself(struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
priv->ieee80211->bCTSToSelfEnable = TRUE;
priv->ieee80211->CTSToSelfTH = CTSToSelfTHVal;
}
static void dm_ctstoself(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv((struct net_device *)dev);
PRT_HIGH_THROUGHPUT pHTInfo = priv->ieee80211->pHTInfo;
static unsigned long lastTxOkCnt = 0;
static unsigned long lastRxOkCnt = 0;
unsigned long curTxOkCnt = 0;
unsigned long curRxOkCnt = 0;
if(priv->ieee80211->bCTSToSelfEnable != TRUE)
{
pHTInfo->IOTAction &= ~HT_IOT_ACT_FORCED_CTS2SELF;
return;
}
/*
1. Uplink
2. Linksys350/Linksys300N
3. <50 disable, >55 enable
*/
if(pHTInfo->IOTPeer == HT_IOT_PEER_BROADCOM)
{
curTxOkCnt = priv->stats.txbytesunicast - lastTxOkCnt;
curRxOkCnt = priv->stats.rxbytesunicast - lastRxOkCnt;
if(curRxOkCnt > 4*curTxOkCnt) //downlink, disable CTS to self
{
pHTInfo->IOTAction &= ~HT_IOT_ACT_FORCED_CTS2SELF;
//DbgPrint("dm_CTSToSelf() ==> CTS to self disabled -- downlink\n");
}
else //uplink
{
pHTInfo->IOTAction |= HT_IOT_ACT_FORCED_CTS2SELF;
}
lastTxOkCnt = priv->stats.txbytesunicast;
lastRxOkCnt = priv->stats.rxbytesunicast;
}
}
/*-----------------------------------------------------------------------------
* Function: dm_check_rfctrl_gpio()
*
* Overview: Copy 8187B template for 9xseries.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 05/28/2008 amy Create Version 0 porting from windows code.
*
*---------------------------------------------------------------------------*/
static void dm_check_rfctrl_gpio(struct net_device * dev)
{
//struct r8192_priv *priv = ieee80211_priv(dev);
// Walk around for DTM test, we will not enable HW - radio on/off because r/w
// page 1 register before Lextra bus is enabled cause system fails when resuming
// from S4. 20080218, Emily
// Stop to execute workitem to prevent S3/S4 bug.
#ifdef RTL8190P
return;
#endif
#ifdef RTL8192U
return;
#endif
#ifdef RTL8192E
queue_delayed_work(priv->priv_wq,&priv->gpio_change_rf_wq,0);
#endif
} /* dm_CheckRfCtrlGPIO */
/*-----------------------------------------------------------------------------
* Function: dm_check_pbc_gpio()
*
* Overview: Check if PBC button is pressed.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 05/28/2008 amy Create Version 0 porting from windows code.
*
*---------------------------------------------------------------------------*/
static void dm_check_pbc_gpio(struct net_device *dev)
{
#ifdef RTL8192U
struct r8192_priv *priv = ieee80211_priv(dev);
u8 tmp1byte;
tmp1byte = read_nic_byte(dev,GPI);
if(tmp1byte == 0xff)
return;
if (tmp1byte&BIT6 || tmp1byte&BIT0)
{
// Here we only set bPbcPressed to TRUE
// After trigger PBC, the variable will be set to FALSE
RT_TRACE(COMP_IO, "CheckPbcGPIO - PBC is pressed\n");
priv->bpbc_pressed = true;
}
#endif
}
#ifdef RTL8192E
/*-----------------------------------------------------------------------------
* Function: dm_GPIOChangeRF
* Overview: PCI will not support workitem call back HW radio on-off control.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 02/21/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
extern void dm_gpio_change_rf_callback(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work,struct delayed_work,work);
struct r8192_priv *priv = container_of(dwork,struct r8192_priv,gpio_change_rf_wq);
struct net_device *dev = priv->ieee80211->dev;
u8 tmp1byte;
RT_RF_POWER_STATE eRfPowerStateToSet;
bool bActuallySet = false;
do{
bActuallySet=false;
if(!priv->up)
{
RT_TRACE((COMP_INIT | COMP_POWER | COMP_RF),"dm_gpio_change_rf_callback(): Callback function breaks out!!\n");
}
else
{
// 0x108 GPIO input register is read only
//set 0x108 B1= 1: RF-ON; 0: RF-OFF.
tmp1byte = read_nic_byte(dev,GPI);
eRfPowerStateToSet = (tmp1byte&BIT1) ? eRfOn : eRfOff;
if( (priv->bHwRadioOff == true) && (eRfPowerStateToSet == eRfOn))
{
RT_TRACE(COMP_RF, "gpiochangeRF - HW Radio ON\n");
priv->bHwRadioOff = false;
bActuallySet = true;
}
else if ( (priv->bHwRadioOff == false) && (eRfPowerStateToSet == eRfOff))
{
RT_TRACE(COMP_RF, "gpiochangeRF - HW Radio OFF\n");
priv->bHwRadioOff = true;
bActuallySet = true;
}
if(bActuallySet)
{
#ifdef TO_DO
MgntActSet_RF_State(dev, eRfPowerStateToSet, RF_CHANGE_BY_HW);
//DrvIFIndicateCurrentPhyStatus(pAdapter);
#endif
}
else
{
msleep(2000);
}
}
}while(TRUE)
} /* dm_GPIOChangeRF */
#endif
/*-----------------------------------------------------------------------------
* Function: DM_RFPathCheckWorkItemCallBack()
*
* Overview: Check if Current RF RX path is enabled
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 01/30/2008 MHC Create Version 0.
*
*---------------------------------------------------------------------------*/
extern void dm_rf_pathcheck_workitemcallback(struct work_struct *work)
{
struct delayed_work *dwork = container_of(work,struct delayed_work,work);
struct r8192_priv *priv = container_of(dwork,struct r8192_priv,rfpath_check_wq);
struct net_device *dev =priv->ieee80211->dev;
//bool bactually_set = false;
u8 rfpath = 0, i;
/* 2008/01/30 MH After discussing with SD3 Jerry, 0xc04/0xd04 register will
always be the same. We only read 0xc04 now. */
rfpath = read_nic_byte(dev, 0xc04);
// Check Bit 0-3, it means if RF A-D is enabled.
for (i = 0; i < RF90_PATH_MAX; i++)
{
if (rfpath & (0x01<<i))
priv->brfpath_rxenable[i] = 1;
else
priv->brfpath_rxenable[i] = 0;
}
if(!DM_RxPathSelTable.Enable)
return;
dm_rxpath_sel_byrssi(dev);
} /* DM_RFPathCheckWorkItemCallBack */
static void dm_init_rxpath_selection(struct net_device * dev)
{
u8 i;
struct r8192_priv *priv = ieee80211_priv(dev);
DM_RxPathSelTable.Enable = 1; //default enabled
DM_RxPathSelTable.SS_TH_low = RxPathSelection_SS_TH_low;
DM_RxPathSelTable.diff_TH = RxPathSelection_diff_TH;
if(priv->CustomerID == RT_CID_819x_Netcore)
DM_RxPathSelTable.cck_method = CCK_Rx_Version_2;
else
DM_RxPathSelTable.cck_method = CCK_Rx_Version_1;
DM_RxPathSelTable.DbgMode = DM_DBG_OFF;
DM_RxPathSelTable.disabledRF = 0;
for(i=0; i<4; i++)
{
DM_RxPathSelTable.rf_rssi[i] = 50;
DM_RxPathSelTable.cck_pwdb_sta[i] = -64;
DM_RxPathSelTable.rf_enable_rssi_th[i] = 100;
}
}
static void dm_rxpath_sel_byrssi(struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
u8 i, max_rssi_index=0, min_rssi_index=0, sec_rssi_index=0, rf_num=0;
u8 tmp_max_rssi=0, tmp_min_rssi=0, tmp_sec_rssi=0;
u8 cck_default_Rx=0x2; //RF-C
u8 cck_optional_Rx=0x3;//RF-D
long tmp_cck_max_pwdb=0, tmp_cck_min_pwdb=0, tmp_cck_sec_pwdb=0;
u8 cck_rx_ver2_max_index=0, cck_rx_ver2_min_index=0, cck_rx_ver2_sec_index=0;
u8 cur_rf_rssi;
long cur_cck_pwdb;
static u8 disabled_rf_cnt=0, cck_Rx_Path_initialized=0;
u8 update_cck_rx_path;
if(priv->rf_type != RF_2T4R)
return;
if(!cck_Rx_Path_initialized)
{
DM_RxPathSelTable.cck_Rx_path = (read_nic_byte(dev, 0xa07)&0xf);
cck_Rx_Path_initialized = 1;
}
DM_RxPathSelTable.disabledRF = 0xf;
DM_RxPathSelTable.disabledRF &=~ (read_nic_byte(dev, 0xc04));
if(priv->ieee80211->mode == WIRELESS_MODE_B)
{
DM_RxPathSelTable.cck_method = CCK_Rx_Version_2; //pure B mode, fixed cck version2
//DbgPrint("Pure B mode, use cck rx version2 \n");
}
//decide max/sec/min rssi index
for (i=0; i<RF90_PATH_MAX; i++)
{
if(!DM_RxPathSelTable.DbgMode)
DM_RxPathSelTable.rf_rssi[i] = priv->stats.rx_rssi_percentage[i];
if(priv->brfpath_rxenable[i])
{
rf_num++;
cur_rf_rssi = DM_RxPathSelTable.rf_rssi[i];
if(rf_num == 1) // find first enabled rf path and the rssi values
{ //initialize, set all rssi index to the same one
max_rssi_index = min_rssi_index = sec_rssi_index = i;
tmp_max_rssi = tmp_min_rssi = tmp_sec_rssi = cur_rf_rssi;
}
else if(rf_num == 2)
{ // we pick up the max index first, and let sec and min to be the same one
if(cur_rf_rssi >= tmp_max_rssi)
{
tmp_max_rssi = cur_rf_rssi;
max_rssi_index = i;
}
else
{
tmp_sec_rssi = tmp_min_rssi = cur_rf_rssi;
sec_rssi_index = min_rssi_index = i;
}
}
else
{
if(cur_rf_rssi > tmp_max_rssi)
{
tmp_sec_rssi = tmp_max_rssi;
sec_rssi_index = max_rssi_index;
tmp_max_rssi = cur_rf_rssi;
max_rssi_index = i;
}
else if(cur_rf_rssi == tmp_max_rssi)
{ // let sec and min point to the different index
tmp_sec_rssi = cur_rf_rssi;
sec_rssi_index = i;
}
else if((cur_rf_rssi < tmp_max_rssi) &&(cur_rf_rssi > tmp_sec_rssi))
{
tmp_sec_rssi = cur_rf_rssi;
sec_rssi_index = i;
}
else if(cur_rf_rssi == tmp_sec_rssi)
{
if(tmp_sec_rssi == tmp_min_rssi)
{ // let sec and min point to the different index
tmp_sec_rssi = cur_rf_rssi;
sec_rssi_index = i;
}
else
{
// This case we don't need to set any index
}
}
else if((cur_rf_rssi < tmp_sec_rssi) && (cur_rf_rssi > tmp_min_rssi))
{
// This case we don't need to set any index
}
else if(cur_rf_rssi == tmp_min_rssi)
{
if(tmp_sec_rssi == tmp_min_rssi)
{ // let sec and min point to the different index
tmp_min_rssi = cur_rf_rssi;
min_rssi_index = i;
}
else
{
// This case we don't need to set any index
}
}
else if(cur_rf_rssi < tmp_min_rssi)
{
tmp_min_rssi = cur_rf_rssi;
min_rssi_index = i;
}
}
}
}
rf_num = 0;
// decide max/sec/min cck pwdb index
if(DM_RxPathSelTable.cck_method == CCK_Rx_Version_2)
{
for (i=0; i<RF90_PATH_MAX; i++)
{
if(priv->brfpath_rxenable[i])
{
rf_num++;
cur_cck_pwdb = DM_RxPathSelTable.cck_pwdb_sta[i];
if(rf_num == 1) // find first enabled rf path and the rssi values
{ //initialize, set all rssi index to the same one
cck_rx_ver2_max_index = cck_rx_ver2_min_index = cck_rx_ver2_sec_index = i;
tmp_cck_max_pwdb = tmp_cck_min_pwdb = tmp_cck_sec_pwdb = cur_cck_pwdb;
}
else if(rf_num == 2)
{ // we pick up the max index first, and let sec and min to be the same one
if(cur_cck_pwdb >= tmp_cck_max_pwdb)
{
tmp_cck_max_pwdb = cur_cck_pwdb;
cck_rx_ver2_max_index = i;
}
else
{
tmp_cck_sec_pwdb = tmp_cck_min_pwdb = cur_cck_pwdb;
cck_rx_ver2_sec_index = cck_rx_ver2_min_index = i;
}
}
else
{
if(cur_cck_pwdb > tmp_cck_max_pwdb)
{
tmp_cck_sec_pwdb = tmp_cck_max_pwdb;
cck_rx_ver2_sec_index = cck_rx_ver2_max_index;
tmp_cck_max_pwdb = cur_cck_pwdb;
cck_rx_ver2_max_index = i;
}
else if(cur_cck_pwdb == tmp_cck_max_pwdb)
{ // let sec and min point to the different index
tmp_cck_sec_pwdb = cur_cck_pwdb;
cck_rx_ver2_sec_index = i;
}
else if((cur_cck_pwdb < tmp_cck_max_pwdb) &&(cur_cck_pwdb > tmp_cck_sec_pwdb))
{
tmp_cck_sec_pwdb = cur_cck_pwdb;
cck_rx_ver2_sec_index = i;
}
else if(cur_cck_pwdb == tmp_cck_sec_pwdb)
{
if(tmp_cck_sec_pwdb == tmp_cck_min_pwdb)
{ // let sec and min point to the different index
tmp_cck_sec_pwdb = cur_cck_pwdb;
cck_rx_ver2_sec_index = i;
}
else
{
// This case we don't need to set any index
}
}
else if((cur_cck_pwdb < tmp_cck_sec_pwdb) && (cur_cck_pwdb > tmp_cck_min_pwdb))
{
// This case we don't need to set any index
}
else if(cur_cck_pwdb == tmp_cck_min_pwdb)
{
if(tmp_cck_sec_pwdb == tmp_cck_min_pwdb)
{ // let sec and min point to the different index
tmp_cck_min_pwdb = cur_cck_pwdb;
cck_rx_ver2_min_index = i;
}
else
{
// This case we don't need to set any index
}
}
else if(cur_cck_pwdb < tmp_cck_min_pwdb)
{
tmp_cck_min_pwdb = cur_cck_pwdb;
cck_rx_ver2_min_index = i;
}
}
}
}
}
// Set CCK Rx path
// reg0xA07[3:2]=cck default rx path, reg0xa07[1:0]=cck optional rx path.
update_cck_rx_path = 0;
if(DM_RxPathSelTable.cck_method == CCK_Rx_Version_2)
{
cck_default_Rx = cck_rx_ver2_max_index;
cck_optional_Rx = cck_rx_ver2_sec_index;
if(tmp_cck_max_pwdb != -64)
update_cck_rx_path = 1;
}
if(tmp_min_rssi < DM_RxPathSelTable.SS_TH_low && disabled_rf_cnt < 2)
{
if((tmp_max_rssi - tmp_min_rssi) >= DM_RxPathSelTable.diff_TH)
{
//record the enabled rssi threshold
DM_RxPathSelTable.rf_enable_rssi_th[min_rssi_index] = tmp_max_rssi+5;
//disable the BB Rx path, OFDM
rtl8192_setBBreg(dev, rOFDM0_TRxPathEnable, 0x1<<min_rssi_index, 0x0); // 0xc04[3:0]
rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0x1<<min_rssi_index, 0x0); // 0xd04[3:0]
disabled_rf_cnt++;
}
if(DM_RxPathSelTable.cck_method == CCK_Rx_Version_1)
{
cck_default_Rx = max_rssi_index;
cck_optional_Rx = sec_rssi_index;
if(tmp_max_rssi)
update_cck_rx_path = 1;
}
}
if(update_cck_rx_path)
{
DM_RxPathSelTable.cck_Rx_path = (cck_default_Rx<<2)|(cck_optional_Rx);
rtl8192_setBBreg(dev, rCCK0_AFESetting, 0x0f000000, DM_RxPathSelTable.cck_Rx_path);
}
if(DM_RxPathSelTable.disabledRF)
{
for(i=0; i<4; i++)
{
if((DM_RxPathSelTable.disabledRF>>i) & 0x1) //disabled rf
{
if(tmp_max_rssi >= DM_RxPathSelTable.rf_enable_rssi_th[i])
{
//enable the BB Rx path
//DbgPrint("RF-%d is enabled. \n", 0x1<<i);
rtl8192_setBBreg(dev, rOFDM0_TRxPathEnable, 0x1<<i, 0x1); // 0xc04[3:0]
rtl8192_setBBreg(dev, rOFDM1_TRxPathEnable, 0x1<<i, 0x1); // 0xd04[3:0]
DM_RxPathSelTable.rf_enable_rssi_th[i] = 100;
disabled_rf_cnt--;
}
}
}
}
}
/*-----------------------------------------------------------------------------
* Function: dm_check_rx_path_selection()
*
* Overview: Call a workitem to check current RXRF path and Rx Path selection by RSSI.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 05/28/2008 amy Create Version 0 porting from windows code.
*
*---------------------------------------------------------------------------*/
static void dm_check_rx_path_selection(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
queue_delayed_work(priv->priv_wq,&priv->rfpath_check_wq,0);
} /* dm_CheckRxRFPath */
static void dm_init_fsync (struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
priv->ieee80211->fsync_time_interval = 500;
priv->ieee80211->fsync_rate_bitmap = 0x0f000800;
priv->ieee80211->fsync_rssi_threshold = 30;
#ifdef RTL8190P
priv->ieee80211->bfsync_enable = true;
#else
priv->ieee80211->bfsync_enable = false;
#endif
priv->ieee80211->fsync_multiple_timeinterval = 3;
priv->ieee80211->fsync_firstdiff_ratethreshold= 100;
priv->ieee80211->fsync_seconddiff_ratethreshold= 200;
priv->ieee80211->fsync_state = Default_Fsync;
priv->framesyncMonitor = 1; // current default 0xc38 monitor on
init_timer(&priv->fsync_timer);
priv->fsync_timer.data = (unsigned long)dev;
priv->fsync_timer.function = dm_fsync_timer_callback;
}
static void dm_deInit_fsync(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
del_timer_sync(&priv->fsync_timer);
}
extern void dm_fsync_timer_callback(unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct r8192_priv *priv = ieee80211_priv((struct net_device *)data);
u32 rate_index, rate_count = 0, rate_count_diff=0;
bool bSwitchFromCountDiff = false;
bool bDoubleTimeInterval = false;
if( priv->ieee80211->state == IEEE80211_LINKED &&
priv->ieee80211->bfsync_enable &&
(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_CDD_FSYNC))
{
// Count rate 54, MCS [7], [12, 13, 14, 15]
u32 rate_bitmap;
for(rate_index = 0; rate_index <= 27; rate_index++)
{
rate_bitmap = 1 << rate_index;
if(priv->ieee80211->fsync_rate_bitmap & rate_bitmap)
rate_count+= priv->stats.received_rate_histogram[1][rate_index];
}
if(rate_count < priv->rate_record)
rate_count_diff = 0xffffffff - rate_count + priv->rate_record;
else
rate_count_diff = rate_count - priv->rate_record;
if(rate_count_diff < priv->rateCountDiffRecord)
{
u32 DiffNum = priv->rateCountDiffRecord - rate_count_diff;
// Contiune count
if(DiffNum >= priv->ieee80211->fsync_seconddiff_ratethreshold)
priv->ContiuneDiffCount++;
else
priv->ContiuneDiffCount = 0;
// Contiune count over
if(priv->ContiuneDiffCount >=2)
{
bSwitchFromCountDiff = true;
priv->ContiuneDiffCount = 0;
}
}
else
{
// Stop contiune count
priv->ContiuneDiffCount = 0;
}
//If Count diff <= FsyncRateCountThreshold
if(rate_count_diff <= priv->ieee80211->fsync_firstdiff_ratethreshold)
{
bSwitchFromCountDiff = true;
priv->ContiuneDiffCount = 0;
}
priv->rate_record = rate_count;
priv->rateCountDiffRecord = rate_count_diff;
RT_TRACE(COMP_HALDM, "rateRecord %d rateCount %d, rateCountdiff %d bSwitchFsync %d\n", priv->rate_record, rate_count, rate_count_diff , priv->bswitch_fsync);
// if we never receive those mcs rate and rssi > 30 % then switch fsyn
if(priv->undecorated_smoothed_pwdb > priv->ieee80211->fsync_rssi_threshold && bSwitchFromCountDiff)
{
bDoubleTimeInterval = true;
priv->bswitch_fsync = !priv->bswitch_fsync;
if(priv->bswitch_fsync)
{
#ifdef RTL8190P
write_nic_byte(dev, 0xC36, 0x00);
#else
write_nic_byte(dev,0xC36, 0x1c);
#endif
write_nic_byte(dev, 0xC3e, 0x90);
}
else
{
#ifdef RTL8190P
write_nic_byte(dev, 0xC36, 0x40);
#else
write_nic_byte(dev, 0xC36, 0x5c);
#endif
write_nic_byte(dev, 0xC3e, 0x96);
}
}
else if(priv->undecorated_smoothed_pwdb <= priv->ieee80211->fsync_rssi_threshold)
{
if(priv->bswitch_fsync)
{
priv->bswitch_fsync = false;
#ifdef RTL8190P
write_nic_byte(dev, 0xC36, 0x40);
#else
write_nic_byte(dev, 0xC36, 0x5c);
#endif
write_nic_byte(dev, 0xC3e, 0x96);
}
}
if(bDoubleTimeInterval){
if(timer_pending(&priv->fsync_timer))
del_timer_sync(&priv->fsync_timer);
priv->fsync_timer.expires = jiffies + MSECS(priv->ieee80211->fsync_time_interval*priv->ieee80211->fsync_multiple_timeinterval);
add_timer(&priv->fsync_timer);
}
else{
if(timer_pending(&priv->fsync_timer))
del_timer_sync(&priv->fsync_timer);
priv->fsync_timer.expires = jiffies + MSECS(priv->ieee80211->fsync_time_interval);
add_timer(&priv->fsync_timer);
}
}
else
{
// Let Register return to default value;
if(priv->bswitch_fsync)
{
priv->bswitch_fsync = false;
#ifdef RTL8190P
write_nic_byte(dev, 0xC36, 0x40);
#else
write_nic_byte(dev, 0xC36, 0x5c);
#endif
write_nic_byte(dev, 0xC3e, 0x96);
}
priv->ContiuneDiffCount = 0;
#ifdef RTL8190P
write_nic_dword(dev, rOFDM0_RxDetector2, 0x164052cd);
#else
write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c52cd);
#endif
}
RT_TRACE(COMP_HALDM, "ContiuneDiffCount %d\n", priv->ContiuneDiffCount);
RT_TRACE(COMP_HALDM, "rateRecord %d rateCount %d, rateCountdiff %d bSwitchFsync %d\n", priv->rate_record, rate_count, rate_count_diff , priv->bswitch_fsync);
}
static void dm_StartHWFsync(struct net_device *dev)
{
RT_TRACE(COMP_HALDM, "%s\n", __FUNCTION__);
write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c12cf);
write_nic_byte(dev, 0xc3b, 0x41);
}
static void dm_EndSWFsync(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
RT_TRACE(COMP_HALDM, "%s\n", __FUNCTION__);
del_timer_sync(&(priv->fsync_timer));
// Let Register return to default value;
if(priv->bswitch_fsync)
{
priv->bswitch_fsync = false;
#ifdef RTL8190P
write_nic_byte(dev, 0xC36, 0x40);
#else
write_nic_byte(dev, 0xC36, 0x5c);
#endif
write_nic_byte(dev, 0xC3e, 0x96);
}
priv->ContiuneDiffCount = 0;
#ifndef RTL8190P
write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c52cd);
#endif
}
static void dm_StartSWFsync(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
u32 rateIndex;
u32 rateBitmap;
RT_TRACE(COMP_HALDM,"%s\n", __FUNCTION__);
// Initial rate record to zero, start to record.
priv->rate_record = 0;
// Initial contiune diff count to zero, start to record.
priv->ContiuneDiffCount = 0;
priv->rateCountDiffRecord = 0;
priv->bswitch_fsync = false;
if(priv->ieee80211->mode == WIRELESS_MODE_N_24G)
{
priv->ieee80211->fsync_firstdiff_ratethreshold= 600;
priv->ieee80211->fsync_seconddiff_ratethreshold = 0xffff;
}
else
{
priv->ieee80211->fsync_firstdiff_ratethreshold= 200;
priv->ieee80211->fsync_seconddiff_ratethreshold = 200;
}
for(rateIndex = 0; rateIndex <= 27; rateIndex++)
{
rateBitmap = 1 << rateIndex;
if(priv->ieee80211->fsync_rate_bitmap & rateBitmap)
priv->rate_record += priv->stats.received_rate_histogram[1][rateIndex];
}
if(timer_pending(&priv->fsync_timer))
del_timer_sync(&priv->fsync_timer);
priv->fsync_timer.expires = jiffies + MSECS(priv->ieee80211->fsync_time_interval);
add_timer(&priv->fsync_timer);
#ifndef RTL8190P
write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c12cd);
#endif
}
static void dm_EndHWFsync(struct net_device *dev)
{
RT_TRACE(COMP_HALDM,"%s\n", __FUNCTION__);
write_nic_dword(dev, rOFDM0_RxDetector2, 0x465c52cd);
write_nic_byte(dev, 0xc3b, 0x49);
}
void dm_check_fsync(struct net_device *dev)
{
#define RegC38_Default 0
#define RegC38_NonFsync_Other_AP 1
#define RegC38_Fsync_AP_BCM 2
struct r8192_priv *priv = ieee80211_priv(dev);
//u32 framesyncC34;
static u8 reg_c38_State=RegC38_Default;
static u32 reset_cnt=0;
RT_TRACE(COMP_HALDM, "RSSI %d TimeInterval %d MultipleTimeInterval %d\n", priv->ieee80211->fsync_rssi_threshold, priv->ieee80211->fsync_time_interval, priv->ieee80211->fsync_multiple_timeinterval);
RT_TRACE(COMP_HALDM, "RateBitmap 0x%x FirstDiffRateThreshold %d SecondDiffRateThreshold %d\n", priv->ieee80211->fsync_rate_bitmap, priv->ieee80211->fsync_firstdiff_ratethreshold, priv->ieee80211->fsync_seconddiff_ratethreshold);
if( priv->ieee80211->state == IEEE80211_LINKED &&
(priv->ieee80211->pHTInfo->IOTAction & HT_IOT_ACT_CDD_FSYNC))
{
if(priv->ieee80211->bfsync_enable == 0)
{
switch(priv->ieee80211->fsync_state)
{
case Default_Fsync:
dm_StartHWFsync(dev);
priv->ieee80211->fsync_state = HW_Fsync;
break;
case SW_Fsync:
dm_EndSWFsync(dev);
dm_StartHWFsync(dev);
priv->ieee80211->fsync_state = HW_Fsync;
break;
case HW_Fsync:
default:
break;
}
}
else
{
switch(priv->ieee80211->fsync_state)
{
case Default_Fsync:
dm_StartSWFsync(dev);
priv->ieee80211->fsync_state = SW_Fsync;
break;
case HW_Fsync:
dm_EndHWFsync(dev);
dm_StartSWFsync(dev);
priv->ieee80211->fsync_state = SW_Fsync;
break;
case SW_Fsync:
default:
break;
}
}
if(priv->framesyncMonitor)
{
if(reg_c38_State != RegC38_Fsync_AP_BCM)
{ //For broadcom AP we write different default value
#ifdef RTL8190P
write_nic_byte(dev, rOFDM0_RxDetector3, 0x15);
#else
write_nic_byte(dev, rOFDM0_RxDetector3, 0x95);
#endif
reg_c38_State = RegC38_Fsync_AP_BCM;
}
}
}
else
{
switch(priv->ieee80211->fsync_state)
{
case HW_Fsync:
dm_EndHWFsync(dev);
priv->ieee80211->fsync_state = Default_Fsync;
break;
case SW_Fsync:
dm_EndSWFsync(dev);
priv->ieee80211->fsync_state = Default_Fsync;
break;
case Default_Fsync:
default:
break;
}
if(priv->framesyncMonitor)
{
if(priv->ieee80211->state == IEEE80211_LINKED)
{
if(priv->undecorated_smoothed_pwdb <= RegC38_TH)
{
if(reg_c38_State != RegC38_NonFsync_Other_AP)
{
#ifdef RTL8190P
write_nic_byte(dev, rOFDM0_RxDetector3, 0x10);
#else
write_nic_byte(dev, rOFDM0_RxDetector3, 0x90);
#endif
reg_c38_State = RegC38_NonFsync_Other_AP;
}
}
else if(priv->undecorated_smoothed_pwdb >= (RegC38_TH+5))
{
if(reg_c38_State)
{
write_nic_byte(dev, rOFDM0_RxDetector3, priv->framesync);
reg_c38_State = RegC38_Default;
//DbgPrint("Fsync is idle, rssi>=40, write 0xc38 = 0x%x \n", pHalData->framesync);
}
}
}
else
{
if(reg_c38_State)
{
write_nic_byte(dev, rOFDM0_RxDetector3, priv->framesync);
reg_c38_State = RegC38_Default;
//DbgPrint("Fsync is idle, not connected, write 0xc38 = 0x%x \n", pHalData->framesync);
}
}
}
}
if(priv->framesyncMonitor)
{
if(priv->reset_count != reset_cnt)
{ //After silent reset, the reg_c38_State will be returned to default value
write_nic_byte(dev, rOFDM0_RxDetector3, priv->framesync);
reg_c38_State = RegC38_Default;
reset_cnt = priv->reset_count;
//DbgPrint("reg_c38_State = 0 for silent reset. \n");
}
}
else
{
if(reg_c38_State)
{
write_nic_byte(dev, rOFDM0_RxDetector3, priv->framesync);
reg_c38_State = RegC38_Default;
//DbgPrint("framesync no monitor, write 0xc38 = 0x%x \n", pHalData->framesync);
}
}
}
/*-----------------------------------------------------------------------------
* Function: dm_shadow_init()
*
* Overview: Store all NIC MAC/BB register content.
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 05/29/2008 amy Create Version 0 porting from windows code.
*
*---------------------------------------------------------------------------*/
extern void dm_shadow_init(struct net_device *dev)
{
u8 page;
u16 offset;
for (page = 0; page < 5; page++)
for (offset = 0; offset < 256; offset++)
{
dm_shadow[page][offset] = read_nic_byte(dev, offset+page*256);
//DbgPrint("P-%d/O-%02x=%02x\r\n", page, offset, DM_Shadow[page][offset]);
}
for (page = 8; page < 11; page++)
for (offset = 0; offset < 256; offset++)
dm_shadow[page][offset] = read_nic_byte(dev, offset+page*256);
for (page = 12; page < 15; page++)
for (offset = 0; offset < 256; offset++)
dm_shadow[page][offset] = read_nic_byte(dev, offset+page*256);
} /* dm_shadow_init */
/*---------------------------Define function prototype------------------------*/
/*-----------------------------------------------------------------------------
* Function: DM_DynamicTxPower()
*
* Overview: Detect Signal strength to control TX Registry
Tx Power Control For Near/Far Range
*
* Input: NONE
*
* Output: NONE
*
* Return: NONE
*
* Revised History:
* When Who Remark
* 03/06/2008 Jacken Create Version 0.
*
*---------------------------------------------------------------------------*/
static void dm_init_dynamic_txpower(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
//Initial TX Power Control for near/far range , add by amy 2008/05/15, porting from windows code.
priv->ieee80211->bdynamic_txpower_enable = true; //Default to enable Tx Power Control
priv->bLastDTPFlag_High = false;
priv->bLastDTPFlag_Low = false;
priv->bDynamicTxHighPower = false;
priv->bDynamicTxLowPower = false;
}
static void dm_dynamic_txpower(struct net_device *dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
unsigned int txhipower_threshhold=0;
unsigned int txlowpower_threshold=0;
if(priv->ieee80211->bdynamic_txpower_enable != true)
{
priv->bDynamicTxHighPower = false;
priv->bDynamicTxLowPower = false;
return;
}
//printk("priv->ieee80211->current_network.unknown_cap_exist is %d ,priv->ieee80211->current_network.broadcom_cap_exist is %d\n",priv->ieee80211->current_network.unknown_cap_exist,priv->ieee80211->current_network.broadcom_cap_exist);
if((priv->ieee80211->current_network.atheros_cap_exist ) && (priv->ieee80211->mode == IEEE_G)){
txhipower_threshhold = TX_POWER_ATHEROAP_THRESH_HIGH;
txlowpower_threshold = TX_POWER_ATHEROAP_THRESH_LOW;
}
else
{
txhipower_threshhold = TX_POWER_NEAR_FIELD_THRESH_HIGH;
txlowpower_threshold = TX_POWER_NEAR_FIELD_THRESH_LOW;
}
// printk("=======>%s(): txhipower_threshhold is %d,txlowpower_threshold is %d\n",__FUNCTION__,txhipower_threshhold,txlowpower_threshold);
RT_TRACE(COMP_TXAGC,"priv->undecorated_smoothed_pwdb = %ld \n" , priv->undecorated_smoothed_pwdb);
if(priv->ieee80211->state == IEEE80211_LINKED)
{
if(priv->undecorated_smoothed_pwdb >= txhipower_threshhold)
{
priv->bDynamicTxHighPower = true;
priv->bDynamicTxLowPower = false;
}
else
{
// high power state check
if(priv->undecorated_smoothed_pwdb < txlowpower_threshold && priv->bDynamicTxHighPower == true)
{
priv->bDynamicTxHighPower = false;
}
// low power state check
if(priv->undecorated_smoothed_pwdb < 35)
{
priv->bDynamicTxLowPower = true;
}
else if(priv->undecorated_smoothed_pwdb >= 40)
{
priv->bDynamicTxLowPower = false;
}
}
}
else
{
//pHalData->bTXPowerCtrlforNearFarRange = !pHalData->bTXPowerCtrlforNearFarRange;
priv->bDynamicTxHighPower = false;
priv->bDynamicTxLowPower = false;
}
if( (priv->bDynamicTxHighPower != priv->bLastDTPFlag_High ) ||
(priv->bDynamicTxLowPower != priv->bLastDTPFlag_Low ) )
{
RT_TRACE(COMP_TXAGC,"SetTxPowerLevel8190() channel = %d \n" , priv->ieee80211->current_network.channel);
#if defined(RTL8190P) || defined(RTL8192E)
SetTxPowerLevel8190(Adapter,pHalData->CurrentChannel);
#endif
#ifdef RTL8192U
rtl8192_phy_setTxPower(dev,priv->ieee80211->current_network.channel);
//pHalData->bStartTxCtrlByTPCNFR = FALSE; //Clear th flag of Set TX Power from Sitesurvey
#endif
}
priv->bLastDTPFlag_High = priv->bDynamicTxHighPower;
priv->bLastDTPFlag_Low = priv->bDynamicTxLowPower;
} /* dm_dynamic_txpower */
//added by vivi, for read tx rate and retrycount
static void dm_check_txrateandretrycount(struct net_device * dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
struct ieee80211_device* ieee = priv->ieee80211;
//for 11n tx rate
// priv->stats.CurrentShowTxate = read_nic_byte(dev, Current_Tx_Rate_Reg);
ieee->softmac_stats.CurrentShowTxate = read_nic_byte(dev, Current_Tx_Rate_Reg);
//printk("=============>tx_rate_reg:%x\n", ieee->softmac_stats.CurrentShowTxate);
//for initial tx rate
// priv->stats.last_packet_rate = read_nic_byte(dev, Initial_Tx_Rate_Reg);
ieee->softmac_stats.last_packet_rate = read_nic_byte(dev ,Initial_Tx_Rate_Reg);
//for tx tx retry count
// priv->stats.txretrycount = read_nic_dword(dev, Tx_Retry_Count_Reg);
ieee->softmac_stats.txretrycount = read_nic_dword(dev, Tx_Retry_Count_Reg);
}
static void dm_send_rssi_tofw(struct net_device *dev)
{
DCMD_TXCMD_T tx_cmd;
struct r8192_priv *priv = ieee80211_priv(dev);
// If we test chariot, we should stop the TX command ?
// Because 92E will always silent reset when we send tx command. We use register
// 0x1e0(byte) to botify driver.
write_nic_byte(dev, DRIVER_RSSI, (u8)priv->undecorated_smoothed_pwdb);
return;
tx_cmd.Op = TXCMD_SET_RX_RSSI;
tx_cmd.Length = 4;
tx_cmd.Value = priv->undecorated_smoothed_pwdb;
cmpk_message_handle_tx(dev, (u8*)&tx_cmd,
DESC_PACKET_TYPE_INIT, sizeof(DCMD_TXCMD_T));
}
/*---------------------------Define function prototype------------------------*/
| gpl-2.0 |
NTSK13/forlinux | arch/arm/kernel/machine_kexec.c | 134 | 2224 | /*
* machine_kexec.c - handle transition of Linux booting another kernel
*/
#include <linux/mm.h>
#include <linux/kexec.h>
#include <linux/delay.h>
#include <linux/reboot.h>
#include <linux/io.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/mmu_context.h>
#include <asm/cacheflush.h>
#include <asm/mach-types.h>
extern const unsigned char relocate_new_kernel[];
extern const unsigned int relocate_new_kernel_size;
extern void setup_mm_for_reboot(char mode);
extern unsigned long kexec_start_address;
extern unsigned long kexec_indirection_page;
extern unsigned long kexec_mach_type;
extern unsigned long kexec_boot_atags;
/*
* Provide a dummy crash_notes definition while crash dump arrives to arm.
* This prevents breakage of crash_notes attribute in kernel/ksysfs.c.
*/
int machine_kexec_prepare(struct kimage *image)
{
return 0;
}
void machine_kexec_cleanup(struct kimage *image)
{
}
void machine_crash_shutdown(struct pt_regs *regs)
{
local_irq_disable();
crash_save_cpu(regs, smp_processor_id());
printk(KERN_INFO "Loading crashdump kernel...\n");
}
void machine_kexec(struct kimage *image)
{
unsigned long page_list;
unsigned long reboot_code_buffer_phys;
void *reboot_code_buffer;
page_list = image->head & PAGE_MASK;
/* we need both effective and real address here */
reboot_code_buffer_phys =
page_to_pfn(image->control_code_page) << PAGE_SHIFT;
reboot_code_buffer = page_address(image->control_code_page);
/* Prepare parameters for reboot_code_buffer*/
kexec_start_address = image->start;
kexec_indirection_page = page_list;
kexec_mach_type = machine_arch_type;
kexec_boot_atags = image->start - KEXEC_ARM_ZIMAGE_OFFSET + KEXEC_ARM_ATAGS_OFFSET;
/* copy our kernel relocation code to the control code page */
memcpy(reboot_code_buffer,
relocate_new_kernel, relocate_new_kernel_size);
flush_icache_range((unsigned long) reboot_code_buffer,
(unsigned long) reboot_code_buffer + KEXEC_CONTROL_PAGE_SIZE);
printk(KERN_INFO "Bye!\n");
local_irq_disable();
local_fiq_disable();
setup_mm_for_reboot(0); /* mode is not used, so just pass 0*/
flush_cache_all();
cpu_proc_fin();
flush_cache_all();
cpu_reset(reboot_code_buffer_phys);
}
| gpl-2.0 |
vigor/vigor_aosp_kernel | drivers/net/wireless/bcm4329_248/siutils.c | 134 | 36639 | /*
* Misc utility routines for accessing chip-specific features
* of the SiliconBackplane-based Broadcom chips.
*
* Copyright (C) 1999-2010, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: siutils.c,v 1.662.4.4.4.16.4.28 2010/06/23 21:37:54 Exp $
*/
#include <typedefs.h>
#include <bcmdefs.h>
#include <osl.h>
#include <bcmutils.h>
#include <siutils.h>
#include <bcmdevs.h>
#include <hndsoc.h>
#include <sbchipc.h>
#include <pcicfg.h>
#include <sbpcmcia.h>
#include <sbsocram.h>
#include <bcmsdh.h>
#include <sdio.h>
#include <sbsdio.h>
#include <sbhnddma.h>
#include <sbsdpcmdev.h>
#include <bcmsdpcm.h>
#include <hndpmu.h>
#include "siutils_priv.h"
/* local prototypes */
static si_info_t *si_doattach(si_info_t *sii, uint devid, osl_t *osh, void *regs,
uint bustype, void *sdh, char **vars, uint *varsz);
static bool si_buscore_prep(si_info_t *sii, uint bustype, uint devid, void *sdh);
static bool si_buscore_setup(si_info_t *sii, chipcregs_t *cc, uint bustype, uint32 savewin,
uint *origidx, void *regs);
/* global variable to indicate reservation/release of gpio's */
static uint32 si_gpioreservation = 0;
static void *common_info_alloced = NULL;
/* global flag to prevent shared resources from being initialized multiple times in si_attach() */
/*
* Allocate a si handle.
* devid - pci device id (used to determine chip#)
* osh - opaque OS handle
* regs - virtual address of initial core registers
* bustype - pci/pcmcia/sb/sdio/etc
* vars - pointer to a pointer area for "environment" variables
* varsz - pointer to int to return the size of the vars
*/
si_t *
si_attach(uint devid, osl_t *osh, void *regs,
uint bustype, void *sdh, char **vars, uint *varsz)
{
si_info_t *sii;
/* alloc si_info_t */
if ((sii = MALLOC(osh, sizeof (si_info_t))) == NULL) {
SI_ERROR(("si_attach: malloc failed! malloced %d bytes\n", MALLOCED(osh)));
return (NULL);
}
if (si_doattach(sii, devid, osh, regs, bustype, sdh, vars, varsz) == NULL) {
if (NULL != sii->common_info)
MFREE(osh, sii->common_info, sizeof(si_common_info_t));
MFREE(osh, sii, sizeof(si_info_t));
return (NULL);
}
sii->vars = vars ? *vars : NULL;
sii->varsz = varsz ? *varsz : 0;
return (si_t *)sii;
}
/* global kernel resource */
static si_info_t ksii;
static uint32 wd_msticks; /* watchdog timer ticks normalized to ms */
/* generic kernel variant of si_attach() */
si_t *
si_kattach(osl_t *osh)
{
static bool ksii_attached = FALSE;
if (!ksii_attached) {
void *regs = REG_MAP(SI_ENUM_BASE, SI_CORE_SIZE);
if (si_doattach(&ksii, BCM4710_DEVICE_ID, osh, regs,
SI_BUS, NULL,
osh != SI_OSH ? &ksii.vars : NULL,
osh != SI_OSH ? &ksii.varsz : NULL) == NULL) {
if (NULL != ksii.common_info)
MFREE(osh, ksii.common_info, sizeof(si_common_info_t));
SI_ERROR(("si_kattach: si_doattach failed\n"));
REG_UNMAP(regs);
return NULL;
}
REG_UNMAP(regs);
/* save ticks normalized to ms for si_watchdog_ms() */
if (PMUCTL_ENAB(&ksii.pub)) {
/* based on 32KHz ILP clock */
wd_msticks = 32;
} else {
wd_msticks = ALP_CLOCK / 1000;
}
ksii_attached = TRUE;
SI_MSG(("si_kattach done. ccrev = %d, wd_msticks = %d\n",
ksii.pub.ccrev, wd_msticks));
}
return &ksii.pub;
}
static bool
si_buscore_prep(si_info_t *sii, uint bustype, uint devid, void *sdh)
{
/* need to set memseg flag for CF card first before any sb registers access */
if (BUSTYPE(bustype) == PCMCIA_BUS)
sii->memseg = TRUE;
if (BUSTYPE(bustype) == SDIO_BUS) {
int err;
uint8 clkset;
/* Try forcing SDIO core to do ALPAvail request only */
clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_ALP_AVAIL_REQ;
bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, clkset, &err);
if (!err) {
uint8 clkval;
/* If register supported, wait for ALPAvail and then force ALP */
clkval = bcmsdh_cfg_read(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR, NULL);
if ((clkval & ~SBSDIO_AVBITS) == clkset) {
SPINWAIT(((clkval = bcmsdh_cfg_read(sdh, SDIO_FUNC_1,
SBSDIO_FUNC1_CHIPCLKCSR, NULL)), !SBSDIO_ALPAV(clkval)),
PMU_MAX_TRANSITION_DLY);
if (!SBSDIO_ALPAV(clkval)) {
SI_ERROR(("timeout on ALPAV wait, clkval 0x%02x\n",
clkval));
return FALSE;
}
clkset = SBSDIO_FORCE_HW_CLKREQ_OFF | SBSDIO_FORCE_ALP;
bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_CHIPCLKCSR,
clkset, &err);
OSL_DELAY(65);
}
}
/* Also, disable the extra SDIO pull-ups */
bcmsdh_cfg_write(sdh, SDIO_FUNC_1, SBSDIO_FUNC1_SDIOPULLUP, 0, NULL);
}
return TRUE;
}
static bool
si_buscore_setup(si_info_t *sii, chipcregs_t *cc, uint bustype, uint32 savewin,
uint *origidx, void *regs)
{
bool pci, pcie;
uint i;
uint pciidx, pcieidx, pcirev, pcierev;
cc = si_setcoreidx(&sii->pub, SI_CC_IDX);
ASSERT((uintptr)cc);
#ifdef HTC_KlocWork
if(cc == NULL){
SI_ERROR(("[HTCKW] si_buscore_setup: cc is NULL\n"));
return FALSE;
}
#endif
/* get chipcommon rev */
sii->pub.ccrev = (int)si_corerev(&sii->pub);
/* get chipcommon chipstatus */
if (sii->pub.ccrev >= 11)
sii->pub.chipst = R_REG(sii->osh, &cc->chipstatus);
/* get chipcommon capabilites */
sii->pub.cccaps = R_REG(sii->osh, &cc->capabilities);
/* get pmu rev and caps */
if (sii->pub.cccaps & CC_CAP_PMU) {
sii->pub.pmucaps = R_REG(sii->osh, &cc->pmucapabilities);
sii->pub.pmurev = sii->pub.pmucaps & PCAP_REV_MASK;
}
SI_MSG(("Chipc: rev %d, caps 0x%x, chipst 0x%x pmurev %d, pmucaps 0x%x\n",
sii->pub.ccrev, sii->pub.cccaps, sii->pub.chipst, sii->pub.pmurev,
sii->pub.pmucaps));
/* figure out bus/orignal core idx */
sii->pub.buscoretype = NODEV_CORE_ID;
sii->pub.buscorerev = NOREV;
sii->pub.buscoreidx = BADIDX;
pci = pcie = FALSE;
pcirev = pcierev = NOREV;
pciidx = pcieidx = BADIDX;
for (i = 0; i < sii->numcores; i++) {
uint cid, crev;
si_setcoreidx(&sii->pub, i);
cid = si_coreid(&sii->pub);
crev = si_corerev(&sii->pub);
/* Display cores found */
SI_MSG(("CORE[%d]: id 0x%x rev %d base 0x%x regs 0x%p\n",
i, cid, crev, sii->common_info->coresba[i], sii->common_info->regs[i]));
if (BUSTYPE(bustype) == PCI_BUS) {
if (cid == PCI_CORE_ID) {
pciidx = i;
pcirev = crev;
pci = TRUE;
} else if (cid == PCIE_CORE_ID) {
pcieidx = i;
pcierev = crev;
pcie = TRUE;
}
} else if ((BUSTYPE(bustype) == PCMCIA_BUS) &&
(cid == PCMCIA_CORE_ID)) {
sii->pub.buscorerev = crev;
sii->pub.buscoretype = cid;
sii->pub.buscoreidx = i;
}
else if (((BUSTYPE(bustype) == SDIO_BUS) ||
(BUSTYPE(bustype) == SPI_BUS)) &&
((cid == PCMCIA_CORE_ID) ||
(cid == SDIOD_CORE_ID))) {
sii->pub.buscorerev = crev;
sii->pub.buscoretype = cid;
sii->pub.buscoreidx = i;
}
/* find the core idx before entering this func. */
if ((savewin && (savewin == sii->common_info->coresba[i])) ||
(regs == sii->common_info->regs[i]))
*origidx = i;
}
SI_MSG(("Buscore id/type/rev %d/0x%x/%d\n", sii->pub.buscoreidx, sii->pub.buscoretype,
sii->pub.buscorerev));
if (BUSTYPE(sii->pub.bustype) == SI_BUS && (CHIPID(sii->pub.chip) == BCM4712_CHIP_ID) &&
(sii->pub.chippkg != BCM4712LARGE_PKG_ID) && (sii->pub.chiprev <= 3))
OR_REG(sii->osh, &cc->slow_clk_ctl, SCC_SS_XTAL);
/* Make sure any on-chip ARM is off (in case strapping is wrong), or downloaded code was
* already running.
*/
if ((BUSTYPE(bustype) == SDIO_BUS) || (BUSTYPE(bustype) == SPI_BUS)) {
if (si_setcore(&sii->pub, ARM7S_CORE_ID, 0) ||
si_setcore(&sii->pub, ARMCM3_CORE_ID, 0))
si_core_disable(&sii->pub, 0);
}
/* return to the original core */
si_setcoreidx(&sii->pub, *origidx);
return TRUE;
}
static si_info_t *
si_doattach(si_info_t *sii, uint devid, osl_t *osh, void *regs,
uint bustype, void *sdh, char **vars, uint *varsz)
{
struct si_pub *sih = &sii->pub;
uint32 w, savewin;
chipcregs_t *cc;
char *pvars = NULL;
uint origidx;
ASSERT(GOODREGS(regs));
bzero((uchar*)sii, sizeof(si_info_t));
{
if (NULL == (common_info_alloced = (void *)MALLOC(osh, sizeof(si_common_info_t)))) {
SI_ERROR(("si_doattach: malloc failed! malloced %dbytes\n", MALLOCED(osh)));
return (NULL);
}
bzero((uchar*)(common_info_alloced), sizeof(si_common_info_t));
}
sii->common_info = (si_common_info_t *)common_info_alloced;
sii->common_info->attach_count++;
savewin = 0;
sih->buscoreidx = BADIDX;
sii->curmap = regs;
sii->sdh = sdh;
sii->osh = osh;
/* find Chipcommon address */
if (bustype == PCI_BUS) {
savewin = OSL_PCI_READ_CONFIG(sii->osh, PCI_BAR0_WIN, sizeof(uint32));
if (!GOODCOREADDR(savewin, SI_ENUM_BASE))
savewin = SI_ENUM_BASE;
OSL_PCI_WRITE_CONFIG(sii->osh, PCI_BAR0_WIN, 4, SI_ENUM_BASE);
cc = (chipcregs_t *)regs;
} else
if ((bustype == SDIO_BUS) || (bustype == SPI_BUS)) {
cc = (chipcregs_t *)sii->curmap;
} else {
cc = (chipcregs_t *)REG_MAP(SI_ENUM_BASE, SI_CORE_SIZE);
}
sih->bustype = bustype;
if (bustype != BUSTYPE(bustype)) {
SI_ERROR(("si_doattach: bus type %d does not match configured bus type %d\n",
bustype, BUSTYPE(bustype)));
return NULL;
}
/* bus/core/clk setup for register access */
if (!si_buscore_prep(sii, bustype, devid, sdh)) {
SI_ERROR(("si_doattach: si_core_clk_prep failed %d\n", bustype));
return NULL;
}
/* ChipID recognition.
* We assume we can read chipid at offset 0 from the regs arg.
* If we add other chiptypes (or if we need to support old sdio hosts w/o chipcommon),
* some way of recognizing them needs to be added here.
*/
#ifdef HTC_KlocWork
if(cc == NULL) {
SI_ERROR(("[HTCKW] si_doattach: cc is NULL-1\n"));
return NULL;
}
#endif
w = R_REG(osh, &cc->chipid);
sih->socitype = (w & CID_TYPE_MASK) >> CID_TYPE_SHIFT;
/* Might as wll fill in chip id rev & pkg */
sih->chip = w & CID_ID_MASK;
sih->chiprev = (w & CID_REV_MASK) >> CID_REV_SHIFT;
sih->chippkg = (w & CID_PKG_MASK) >> CID_PKG_SHIFT;
if ((CHIPID(sih->chip) == BCM4329_CHIP_ID) && (sih->chippkg != BCM4329_289PIN_PKG_ID))
sih->chippkg = BCM4329_182PIN_PKG_ID;
sih->issim = IS_SIM(sih->chippkg);
/* scan for cores */
if (CHIPTYPE(sii->pub.socitype) == SOCI_SB) {
SI_MSG(("Found chip type SB (0x%08x)\n", w));
sb_scan(&sii->pub, regs, devid);
} else if (CHIPTYPE(sii->pub.socitype) == SOCI_AI) {
SI_MSG(("Found chip type AI (0x%08x)\n", w));
/* pass chipc address instead of original core base */
ai_scan(&sii->pub, (void *)cc, devid);
} else {
SI_ERROR(("Found chip of unkown type (0x%08x)\n", w));
return NULL;
}
/* no cores found, bail out */
if (sii->numcores == 0) {
SI_ERROR(("si_doattach: could not find any cores\n"));
return NULL;
}
/* bus/core/clk setup */
origidx = SI_CC_IDX;
if (!si_buscore_setup(sii, cc, bustype, savewin, &origidx, regs)) {
SI_ERROR(("si_doattach: si_buscore_setup failed\n"));
return NULL;
}
pvars = NULL;
if (sii->pub.ccrev >= 20) {
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
#ifdef HTC_KlocWork
if(cc == NULL) {
SI_ERROR(("[HTCKW] si_doattach: cc is NULL-2\n"));
return NULL;
}
#endif
W_REG(osh, &cc->gpiopullup, 0);
W_REG(osh, &cc->gpiopulldown, 0);
si_setcoreidx(sih, origidx);
}
/* Skip PMU initialization from the Dongle Host.
* Firmware will take care of it when it comes up.
*/
return (sii);
}
/* may be called with core in reset */
void
si_detach(si_t *sih)
{
si_info_t *sii;
uint idx;
sii = SI_INFO(sih);
if (sii == NULL)
return;
if (BUSTYPE(sih->bustype) == SI_BUS)
for (idx = 0; idx < SI_MAXCORES; idx++)
if (sii->common_info->regs[idx]) {
REG_UNMAP(sii->common_info->regs[idx]);
sii->common_info->regs[idx] = NULL;
}
if (1 == sii->common_info->attach_count--) {
MFREE(sii->osh, sii->common_info, sizeof(si_common_info_t));
common_info_alloced = NULL;
}
#if !defined(BCMBUSTYPE) || (BCMBUSTYPE == SI_BUS)
if (sii != &ksii)
#endif /* !BCMBUSTYPE || (BCMBUSTYPE == SI_BUS) */
MFREE(sii->osh, sii, sizeof(si_info_t));
}
void *
si_osh(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
return sii->osh;
}
void
si_setosh(si_t *sih, osl_t *osh)
{
si_info_t *sii;
sii = SI_INFO(sih);
if (sii->osh != NULL) {
SI_ERROR(("osh is already set....\n"));
ASSERT(!sii->osh);
}
sii->osh = osh;
}
/* register driver interrupt disabling and restoring callback functions */
void
si_register_intr_callback(si_t *sih, void *intrsoff_fn, void *intrsrestore_fn,
void *intrsenabled_fn, void *intr_arg)
{
si_info_t *sii;
sii = SI_INFO(sih);
sii->intr_arg = intr_arg;
sii->intrsoff_fn = (si_intrsoff_t)intrsoff_fn;
sii->intrsrestore_fn = (si_intrsrestore_t)intrsrestore_fn;
sii->intrsenabled_fn = (si_intrsenabled_t)intrsenabled_fn;
/* save current core id. when this function called, the current core
* must be the core which provides driver functions(il, et, wl, etc.)
*/
sii->dev_coreid = sii->common_info->coreid[sii->curidx];
}
void
si_deregister_intr_callback(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
sii->intrsoff_fn = NULL;
}
uint
si_intflag(si_t *sih)
{
si_info_t *sii = SI_INFO(sih);
if (CHIPTYPE(sih->socitype) == SOCI_SB) {
sbconfig_t *ccsbr = (sbconfig_t *)((uintptr)((ulong)
(sii->common_info->coresba[SI_CC_IDX]) + SBCONFIGOFF));
return R_REG(sii->osh, &ccsbr->sbflagst);
} else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return R_REG(sii->osh, ((uint32 *)(uintptr)
(sii->common_info->oob_router + OOB_STATUSA)));
else {
ASSERT(0);
return 0;
}
}
uint
si_flag(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_flag(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_flag(sih);
else {
ASSERT(0);
return 0;
}
}
void
si_setint(si_t *sih, int siflag)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_setint(sih, siflag);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_setint(sih, siflag);
else
ASSERT(0);
}
uint
si_coreid(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
return sii->common_info->coreid[sii->curidx];
}
uint
si_coreidx(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
return sii->curidx;
}
/* return the core-type instantiation # of the current core */
uint
si_coreunit(si_t *sih)
{
si_info_t *sii;
uint idx;
uint coreid;
uint coreunit;
uint i;
sii = SI_INFO(sih);
coreunit = 0;
idx = sii->curidx;
ASSERT(GOODREGS(sii->curmap));
coreid = si_coreid(sih);
/* count the cores of our type */
for (i = 0; i < idx; i++)
if (sii->common_info->coreid[i] == coreid)
coreunit++;
return (coreunit);
}
uint
si_corevendor(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_corevendor(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_corevendor(sih);
else {
ASSERT(0);
return 0;
}
}
bool
si_backplane64(si_t *sih)
{
return ((sih->cccaps & CC_CAP_BKPLN64) != 0);
}
uint
si_corerev(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_corerev(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_corerev(sih);
else {
ASSERT(0);
return 0;
}
}
/* return index of coreid or BADIDX if not found */
uint
si_findcoreidx(si_t *sih, uint coreid, uint coreunit)
{
si_info_t *sii;
uint found;
uint i;
sii = SI_INFO(sih);
found = 0;
for (i = 0; i < sii->numcores; i++)
if (sii->common_info->coreid[i] == coreid) {
if (found == coreunit)
return (i);
found++;
}
return (BADIDX);
}
/* return list of found cores */
uint
si_corelist(si_t *sih, uint coreid[])
{
si_info_t *sii;
sii = SI_INFO(sih);
bcopy((uchar*)sii->common_info->coreid, (uchar*)coreid, (sii->numcores * sizeof(uint)));
return (sii->numcores);
}
/* return current register mapping */
void *
si_coreregs(si_t *sih)
{
si_info_t *sii;
sii = SI_INFO(sih);
ASSERT(GOODREGS(sii->curmap));
return (sii->curmap);
}
/*
* This function changes logical "focus" to the indicated core;
* must be called with interrupts off.
* Moreover, callers should keep interrupts off during switching out of and back to d11 core
*/
void *
si_setcore(si_t *sih, uint coreid, uint coreunit)
{
uint idx;
idx = si_findcoreidx(sih, coreid, coreunit);
if (!GOODIDX(idx))
return (NULL);
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_setcoreidx(sih, idx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_setcoreidx(sih, idx);
else {
ASSERT(0);
return NULL;
}
}
void *
si_setcoreidx(si_t *sih, uint coreidx)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_setcoreidx(sih, coreidx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_setcoreidx(sih, coreidx);
else {
ASSERT(0);
return NULL;
}
}
/* Turn off interrupt as required by sb_setcore, before switch core */
void *si_switch_core(si_t *sih, uint coreid, uint *origidx, uint *intr_val)
{
void *cc;
si_info_t *sii;
sii = SI_INFO(sih);
INTR_OFF(sii, *intr_val);
*origidx = sii->curidx;
cc = si_setcore(sih, coreid, 0);
ASSERT(cc != NULL);
return cc;
}
/* restore coreidx and restore interrupt */
void si_restore_core(si_t *sih, uint coreid, uint intr_val)
{
si_info_t *sii;
sii = SI_INFO(sih);
si_setcoreidx(sih, coreid);
INTR_RESTORE(sii, intr_val);
}
int
si_numaddrspaces(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_numaddrspaces(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_numaddrspaces(sih);
else {
ASSERT(0);
return 0;
}
}
uint32
si_addrspace(si_t *sih, uint asidx)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_addrspace(sih, asidx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_addrspace(sih, asidx);
else {
ASSERT(0);
return 0;
}
}
uint32
si_addrspacesize(si_t *sih, uint asidx)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_addrspacesize(sih, asidx);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_addrspacesize(sih, asidx);
else {
ASSERT(0);
return 0;
}
}
uint32
si_core_cflags(si_t *sih, uint32 mask, uint32 val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_core_cflags(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_core_cflags(sih, mask, val);
else {
ASSERT(0);
return 0;
}
}
void
si_core_cflags_wo(si_t *sih, uint32 mask, uint32 val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_cflags_wo(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_core_cflags_wo(sih, mask, val);
else
ASSERT(0);
}
uint32
si_core_sflags(si_t *sih, uint32 mask, uint32 val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_core_sflags(sih, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_core_sflags(sih, mask, val);
else {
ASSERT(0);
return 0;
}
}
bool
si_iscoreup(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_iscoreup(sih);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_iscoreup(sih);
else {
ASSERT(0);
return FALSE;
}
}
void
si_write_wrapperreg(si_t *sih, uint32 offset, uint32 val)
{
/* only for 4319, no requirement for SOCI_SB */
if (CHIPTYPE(sih->socitype) == SOCI_AI) {
ai_write_wrap_reg(sih, offset, val);
}
else
return;
return;
}
uint
si_corereg(si_t *sih, uint coreidx, uint regoff, uint mask, uint val)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
return sb_corereg(sih, coreidx, regoff, mask, val);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
return ai_corereg(sih, coreidx, regoff, mask, val);
else {
ASSERT(0);
return 0;
}
}
void
si_core_disable(si_t *sih, uint32 bits)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_disable(sih, bits);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_core_disable(sih, bits);
}
void
si_core_reset(si_t *sih, uint32 bits, uint32 resetbits)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_reset(sih, bits, resetbits);
else if (CHIPTYPE(sih->socitype) == SOCI_AI)
ai_core_reset(sih, bits, resetbits);
}
void
si_core_tofixup(si_t *sih)
{
if (CHIPTYPE(sih->socitype) == SOCI_SB)
sb_core_tofixup(sih);
}
/* Run bist on current core. Caller needs to take care of core-specific bist hazards */
int
si_corebist(si_t *sih)
{
uint32 cflags;
int result = 0;
/* Read core control flags */
cflags = si_core_cflags(sih, 0, 0);
/* Set bist & fgc */
si_core_cflags(sih, 0, (SICF_BIST_EN | SICF_FGC));
/* Wait for bist done */
SPINWAIT(((si_core_sflags(sih, 0, 0) & SISF_BIST_DONE) == 0), 100000);
if (si_core_sflags(sih, 0, 0) & SISF_BIST_ERROR)
result = BCME_ERROR;
/* Reset core control flags */
si_core_cflags(sih, 0xffff, cflags);
return result;
}
static uint32
factor6(uint32 x)
{
switch (x) {
case CC_F6_2: return 2;
case CC_F6_3: return 3;
case CC_F6_4: return 4;
case CC_F6_5: return 5;
case CC_F6_6: return 6;
case CC_F6_7: return 7;
default: return 0;
}
}
/* calculate the speed the SI would run at given a set of clockcontrol values */
uint32
si_clock_rate(uint32 pll_type, uint32 n, uint32 m)
{
uint32 n1, n2, clock, m1, m2, m3, mc;
n1 = n & CN_N1_MASK;
n2 = (n & CN_N2_MASK) >> CN_N2_SHIFT;
if (pll_type == PLL_TYPE6) {
if (m & CC_T6_MMASK)
return CC_T6_M1;
else
return CC_T6_M0;
} else if ((pll_type == PLL_TYPE1) ||
(pll_type == PLL_TYPE3) ||
(pll_type == PLL_TYPE4) ||
(pll_type == PLL_TYPE7)) {
n1 = factor6(n1);
n2 += CC_F5_BIAS;
} else if (pll_type == PLL_TYPE2) {
n1 += CC_T2_BIAS;
n2 += CC_T2_BIAS;
ASSERT((n1 >= 2) && (n1 <= 7));
ASSERT((n2 >= 5) && (n2 <= 23));
} else if (pll_type == PLL_TYPE5) {
return (100000000);
} else
ASSERT(0);
/* PLL types 3 and 7 use BASE2 (25Mhz) */
if ((pll_type == PLL_TYPE3) ||
(pll_type == PLL_TYPE7)) {
clock = CC_CLOCK_BASE2 * n1 * n2;
} else
clock = CC_CLOCK_BASE1 * n1 * n2;
if (clock == 0)
return 0;
m1 = m & CC_M1_MASK;
m2 = (m & CC_M2_MASK) >> CC_M2_SHIFT;
m3 = (m & CC_M3_MASK) >> CC_M3_SHIFT;
mc = (m & CC_MC_MASK) >> CC_MC_SHIFT;
if ((pll_type == PLL_TYPE1) ||
(pll_type == PLL_TYPE3) ||
(pll_type == PLL_TYPE4) ||
(pll_type == PLL_TYPE7)) {
m1 = factor6(m1);
if ((pll_type == PLL_TYPE1) || (pll_type == PLL_TYPE3))
m2 += CC_F5_BIAS;
else
m2 = factor6(m2);
m3 = factor6(m3);
switch (mc) {
case CC_MC_BYPASS: return (clock);
case CC_MC_M1: return (clock / m1);
case CC_MC_M1M2: return (clock / (m1 * m2));
case CC_MC_M1M2M3: return (clock / (m1 * m2 * m3));
case CC_MC_M1M3: return (clock / (m1 * m3));
default: return (0);
}
} else {
ASSERT(pll_type == PLL_TYPE2);
m1 += CC_T2_BIAS;
m2 += CC_T2M2_BIAS;
m3 += CC_T2_BIAS;
ASSERT((m1 >= 2) && (m1 <= 7));
ASSERT((m2 >= 3) && (m2 <= 10));
ASSERT((m3 >= 2) && (m3 <= 7));
if ((mc & CC_T2MC_M1BYP) == 0)
clock /= m1;
if ((mc & CC_T2MC_M2BYP) == 0)
clock /= m2;
if ((mc & CC_T2MC_M3BYP) == 0)
clock /= m3;
return (clock);
}
}
/* set chip watchdog reset timer to fire in 'ticks' */
void
si_watchdog(si_t *sih, uint ticks)
{
if (PMUCTL_ENAB(sih)) {
if ((sih->chip == BCM4319_CHIP_ID) && (sih->chiprev == 0) && (ticks != 0)) {
si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, clk_ctl_st), ~0, 0x2);
si_setcore(sih, USB20D_CORE_ID, 0);
si_core_disable(sih, 1);
si_setcore(sih, CC_CORE_ID, 0);
}
if (ticks == 1)
ticks = 2;
si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, pmuwatchdog), ~0, ticks);
} else {
/* instant NMI */
si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, watchdog), ~0, ticks);
}
}
#if !defined(BCMBUSTYPE) || (BCMBUSTYPE == SI_BUS)
/* trigger watchdog reset after ms milliseconds */
void
si_watchdog_ms(si_t *sih, uint32 ms)
{
si_info_t *sii;
sii = SI_INFO(sih);
si_watchdog(sih, wd_msticks * ms);
}
#endif
/* initialize the sdio core */
void
si_sdio_init(si_t *sih)
{
si_info_t *sii = SI_INFO(sih);
if (((sih->buscoretype == PCMCIA_CORE_ID) && (sih->buscorerev >= 8)) ||
(sih->buscoretype == SDIOD_CORE_ID)) {
uint idx;
#ifdef HTC_KlocWork
sdpcmd_regs_t *sdpregs=NULL;
#else
sdpcmd_regs_t *sdpregs;
#endif
/* get the current core index */
idx = sii->curidx;
ASSERT(idx == si_findcoreidx(sih, D11_CORE_ID, 0));
/* switch to sdio core */
if (!(sdpregs = (sdpcmd_regs_t *)si_setcore(sih, PCMCIA_CORE_ID, 0)))
sdpregs = (sdpcmd_regs_t *)si_setcore(sih, SDIOD_CORE_ID, 0);
ASSERT(sdpregs);
SI_MSG(("si_sdio_init: For PCMCIA/SDIO Corerev %d, enable ints from core %d "
"through SD core %d (%p)\n",
sih->buscorerev, idx, sii->curidx, sdpregs));
#ifdef HTC_KlocWork
if(sdpregs != NULL) {
/* enable backplane error and core interrupts */
W_REG(sii->osh, &sdpregs->hostintmask, I_SBINT);
W_REG(sii->osh, &sdpregs->sbintmask, (I_SB_SERR | I_SB_RESPERR | (1 << idx)));
}else
SI_ERROR(("[HTCKW] si_sdio_init: sdpregs is NULL\n"));
#else
/* enable backplane error and core interrupts */
W_REG(sii->osh, &sdpregs->hostintmask, I_SBINT);
W_REG(sii->osh, &sdpregs->sbintmask, (I_SB_SERR | I_SB_RESPERR | (1 << idx)));
#endif
/* switch back to previous core */
si_setcoreidx(sih, idx);
}
/* enable interrupts */
bcmsdh_intr_enable(sii->sdh);
}
/* change logical "focus" to the gpio core for optimized access */
void *
si_gpiosetcore(si_t *sih)
{
return (si_setcoreidx(sih, SI_CC_IDX));
}
/* mask&set gpiocontrol bits */
uint32
si_gpiocontrol(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
regoff = 0;
/* gpios could be shared on router platforms
* ignore reservation if it's high priority (e.g., test apps)
*/
if ((priority != GPIO_HI_PRIORITY) &&
(BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpiocontrol);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* mask&set gpio output enable bits */
uint32
si_gpioouten(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
regoff = 0;
/* gpios could be shared on router platforms
* ignore reservation if it's high priority (e.g., test apps)
*/
if ((priority != GPIO_HI_PRIORITY) &&
(BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpioouten);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* mask&set gpio output bits */
uint32
si_gpioout(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
uint regoff;
regoff = 0;
/* gpios could be shared on router platforms
* ignore reservation if it's high priority (e.g., test apps)
*/
if ((priority != GPIO_HI_PRIORITY) &&
(BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpioout);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* reserve one gpio */
uint32
si_gpioreserve(si_t *sih, uint32 gpio_bitmask, uint8 priority)
{
si_info_t *sii;
sii = SI_INFO(sih);
/* only cores on SI_BUS share GPIO's and only applcation users need to
* reserve/release GPIO
*/
if ((BUSTYPE(sih->bustype) != SI_BUS) || (!priority)) {
ASSERT((BUSTYPE(sih->bustype) == SI_BUS) && (priority));
return -1;
}
/* make sure only one bit is set */
if ((!gpio_bitmask) || ((gpio_bitmask) & (gpio_bitmask - 1))) {
ASSERT((gpio_bitmask) && !((gpio_bitmask) & (gpio_bitmask - 1)));
return -1;
}
/* already reserved */
if (si_gpioreservation & gpio_bitmask)
return -1;
/* set reservation */
si_gpioreservation |= gpio_bitmask;
return si_gpioreservation;
}
/* release one gpio */
/*
* releasing the gpio doesn't change the current value on the GPIO last write value
* persists till some one overwrites it
*/
uint32
si_gpiorelease(si_t *sih, uint32 gpio_bitmask, uint8 priority)
{
si_info_t *sii;
sii = SI_INFO(sih);
/* only cores on SI_BUS share GPIO's and only applcation users need to
* reserve/release GPIO
*/
if ((BUSTYPE(sih->bustype) != SI_BUS) || (!priority)) {
ASSERT((BUSTYPE(sih->bustype) == SI_BUS) && (priority));
return -1;
}
/* make sure only one bit is set */
if ((!gpio_bitmask) || ((gpio_bitmask) & (gpio_bitmask - 1))) {
ASSERT((gpio_bitmask) && !((gpio_bitmask) & (gpio_bitmask - 1)));
return -1;
}
/* already released */
if (!(si_gpioreservation & gpio_bitmask))
return -1;
/* clear reservation */
si_gpioreservation &= ~gpio_bitmask;
return si_gpioreservation;
}
/* return the current gpioin register value */
uint32
si_gpioin(si_t *sih)
{
si_info_t *sii;
uint regoff;
sii = SI_INFO(sih);
regoff = 0;
regoff = OFFSETOF(chipcregs_t, gpioin);
return (si_corereg(sih, SI_CC_IDX, regoff, 0, 0));
}
/* mask&set gpio interrupt polarity bits */
uint32
si_gpiointpolarity(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
si_info_t *sii;
uint regoff;
sii = SI_INFO(sih);
regoff = 0;
/* gpios could be shared on router platforms */
if ((BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpiointpolarity);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* mask&set gpio interrupt mask bits */
uint32
si_gpiointmask(si_t *sih, uint32 mask, uint32 val, uint8 priority)
{
si_info_t *sii;
uint regoff;
sii = SI_INFO(sih);
regoff = 0;
/* gpios could be shared on router platforms */
if ((BUSTYPE(sih->bustype) == SI_BUS) && (val || mask)) {
mask = priority ? (si_gpioreservation & mask) :
((si_gpioreservation | mask) & ~(si_gpioreservation));
val &= mask;
}
regoff = OFFSETOF(chipcregs_t, gpiointmask);
return (si_corereg(sih, SI_CC_IDX, regoff, mask, val));
}
/* assign the gpio to an led */
uint32
si_gpioled(si_t *sih, uint32 mask, uint32 val)
{
si_info_t *sii;
sii = SI_INFO(sih);
if (sih->ccrev < 16)
return -1;
/* gpio led powersave reg */
return (si_corereg(sih, SI_CC_IDX, OFFSETOF(chipcregs_t, gpiotimeroutmask), mask, val));
}
/* mask&set gpio timer val */
uint32
si_gpiotimerval(si_t *sih, uint32 mask, uint32 gpiotimerval)
{
si_info_t *sii;
sii = SI_INFO(sih);
if (sih->ccrev < 16)
return -1;
return (si_corereg(sih, SI_CC_IDX,
OFFSETOF(chipcregs_t, gpiotimerval), mask, gpiotimerval));
}
uint32
si_gpiopull(si_t *sih, bool updown, uint32 mask, uint32 val)
{
si_info_t *sii;
uint offs;
sii = SI_INFO(sih);
if (sih->ccrev < 20)
return -1;
offs = (updown ? OFFSETOF(chipcregs_t, gpiopulldown) : OFFSETOF(chipcregs_t, gpiopullup));
return (si_corereg(sih, SI_CC_IDX, offs, mask, val));
}
uint32
si_gpioevent(si_t *sih, uint regtype, uint32 mask, uint32 val)
{
si_info_t *sii;
uint offs;
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return -1;
if (regtype == GPIO_REGEVT)
offs = OFFSETOF(chipcregs_t, gpioevent);
else if (regtype == GPIO_REGEVT_INTMSK)
offs = OFFSETOF(chipcregs_t, gpioeventintmask);
else if (regtype == GPIO_REGEVT_INTPOL)
offs = OFFSETOF(chipcregs_t, gpioeventintpolarity);
else
return -1;
return (si_corereg(sih, SI_CC_IDX, offs, mask, val));
}
void *
si_gpio_handler_register(si_t *sih, uint32 event,
bool level, gpio_handler_t cb, void *arg)
{
si_info_t *sii;
gpioh_item_t *gi;
ASSERT(event);
ASSERT(cb != NULL);
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return NULL;
if ((gi = MALLOC(sii->osh, sizeof(gpioh_item_t))) == NULL)
return NULL;
bzero(gi, sizeof(gpioh_item_t));
gi->event = event;
gi->handler = cb;
gi->arg = arg;
gi->level = level;
gi->next = sii->gpioh_head;
sii->gpioh_head = gi;
return (void *)(gi);
}
void
si_gpio_handler_unregister(si_t *sih, void *gpioh)
{
si_info_t *sii;
gpioh_item_t *p, *n;
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return;
ASSERT(sii->gpioh_head != NULL);
if ((void*)sii->gpioh_head == gpioh) {
sii->gpioh_head = sii->gpioh_head->next;
MFREE(sii->osh, gpioh, sizeof(gpioh_item_t));
return;
} else {
p = sii->gpioh_head;
n = p->next;
while (n) {
if ((void*)n == gpioh) {
p->next = n->next;
MFREE(sii->osh, gpioh, sizeof(gpioh_item_t));
return;
}
p = n;
n = n->next;
}
}
ASSERT(0); /* Not found in list */
}
void
si_gpio_handler_process(si_t *sih)
{
si_info_t *sii;
gpioh_item_t *h;
uint32 status;
uint32 level = si_gpioin(sih);
uint32 edge = si_gpioevent(sih, GPIO_REGEVT, 0, 0);
sii = SI_INFO(sih);
for (h = sii->gpioh_head; h != NULL; h = h->next) {
if (h->handler) {
status = (h->level ? level : edge);
if (status & h->event)
h->handler(status, h->arg);
}
}
si_gpioevent(sih, GPIO_REGEVT, edge, edge); /* clear edge-trigger status */
}
uint32
si_gpio_int_enable(si_t *sih, bool enable)
{
si_info_t *sii;
uint offs;
sii = SI_INFO(sih);
if (sih->ccrev < 11)
return -1;
offs = OFFSETOF(chipcregs_t, intmask);
return (si_corereg(sih, SI_CC_IDX, offs, CI_GPIO, (enable ? CI_GPIO : 0)));
}
/* Return the RAM size of the SOCRAM core */
uint32
si_socram_size(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
sbsocramregs_t *regs;
bool wasup;
uint corerev;
uint32 coreinfo;
uint memsize = 0;
sii = SI_INFO(sih);
/* Block ints and save current core */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
/* Switch to SOCRAM core */
if (!(regs = si_setcore(sih, SOCRAM_CORE_ID, 0)))
goto done;
/* Get info for determining size */
if (!(wasup = si_iscoreup(sih)))
si_core_reset(sih, 0, 0);
corerev = si_corerev(sih);
coreinfo = R_REG(sii->osh, ®s->coreinfo);
/* Calculate size from coreinfo based on rev */
if (corerev == 0)
memsize = 1 << (16 + (coreinfo & SRCI_MS0_MASK));
else if (corerev < 3) {
memsize = 1 << (SR_BSZ_BASE + (coreinfo & SRCI_SRBSZ_MASK));
memsize *= (coreinfo & SRCI_SRNB_MASK) >> SRCI_SRNB_SHIFT;
} else {
uint nb = (coreinfo & SRCI_SRNB_MASK) >> SRCI_SRNB_SHIFT;
uint bsz = (coreinfo & SRCI_SRBSZ_MASK);
uint lss = (coreinfo & SRCI_LSS_MASK) >> SRCI_LSS_SHIFT;
if (lss != 0)
nb --;
memsize = nb * (1 << (bsz + SR_BSZ_BASE));
if (lss != 0)
memsize += (1 << ((lss - 1) + SR_BSZ_BASE));
}
/* Return to previous state and core */
if (!wasup)
si_core_disable(sih, 0);
si_setcoreidx(sih, origidx);
done:
INTR_RESTORE(sii, intr_val);
return memsize;
}
void
si_btcgpiowar(si_t *sih)
{
si_info_t *sii;
uint origidx;
uint intr_val = 0;
chipcregs_t *cc;
sii = SI_INFO(sih);
/* Make sure that there is ChipCommon core present &&
* UART_TX is strapped to 1
*/
if (!(sih->cccaps & CC_CAP_UARTGPIO))
return;
/* si_corereg cannot be used as we have to guarantee 8-bit read/writes */
INTR_OFF(sii, intr_val);
origidx = si_coreidx(sih);
cc = (chipcregs_t *)si_setcore(sih, CC_CORE_ID, 0);
ASSERT(cc != NULL);
#ifdef HTC_KlocWork
if(cc != NULL)
#endif
W_REG(sii->osh, &cc->uart0mcr, R_REG(sii->osh, &cc->uart0mcr) | 0x04);
/* restore the original index */
si_setcoreidx(sih, origidx);
INTR_RESTORE(sii, intr_val);
}
/* check if the device is removed */
bool
si_deviceremoved(si_t *sih)
{
uint32 w;
si_info_t *sii;
sii = SI_INFO(sih);
switch (BUSTYPE(sih->bustype)) {
case PCI_BUS:
ASSERT(sii->osh != NULL);
w = OSL_PCI_READ_CONFIG(sii->osh, PCI_CFG_VID, sizeof(uint32));
if ((w & 0xFFFF) != VENDOR_BROADCOM)
return TRUE;
else
return FALSE;
default:
return FALSE;
}
return FALSE;
}
| gpl-2.0 |
heukelum/linux | arch/x86/mm/dump_pagetables.c | 134 | 11731 | /*
* Debug helper to dump the current kernel pagetables of the system
* so that we can see what the various memory ranges are set to.
*
* (C) Copyright 2008 Intel Corporation
*
* Author: Arjan van de Ven <arjan@linux.intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License.
*/
#include <linux/debugfs.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/seq_file.h>
#include <asm/pgtable.h>
/*
* The dumper groups pagetable entries of the same type into one, and for
* that it needs to keep some state when walking, and flush this state
* when a "break" in the continuity is found.
*/
struct pg_state {
int level;
pgprot_t current_prot;
unsigned long start_address;
unsigned long current_address;
const struct addr_marker *marker;
unsigned long lines;
bool to_dmesg;
bool check_wx;
unsigned long wx_pages;
};
struct addr_marker {
unsigned long start_address;
const char *name;
unsigned long max_lines;
};
/* indices for address_markers; keep sync'd w/ address_markers below */
enum address_markers_idx {
USER_SPACE_NR = 0,
#ifdef CONFIG_X86_64
KERNEL_SPACE_NR,
LOW_KERNEL_NR,
VMALLOC_START_NR,
VMEMMAP_START_NR,
# ifdef CONFIG_X86_ESPFIX64
ESPFIX_START_NR,
# endif
HIGH_KERNEL_NR,
MODULES_VADDR_NR,
MODULES_END_NR,
#else
KERNEL_SPACE_NR,
VMALLOC_START_NR,
VMALLOC_END_NR,
# ifdef CONFIG_HIGHMEM
PKMAP_BASE_NR,
# endif
FIXADDR_START_NR,
#endif
};
/* Address space markers hints */
static struct addr_marker address_markers[] = {
{ 0, "User Space" },
#ifdef CONFIG_X86_64
{ 0x8000000000000000UL, "Kernel Space" },
{ 0/* PAGE_OFFSET */, "Low Kernel Mapping" },
{ 0/* VMALLOC_START */, "vmalloc() Area" },
{ 0/* VMEMMAP_START */, "Vmemmap" },
# ifdef CONFIG_X86_ESPFIX64
{ ESPFIX_BASE_ADDR, "ESPfix Area", 16 },
# endif
# ifdef CONFIG_EFI
{ EFI_VA_END, "EFI Runtime Services" },
# endif
{ __START_KERNEL_map, "High Kernel Mapping" },
{ MODULES_VADDR, "Modules" },
{ MODULES_END, "End Modules" },
#else
{ PAGE_OFFSET, "Kernel Mapping" },
{ 0/* VMALLOC_START */, "vmalloc() Area" },
{ 0/*VMALLOC_END*/, "vmalloc() End" },
# ifdef CONFIG_HIGHMEM
{ 0/*PKMAP_BASE*/, "Persistent kmap() Area" },
# endif
{ 0/*FIXADDR_START*/, "Fixmap Area" },
#endif
{ -1, NULL } /* End of list */
};
/* Multipliers for offsets within the PTEs */
#define PTE_LEVEL_MULT (PAGE_SIZE)
#define PMD_LEVEL_MULT (PTRS_PER_PTE * PTE_LEVEL_MULT)
#define PUD_LEVEL_MULT (PTRS_PER_PMD * PMD_LEVEL_MULT)
#define PGD_LEVEL_MULT (PTRS_PER_PUD * PUD_LEVEL_MULT)
#define pt_dump_seq_printf(m, to_dmesg, fmt, args...) \
({ \
if (to_dmesg) \
printk(KERN_INFO fmt, ##args); \
else \
if (m) \
seq_printf(m, fmt, ##args); \
})
#define pt_dump_cont_printf(m, to_dmesg, fmt, args...) \
({ \
if (to_dmesg) \
printk(KERN_CONT fmt, ##args); \
else \
if (m) \
seq_printf(m, fmt, ##args); \
})
/*
* Print a readable form of a pgprot_t to the seq_file
*/
static void printk_prot(struct seq_file *m, pgprot_t prot, int level, bool dmsg)
{
pgprotval_t pr = pgprot_val(prot);
static const char * const level_name[] =
{ "cr3", "pgd", "pud", "pmd", "pte" };
if (!pgprot_val(prot)) {
/* Not present */
pt_dump_cont_printf(m, dmsg, " ");
} else {
if (pr & _PAGE_USER)
pt_dump_cont_printf(m, dmsg, "USR ");
else
pt_dump_cont_printf(m, dmsg, " ");
if (pr & _PAGE_RW)
pt_dump_cont_printf(m, dmsg, "RW ");
else
pt_dump_cont_printf(m, dmsg, "ro ");
if (pr & _PAGE_PWT)
pt_dump_cont_printf(m, dmsg, "PWT ");
else
pt_dump_cont_printf(m, dmsg, " ");
if (pr & _PAGE_PCD)
pt_dump_cont_printf(m, dmsg, "PCD ");
else
pt_dump_cont_printf(m, dmsg, " ");
/* Bit 7 has a different meaning on level 3 vs 4 */
if (level <= 3 && pr & _PAGE_PSE)
pt_dump_cont_printf(m, dmsg, "PSE ");
else
pt_dump_cont_printf(m, dmsg, " ");
if ((level == 4 && pr & _PAGE_PAT) ||
((level == 3 || level == 2) && pr & _PAGE_PAT_LARGE))
pt_dump_cont_printf(m, dmsg, "PAT ");
else
pt_dump_cont_printf(m, dmsg, " ");
if (pr & _PAGE_GLOBAL)
pt_dump_cont_printf(m, dmsg, "GLB ");
else
pt_dump_cont_printf(m, dmsg, " ");
if (pr & _PAGE_NX)
pt_dump_cont_printf(m, dmsg, "NX ");
else
pt_dump_cont_printf(m, dmsg, "x ");
}
pt_dump_cont_printf(m, dmsg, "%s\n", level_name[level]);
}
/*
* On 64 bits, sign-extend the 48 bit address to 64 bit
*/
static unsigned long normalize_addr(unsigned long u)
{
#ifdef CONFIG_X86_64
return (signed long)(u << 16) >> 16;
#else
return u;
#endif
}
/*
* This function gets called on a break in a continuous series
* of PTE entries; the next one is different so we need to
* print what we collected so far.
*/
static void note_page(struct seq_file *m, struct pg_state *st,
pgprot_t new_prot, int level)
{
pgprotval_t prot, cur;
static const char units[] = "BKMGTPE";
/*
* If we have a "break" in the series, we need to flush the state that
* we have now. "break" is either changing perms, levels or
* address space marker.
*/
prot = pgprot_val(new_prot);
cur = pgprot_val(st->current_prot);
if (!st->level) {
/* First entry */
st->current_prot = new_prot;
st->level = level;
st->marker = address_markers;
st->lines = 0;
pt_dump_seq_printf(m, st->to_dmesg, "---[ %s ]---\n",
st->marker->name);
} else if (prot != cur || level != st->level ||
st->current_address >= st->marker[1].start_address) {
const char *unit = units;
unsigned long delta;
int width = sizeof(unsigned long) * 2;
pgprotval_t pr = pgprot_val(st->current_prot);
if (st->check_wx && (pr & _PAGE_RW) && !(pr & _PAGE_NX)) {
WARN_ONCE(1,
"x86/mm: Found insecure W+X mapping at address %p/%pS\n",
(void *)st->start_address,
(void *)st->start_address);
st->wx_pages += (st->current_address -
st->start_address) / PAGE_SIZE;
}
/*
* Now print the actual finished series
*/
if (!st->marker->max_lines ||
st->lines < st->marker->max_lines) {
pt_dump_seq_printf(m, st->to_dmesg,
"0x%0*lx-0x%0*lx ",
width, st->start_address,
width, st->current_address);
delta = st->current_address - st->start_address;
while (!(delta & 1023) && unit[1]) {
delta >>= 10;
unit++;
}
pt_dump_cont_printf(m, st->to_dmesg, "%9lu%c ",
delta, *unit);
printk_prot(m, st->current_prot, st->level,
st->to_dmesg);
}
st->lines++;
/*
* We print markers for special areas of address space,
* such as the start of vmalloc space etc.
* This helps in the interpretation.
*/
if (st->current_address >= st->marker[1].start_address) {
if (st->marker->max_lines &&
st->lines > st->marker->max_lines) {
unsigned long nskip =
st->lines - st->marker->max_lines;
pt_dump_seq_printf(m, st->to_dmesg,
"... %lu entr%s skipped ... \n",
nskip,
nskip == 1 ? "y" : "ies");
}
st->marker++;
st->lines = 0;
pt_dump_seq_printf(m, st->to_dmesg, "---[ %s ]---\n",
st->marker->name);
}
st->start_address = st->current_address;
st->current_prot = new_prot;
st->level = level;
}
}
static void walk_pte_level(struct seq_file *m, struct pg_state *st, pmd_t addr,
unsigned long P)
{
int i;
pte_t *start;
pgprotval_t prot;
start = (pte_t *) pmd_page_vaddr(addr);
for (i = 0; i < PTRS_PER_PTE; i++) {
prot = pte_flags(*start);
st->current_address = normalize_addr(P + i * PTE_LEVEL_MULT);
note_page(m, st, __pgprot(prot), 4);
start++;
}
}
#if PTRS_PER_PMD > 1
static void walk_pmd_level(struct seq_file *m, struct pg_state *st, pud_t addr,
unsigned long P)
{
int i;
pmd_t *start;
pgprotval_t prot;
start = (pmd_t *) pud_page_vaddr(addr);
for (i = 0; i < PTRS_PER_PMD; i++) {
st->current_address = normalize_addr(P + i * PMD_LEVEL_MULT);
if (!pmd_none(*start)) {
if (pmd_large(*start) || !pmd_present(*start)) {
prot = pmd_flags(*start);
note_page(m, st, __pgprot(prot), 3);
} else {
walk_pte_level(m, st, *start,
P + i * PMD_LEVEL_MULT);
}
} else
note_page(m, st, __pgprot(0), 3);
start++;
}
}
#else
#define walk_pmd_level(m,s,a,p) walk_pte_level(m,s,__pmd(pud_val(a)),p)
#define pud_large(a) pmd_large(__pmd(pud_val(a)))
#define pud_none(a) pmd_none(__pmd(pud_val(a)))
#endif
#if PTRS_PER_PUD > 1
static void walk_pud_level(struct seq_file *m, struct pg_state *st, pgd_t addr,
unsigned long P)
{
int i;
pud_t *start;
pgprotval_t prot;
start = (pud_t *) pgd_page_vaddr(addr);
for (i = 0; i < PTRS_PER_PUD; i++) {
st->current_address = normalize_addr(P + i * PUD_LEVEL_MULT);
if (!pud_none(*start)) {
if (pud_large(*start) || !pud_present(*start)) {
prot = pud_flags(*start);
note_page(m, st, __pgprot(prot), 2);
} else {
walk_pmd_level(m, st, *start,
P + i * PUD_LEVEL_MULT);
}
} else
note_page(m, st, __pgprot(0), 2);
start++;
}
}
#else
#define walk_pud_level(m,s,a,p) walk_pmd_level(m,s,__pud(pgd_val(a)),p)
#define pgd_large(a) pud_large(__pud(pgd_val(a)))
#define pgd_none(a) pud_none(__pud(pgd_val(a)))
#endif
static inline bool is_hypervisor_range(int idx)
{
#ifdef CONFIG_X86_64
/*
* ffff800000000000 - ffff87ffffffffff is reserved for
* the hypervisor.
*/
return (idx >= pgd_index(__PAGE_OFFSET) - 16) &&
(idx < pgd_index(__PAGE_OFFSET));
#else
return false;
#endif
}
static void ptdump_walk_pgd_level_core(struct seq_file *m, pgd_t *pgd,
bool checkwx)
{
#ifdef CONFIG_X86_64
pgd_t *start = (pgd_t *) &init_level4_pgt;
#else
pgd_t *start = swapper_pg_dir;
#endif
pgprotval_t prot;
int i;
struct pg_state st = {};
if (pgd) {
start = pgd;
st.to_dmesg = true;
}
st.check_wx = checkwx;
if (checkwx)
st.wx_pages = 0;
for (i = 0; i < PTRS_PER_PGD; i++) {
st.current_address = normalize_addr(i * PGD_LEVEL_MULT);
if (!pgd_none(*start) && !is_hypervisor_range(i)) {
if (pgd_large(*start) || !pgd_present(*start)) {
prot = pgd_flags(*start);
note_page(m, &st, __pgprot(prot), 1);
} else {
walk_pud_level(m, &st, *start,
i * PGD_LEVEL_MULT);
}
} else
note_page(m, &st, __pgprot(0), 1);
start++;
}
/* Flush out the last page */
st.current_address = normalize_addr(PTRS_PER_PGD*PGD_LEVEL_MULT);
note_page(m, &st, __pgprot(0), 0);
if (!checkwx)
return;
if (st.wx_pages)
pr_info("x86/mm: Checked W+X mappings: FAILED, %lu W+X pages found.\n",
st.wx_pages);
else
pr_info("x86/mm: Checked W+X mappings: passed, no W+X pages found.\n");
}
void ptdump_walk_pgd_level(struct seq_file *m, pgd_t *pgd)
{
ptdump_walk_pgd_level_core(m, pgd, false);
}
EXPORT_SYMBOL_GPL(ptdump_walk_pgd_level);
void ptdump_walk_pgd_level_checkwx(void)
{
ptdump_walk_pgd_level_core(NULL, NULL, true);
}
static int __init pt_dump_init(void)
{
/*
* Various markers are not compile-time constants, so assign them
* here.
*/
#ifdef CONFIG_X86_64
address_markers[LOW_KERNEL_NR].start_address = PAGE_OFFSET;
address_markers[VMALLOC_START_NR].start_address = VMALLOC_START;
address_markers[VMEMMAP_START_NR].start_address = VMEMMAP_START;
#endif
#ifdef CONFIG_X86_32
address_markers[VMALLOC_START_NR].start_address = VMALLOC_START;
address_markers[VMALLOC_END_NR].start_address = VMALLOC_END;
# ifdef CONFIG_HIGHMEM
address_markers[PKMAP_BASE_NR].start_address = PKMAP_BASE;
# endif
address_markers[FIXADDR_START_NR].start_address = FIXADDR_START;
#endif
return 0;
}
__initcall(pt_dump_init);
| gpl-2.0 |
Frank77GLD/android_kernel_YG_m805_892x | drivers/gpu/drm/nouveau/nvc0_vram.c | 390 | 3742 | /*
* Copyright 2010 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "drmP.h"
#include "nouveau_drv.h"
#include "nouveau_mm.h"
/* 0 = unsupported
* 1 = non-compressed
* 3 = compressed
*/
static const u8 types[256] = {
1, 1, 3, 3, 3, 3, 0, 3, 3, 3, 3, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3,
3, 3, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0, 1, 1, 1, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 3, 3, 3, 3, 1, 1, 1, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3,
3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3,
3, 3, 0, 0, 0, 0, 0, 0, 3, 0, 0, 3, 0, 3, 0, 3,
3, 0, 3, 3, 3, 3, 3, 0, 0, 3, 0, 3, 0, 3, 3, 0,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 1, 1, 0
};
bool
nvc0_vram_flags_valid(struct drm_device *dev, u32 tile_flags)
{
u8 memtype = (tile_flags & NOUVEAU_GEM_TILE_LAYOUT_MASK) >> 8;
return likely((types[memtype] == 1));
}
int
nvc0_vram_new(struct drm_device *dev, u64 size, u32 align, u32 ncmin,
u32 type, struct nouveau_mem **pmem)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_mm *mm = dev_priv->engine.vram.mm;
struct nouveau_mm_node *r;
struct nouveau_mem *mem;
int ret;
size >>= 12;
align >>= 12;
ncmin >>= 12;
mem = kzalloc(sizeof(*mem), GFP_KERNEL);
if (!mem)
return -ENOMEM;
INIT_LIST_HEAD(&mem->regions);
mem->dev = dev_priv->dev;
mem->memtype = (type & 0xff);
mem->size = size;
mutex_lock(&mm->mutex);
do {
ret = nouveau_mm_get(mm, 1, size, ncmin, align, &r);
if (ret) {
mutex_unlock(&mm->mutex);
nv50_vram_del(dev, &mem);
return ret;
}
list_add_tail(&r->rl_entry, &mem->regions);
size -= r->length;
} while (size);
mutex_unlock(&mm->mutex);
r = list_first_entry(&mem->regions, struct nouveau_mm_node, rl_entry);
mem->offset = (u64)r->offset << 12;
*pmem = mem;
return 0;
}
int
nvc0_vram_init(struct drm_device *dev)
{
struct drm_nouveau_private *dev_priv = dev->dev_private;
struct nouveau_vram_engine *vram = &dev_priv->engine.vram;
const u32 rsvd_head = ( 256 * 1024) >> 12; /* vga memory */
const u32 rsvd_tail = (1024 * 1024) >> 12; /* vbios etc */
u32 length;
dev_priv->vram_size = nv_rd32(dev, 0x10f20c) << 20;
dev_priv->vram_size *= nv_rd32(dev, 0x121c74);
length = (dev_priv->vram_size >> 12) - rsvd_head - rsvd_tail;
return nouveau_mm_init(&vram->mm, rsvd_head, length, 1);
}
| gpl-2.0 |
fosser2/linux-2.6 | drivers/net/ipg.c | 390 | 61852 | /*
* ipg.c: Device Driver for the IP1000 Gigabit Ethernet Adapter
*
* Copyright (C) 2003, 2007 IC Plus Corp
*
* Original Author:
*
* Craig Rich
* Sundance Technology, Inc.
* www.sundanceti.com
* craig_rich@sundanceti.com
*
* Current Maintainer:
*
* Sorbica Shieh.
* http://www.icplus.com.tw
* sorbica@icplus.com.tw
*
* Jesse Huang
* http://www.icplus.com.tw
* jesse@icplus.com.tw
*/
#include <linux/crc32.h>
#include <linux/ethtool.h>
#include <linux/interrupt.h>
#include <linux/gfp.h>
#include <linux/mii.h>
#include <linux/mutex.h>
#include <asm/div64.h>
#define IPG_RX_RING_BYTES (sizeof(struct ipg_rx) * IPG_RFDLIST_LENGTH)
#define IPG_TX_RING_BYTES (sizeof(struct ipg_tx) * IPG_TFDLIST_LENGTH)
#define IPG_RESET_MASK \
(IPG_AC_GLOBAL_RESET | IPG_AC_RX_RESET | IPG_AC_TX_RESET | \
IPG_AC_DMA | IPG_AC_FIFO | IPG_AC_NETWORK | IPG_AC_HOST | \
IPG_AC_AUTO_INIT)
#define ipg_w32(val32, reg) iowrite32((val32), ioaddr + (reg))
#define ipg_w16(val16, reg) iowrite16((val16), ioaddr + (reg))
#define ipg_w8(val8, reg) iowrite8((val8), ioaddr + (reg))
#define ipg_r32(reg) ioread32(ioaddr + (reg))
#define ipg_r16(reg) ioread16(ioaddr + (reg))
#define ipg_r8(reg) ioread8(ioaddr + (reg))
enum {
netdev_io_size = 128
};
#include "ipg.h"
#define DRV_NAME "ipg"
MODULE_AUTHOR("IC Plus Corp. 2003");
MODULE_DESCRIPTION("IC Plus IP1000 Gigabit Ethernet Adapter Linux Driver");
MODULE_LICENSE("GPL");
/*
* Defaults
*/
#define IPG_MAX_RXFRAME_SIZE 0x0600
#define IPG_RXFRAG_SIZE 0x0600
#define IPG_RXSUPPORT_SIZE 0x0600
#define IPG_IS_JUMBO false
/*
* Variable record -- index by leading revision/length
* Revision/Length(=N*4), Address1, Data1, Address2, Data2,...,AddressN,DataN
*/
static unsigned short DefaultPhyParam[] = {
/* 11/12/03 IP1000A v1-3 rev=0x40 */
/*--------------------------------------------------------------------------
(0x4000|(15*4)), 31, 0x0001, 27, 0x01e0, 31, 0x0002, 22, 0x85bd, 24, 0xfff2,
27, 0x0c10, 28, 0x0c10, 29, 0x2c10, 31, 0x0003, 23, 0x92f6,
31, 0x0000, 23, 0x003d, 30, 0x00de, 20, 0x20e7, 9, 0x0700,
--------------------------------------------------------------------------*/
/* 12/17/03 IP1000A v1-4 rev=0x40 */
(0x4000 | (07 * 4)), 31, 0x0001, 27, 0x01e0, 31, 0x0002, 27, 0xeb8e, 31,
0x0000,
30, 0x005e, 9, 0x0700,
/* 01/09/04 IP1000A v1-5 rev=0x41 */
(0x4100 | (07 * 4)), 31, 0x0001, 27, 0x01e0, 31, 0x0002, 27, 0xeb8e, 31,
0x0000,
30, 0x005e, 9, 0x0700,
0x0000
};
static const char *ipg_brand_name[] = {
"IC PLUS IP1000 1000/100/10 based NIC",
"Sundance Technology ST2021 based NIC",
"Tamarack Microelectronics TC9020/9021 based NIC",
"D-Link NIC IP1000A"
};
static DEFINE_PCI_DEVICE_TABLE(ipg_pci_tbl) = {
{ PCI_VDEVICE(SUNDANCE, 0x1023), 0 },
{ PCI_VDEVICE(SUNDANCE, 0x2021), 1 },
{ PCI_VDEVICE(DLINK, 0x9021), 2 },
{ PCI_VDEVICE(DLINK, 0x4020), 3 },
{ 0, }
};
MODULE_DEVICE_TABLE(pci, ipg_pci_tbl);
static inline void __iomem *ipg_ioaddr(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
return sp->ioaddr;
}
#ifdef IPG_DEBUG
static void ipg_dump_rfdlist(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
unsigned int i;
u32 offset;
IPG_DEBUG_MSG("_dump_rfdlist\n");
printk(KERN_INFO "rx_current = %2.2x\n", sp->rx_current);
printk(KERN_INFO "rx_dirty = %2.2x\n", sp->rx_dirty);
printk(KERN_INFO "RFDList start address = %16.16lx\n",
(unsigned long) sp->rxd_map);
printk(KERN_INFO "RFDListPtr register = %8.8x%8.8x\n",
ipg_r32(IPG_RFDLISTPTR1), ipg_r32(IPG_RFDLISTPTR0));
for (i = 0; i < IPG_RFDLIST_LENGTH; i++) {
offset = (u32) &sp->rxd[i].next_desc - (u32) sp->rxd;
printk(KERN_INFO "%2.2x %4.4x RFDNextPtr = %16.16lx\n", i,
offset, (unsigned long) sp->rxd[i].next_desc);
offset = (u32) &sp->rxd[i].rfs - (u32) sp->rxd;
printk(KERN_INFO "%2.2x %4.4x RFS = %16.16lx\n", i,
offset, (unsigned long) sp->rxd[i].rfs);
offset = (u32) &sp->rxd[i].frag_info - (u32) sp->rxd;
printk(KERN_INFO "%2.2x %4.4x frag_info = %16.16lx\n", i,
offset, (unsigned long) sp->rxd[i].frag_info);
}
}
static void ipg_dump_tfdlist(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
unsigned int i;
u32 offset;
IPG_DEBUG_MSG("_dump_tfdlist\n");
printk(KERN_INFO "tx_current = %2.2x\n", sp->tx_current);
printk(KERN_INFO "tx_dirty = %2.2x\n", sp->tx_dirty);
printk(KERN_INFO "TFDList start address = %16.16lx\n",
(unsigned long) sp->txd_map);
printk(KERN_INFO "TFDListPtr register = %8.8x%8.8x\n",
ipg_r32(IPG_TFDLISTPTR1), ipg_r32(IPG_TFDLISTPTR0));
for (i = 0; i < IPG_TFDLIST_LENGTH; i++) {
offset = (u32) &sp->txd[i].next_desc - (u32) sp->txd;
printk(KERN_INFO "%2.2x %4.4x TFDNextPtr = %16.16lx\n", i,
offset, (unsigned long) sp->txd[i].next_desc);
offset = (u32) &sp->txd[i].tfc - (u32) sp->txd;
printk(KERN_INFO "%2.2x %4.4x TFC = %16.16lx\n", i,
offset, (unsigned long) sp->txd[i].tfc);
offset = (u32) &sp->txd[i].frag_info - (u32) sp->txd;
printk(KERN_INFO "%2.2x %4.4x frag_info = %16.16lx\n", i,
offset, (unsigned long) sp->txd[i].frag_info);
}
}
#endif
static void ipg_write_phy_ctl(void __iomem *ioaddr, u8 data)
{
ipg_w8(IPG_PC_RSVD_MASK & data, PHY_CTRL);
ndelay(IPG_PC_PHYCTRLWAIT_NS);
}
static void ipg_drive_phy_ctl_low_high(void __iomem *ioaddr, u8 data)
{
ipg_write_phy_ctl(ioaddr, IPG_PC_MGMTCLK_LO | data);
ipg_write_phy_ctl(ioaddr, IPG_PC_MGMTCLK_HI | data);
}
static void send_three_state(void __iomem *ioaddr, u8 phyctrlpolarity)
{
phyctrlpolarity |= (IPG_PC_MGMTDATA & 0) | IPG_PC_MGMTDIR;
ipg_drive_phy_ctl_low_high(ioaddr, phyctrlpolarity);
}
static void send_end(void __iomem *ioaddr, u8 phyctrlpolarity)
{
ipg_w8((IPG_PC_MGMTCLK_LO | (IPG_PC_MGMTDATA & 0) | IPG_PC_MGMTDIR |
phyctrlpolarity) & IPG_PC_RSVD_MASK, PHY_CTRL);
}
static u16 read_phy_bit(void __iomem *ioaddr, u8 phyctrlpolarity)
{
u16 bit_data;
ipg_write_phy_ctl(ioaddr, IPG_PC_MGMTCLK_LO | phyctrlpolarity);
bit_data = ((ipg_r8(PHY_CTRL) & IPG_PC_MGMTDATA) >> 1) & 1;
ipg_write_phy_ctl(ioaddr, IPG_PC_MGMTCLK_HI | phyctrlpolarity);
return bit_data;
}
/*
* Read a register from the Physical Layer device located
* on the IPG NIC, using the IPG PHYCTRL register.
*/
static int mdio_read(struct net_device *dev, int phy_id, int phy_reg)
{
void __iomem *ioaddr = ipg_ioaddr(dev);
/*
* The GMII mangement frame structure for a read is as follows:
*
* |Preamble|st|op|phyad|regad|ta| data |idle|
* |< 32 1s>|01|10|AAAAA|RRRRR|z0|DDDDDDDDDDDDDDDD|z |
*
* <32 1s> = 32 consecutive logic 1 values
* A = bit of Physical Layer device address (MSB first)
* R = bit of register address (MSB first)
* z = High impedance state
* D = bit of read data (MSB first)
*
* Transmission order is 'Preamble' field first, bits transmitted
* left to right (first to last).
*/
struct {
u32 field;
unsigned int len;
} p[] = {
{ GMII_PREAMBLE, 32 }, /* Preamble */
{ GMII_ST, 2 }, /* ST */
{ GMII_READ, 2 }, /* OP */
{ phy_id, 5 }, /* PHYAD */
{ phy_reg, 5 }, /* REGAD */
{ 0x0000, 2 }, /* TA */
{ 0x0000, 16 }, /* DATA */
{ 0x0000, 1 } /* IDLE */
};
unsigned int i, j;
u8 polarity, data;
polarity = ipg_r8(PHY_CTRL);
polarity &= (IPG_PC_DUPLEX_POLARITY | IPG_PC_LINK_POLARITY);
/* Create the Preamble, ST, OP, PHYAD, and REGAD field. */
for (j = 0; j < 5; j++) {
for (i = 0; i < p[j].len; i++) {
/* For each variable length field, the MSB must be
* transmitted first. Rotate through the field bits,
* starting with the MSB, and move each bit into the
* the 1st (2^1) bit position (this is the bit position
* corresponding to the MgmtData bit of the PhyCtrl
* register for the IPG).
*
* Example: ST = 01;
*
* First write a '0' to bit 1 of the PhyCtrl
* register, then write a '1' to bit 1 of the
* PhyCtrl register.
*
* To do this, right shift the MSB of ST by the value:
* [field length - 1 - #ST bits already written]
* then left shift this result by 1.
*/
data = (p[j].field >> (p[j].len - 1 - i)) << 1;
data &= IPG_PC_MGMTDATA;
data |= polarity | IPG_PC_MGMTDIR;
ipg_drive_phy_ctl_low_high(ioaddr, data);
}
}
send_three_state(ioaddr, polarity);
read_phy_bit(ioaddr, polarity);
/*
* For a read cycle, the bits for the next two fields (TA and
* DATA) are driven by the PHY (the IPG reads these bits).
*/
for (i = 0; i < p[6].len; i++) {
p[6].field |=
(read_phy_bit(ioaddr, polarity) << (p[6].len - 1 - i));
}
send_three_state(ioaddr, polarity);
send_three_state(ioaddr, polarity);
send_three_state(ioaddr, polarity);
send_end(ioaddr, polarity);
/* Return the value of the DATA field. */
return p[6].field;
}
/*
* Write to a register from the Physical Layer device located
* on the IPG NIC, using the IPG PHYCTRL register.
*/
static void mdio_write(struct net_device *dev, int phy_id, int phy_reg, int val)
{
void __iomem *ioaddr = ipg_ioaddr(dev);
/*
* The GMII mangement frame structure for a read is as follows:
*
* |Preamble|st|op|phyad|regad|ta| data |idle|
* |< 32 1s>|01|10|AAAAA|RRRRR|z0|DDDDDDDDDDDDDDDD|z |
*
* <32 1s> = 32 consecutive logic 1 values
* A = bit of Physical Layer device address (MSB first)
* R = bit of register address (MSB first)
* z = High impedance state
* D = bit of write data (MSB first)
*
* Transmission order is 'Preamble' field first, bits transmitted
* left to right (first to last).
*/
struct {
u32 field;
unsigned int len;
} p[] = {
{ GMII_PREAMBLE, 32 }, /* Preamble */
{ GMII_ST, 2 }, /* ST */
{ GMII_WRITE, 2 }, /* OP */
{ phy_id, 5 }, /* PHYAD */
{ phy_reg, 5 }, /* REGAD */
{ 0x0002, 2 }, /* TA */
{ val & 0xffff, 16 }, /* DATA */
{ 0x0000, 1 } /* IDLE */
};
unsigned int i, j;
u8 polarity, data;
polarity = ipg_r8(PHY_CTRL);
polarity &= (IPG_PC_DUPLEX_POLARITY | IPG_PC_LINK_POLARITY);
/* Create the Preamble, ST, OP, PHYAD, and REGAD field. */
for (j = 0; j < 7; j++) {
for (i = 0; i < p[j].len; i++) {
/* For each variable length field, the MSB must be
* transmitted first. Rotate through the field bits,
* starting with the MSB, and move each bit into the
* the 1st (2^1) bit position (this is the bit position
* corresponding to the MgmtData bit of the PhyCtrl
* register for the IPG).
*
* Example: ST = 01;
*
* First write a '0' to bit 1 of the PhyCtrl
* register, then write a '1' to bit 1 of the
* PhyCtrl register.
*
* To do this, right shift the MSB of ST by the value:
* [field length - 1 - #ST bits already written]
* then left shift this result by 1.
*/
data = (p[j].field >> (p[j].len - 1 - i)) << 1;
data &= IPG_PC_MGMTDATA;
data |= polarity | IPG_PC_MGMTDIR;
ipg_drive_phy_ctl_low_high(ioaddr, data);
}
}
/* The last cycle is a tri-state, so read from the PHY. */
for (j = 7; j < 8; j++) {
for (i = 0; i < p[j].len; i++) {
ipg_write_phy_ctl(ioaddr, IPG_PC_MGMTCLK_LO | polarity);
p[j].field |= ((ipg_r8(PHY_CTRL) &
IPG_PC_MGMTDATA) >> 1) << (p[j].len - 1 - i);
ipg_write_phy_ctl(ioaddr, IPG_PC_MGMTCLK_HI | polarity);
}
}
}
static void ipg_set_led_mode(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
u32 mode;
mode = ipg_r32(ASIC_CTRL);
mode &= ~(IPG_AC_LED_MODE_BIT_1 | IPG_AC_LED_MODE | IPG_AC_LED_SPEED);
if ((sp->led_mode & 0x03) > 1)
mode |= IPG_AC_LED_MODE_BIT_1; /* Write Asic Control Bit 29 */
if ((sp->led_mode & 0x01) == 1)
mode |= IPG_AC_LED_MODE; /* Write Asic Control Bit 14 */
if ((sp->led_mode & 0x08) == 8)
mode |= IPG_AC_LED_SPEED; /* Write Asic Control Bit 27 */
ipg_w32(mode, ASIC_CTRL);
}
static void ipg_set_phy_set(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
int physet;
physet = ipg_r8(PHY_SET);
physet &= ~(IPG_PS_MEM_LENB9B | IPG_PS_MEM_LEN9 | IPG_PS_NON_COMPDET);
physet |= ((sp->led_mode & 0x70) >> 4);
ipg_w8(physet, PHY_SET);
}
static int ipg_reset(struct net_device *dev, u32 resetflags)
{
/* Assert functional resets via the IPG AsicCtrl
* register as specified by the 'resetflags' input
* parameter.
*/
void __iomem *ioaddr = ipg_ioaddr(dev);
unsigned int timeout_count = 0;
IPG_DEBUG_MSG("_reset\n");
ipg_w32(ipg_r32(ASIC_CTRL) | resetflags, ASIC_CTRL);
/* Delay added to account for problem with 10Mbps reset. */
mdelay(IPG_AC_RESETWAIT);
while (IPG_AC_RESET_BUSY & ipg_r32(ASIC_CTRL)) {
mdelay(IPG_AC_RESETWAIT);
if (++timeout_count > IPG_AC_RESET_TIMEOUT)
return -ETIME;
}
/* Set LED Mode in Asic Control */
ipg_set_led_mode(dev);
/* Set PHYSet Register Value */
ipg_set_phy_set(dev);
return 0;
}
/* Find the GMII PHY address. */
static int ipg_find_phyaddr(struct net_device *dev)
{
unsigned int phyaddr, i;
for (i = 0; i < 32; i++) {
u32 status;
/* Search for the correct PHY address among 32 possible. */
phyaddr = (IPG_NIC_PHY_ADDRESS + i) % 32;
/* 10/22/03 Grace change verify from GMII_PHY_STATUS to
GMII_PHY_ID1
*/
status = mdio_read(dev, phyaddr, MII_BMSR);
if ((status != 0xFFFF) && (status != 0))
return phyaddr;
}
return 0x1f;
}
/*
* Configure IPG based on result of IEEE 802.3 PHY
* auto-negotiation.
*/
static int ipg_config_autoneg(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
unsigned int txflowcontrol;
unsigned int rxflowcontrol;
unsigned int fullduplex;
u32 mac_ctrl_val;
u32 asicctrl;
u8 phyctrl;
IPG_DEBUG_MSG("_config_autoneg\n");
asicctrl = ipg_r32(ASIC_CTRL);
phyctrl = ipg_r8(PHY_CTRL);
mac_ctrl_val = ipg_r32(MAC_CTRL);
/* Set flags for use in resolving auto-negotiation, assuming
* non-1000Mbps, half duplex, no flow control.
*/
fullduplex = 0;
txflowcontrol = 0;
rxflowcontrol = 0;
/* To accommodate a problem in 10Mbps operation,
* set a global flag if PHY running in 10Mbps mode.
*/
sp->tenmbpsmode = 0;
printk(KERN_INFO "%s: Link speed = ", dev->name);
/* Determine actual speed of operation. */
switch (phyctrl & IPG_PC_LINK_SPEED) {
case IPG_PC_LINK_SPEED_10MBPS:
printk("10Mbps.\n");
printk(KERN_INFO "%s: 10Mbps operational mode enabled.\n",
dev->name);
sp->tenmbpsmode = 1;
break;
case IPG_PC_LINK_SPEED_100MBPS:
printk("100Mbps.\n");
break;
case IPG_PC_LINK_SPEED_1000MBPS:
printk("1000Mbps.\n");
break;
default:
printk("undefined!\n");
return 0;
}
if (phyctrl & IPG_PC_DUPLEX_STATUS) {
fullduplex = 1;
txflowcontrol = 1;
rxflowcontrol = 1;
}
/* Configure full duplex, and flow control. */
if (fullduplex == 1) {
/* Configure IPG for full duplex operation. */
printk(KERN_INFO "%s: setting full duplex, ", dev->name);
mac_ctrl_val |= IPG_MC_DUPLEX_SELECT_FD;
if (txflowcontrol == 1) {
printk("TX flow control");
mac_ctrl_val |= IPG_MC_TX_FLOW_CONTROL_ENABLE;
} else {
printk("no TX flow control");
mac_ctrl_val &= ~IPG_MC_TX_FLOW_CONTROL_ENABLE;
}
if (rxflowcontrol == 1) {
printk(", RX flow control.");
mac_ctrl_val |= IPG_MC_RX_FLOW_CONTROL_ENABLE;
} else {
printk(", no RX flow control.");
mac_ctrl_val &= ~IPG_MC_RX_FLOW_CONTROL_ENABLE;
}
printk("\n");
} else {
/* Configure IPG for half duplex operation. */
printk(KERN_INFO "%s: setting half duplex, "
"no TX flow control, no RX flow control.\n", dev->name);
mac_ctrl_val &= ~IPG_MC_DUPLEX_SELECT_FD &
~IPG_MC_TX_FLOW_CONTROL_ENABLE &
~IPG_MC_RX_FLOW_CONTROL_ENABLE;
}
ipg_w32(mac_ctrl_val, MAC_CTRL);
return 0;
}
/* Determine and configure multicast operation and set
* receive mode for IPG.
*/
static void ipg_nic_set_multicast_list(struct net_device *dev)
{
void __iomem *ioaddr = ipg_ioaddr(dev);
struct netdev_hw_addr *ha;
unsigned int hashindex;
u32 hashtable[2];
u8 receivemode;
IPG_DEBUG_MSG("_nic_set_multicast_list\n");
receivemode = IPG_RM_RECEIVEUNICAST | IPG_RM_RECEIVEBROADCAST;
if (dev->flags & IFF_PROMISC) {
/* NIC to be configured in promiscuous mode. */
receivemode = IPG_RM_RECEIVEALLFRAMES;
} else if ((dev->flags & IFF_ALLMULTI) ||
((dev->flags & IFF_MULTICAST) &&
(netdev_mc_count(dev) > IPG_MULTICAST_HASHTABLE_SIZE))) {
/* NIC to be configured to receive all multicast
* frames. */
receivemode |= IPG_RM_RECEIVEMULTICAST;
} else if ((dev->flags & IFF_MULTICAST) && !netdev_mc_empty(dev)) {
/* NIC to be configured to receive selected
* multicast addresses. */
receivemode |= IPG_RM_RECEIVEMULTICASTHASH;
}
/* Calculate the bits to set for the 64 bit, IPG HASHTABLE.
* The IPG applies a cyclic-redundancy-check (the same CRC
* used to calculate the frame data FCS) to the destination
* address all incoming multicast frames whose destination
* address has the multicast bit set. The least significant
* 6 bits of the CRC result are used as an addressing index
* into the hash table. If the value of the bit addressed by
* this index is a 1, the frame is passed to the host system.
*/
/* Clear hashtable. */
hashtable[0] = 0x00000000;
hashtable[1] = 0x00000000;
/* Cycle through all multicast addresses to filter. */
netdev_for_each_mc_addr(ha, dev) {
/* Calculate CRC result for each multicast address. */
hashindex = crc32_le(0xffffffff, ha->addr,
ETH_ALEN);
/* Use only the least significant 6 bits. */
hashindex = hashindex & 0x3F;
/* Within "hashtable", set bit number "hashindex"
* to a logic 1.
*/
set_bit(hashindex, (void *)hashtable);
}
/* Write the value of the hashtable, to the 4, 16 bit
* HASHTABLE IPG registers.
*/
ipg_w32(hashtable[0], HASHTABLE_0);
ipg_w32(hashtable[1], HASHTABLE_1);
ipg_w8(IPG_RM_RSVD_MASK & receivemode, RECEIVE_MODE);
IPG_DEBUG_MSG("ReceiveMode = %x\n", ipg_r8(RECEIVE_MODE));
}
static int ipg_io_config(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = ipg_ioaddr(dev);
u32 origmacctrl;
u32 restoremacctrl;
IPG_DEBUG_MSG("_io_config\n");
origmacctrl = ipg_r32(MAC_CTRL);
restoremacctrl = origmacctrl | IPG_MC_STATISTICS_ENABLE;
/* Based on compilation option, determine if FCS is to be
* stripped on receive frames by IPG.
*/
if (!IPG_STRIP_FCS_ON_RX)
restoremacctrl |= IPG_MC_RCV_FCS;
/* Determine if transmitter and/or receiver are
* enabled so we may restore MACCTRL correctly.
*/
if (origmacctrl & IPG_MC_TX_ENABLED)
restoremacctrl |= IPG_MC_TX_ENABLE;
if (origmacctrl & IPG_MC_RX_ENABLED)
restoremacctrl |= IPG_MC_RX_ENABLE;
/* Transmitter and receiver must be disabled before setting
* IFSSelect.
*/
ipg_w32((origmacctrl & (IPG_MC_RX_DISABLE | IPG_MC_TX_DISABLE)) &
IPG_MC_RSVD_MASK, MAC_CTRL);
/* Now that transmitter and receiver are disabled, write
* to IFSSelect.
*/
ipg_w32((origmacctrl & IPG_MC_IFS_96BIT) & IPG_MC_RSVD_MASK, MAC_CTRL);
/* Set RECEIVEMODE register. */
ipg_nic_set_multicast_list(dev);
ipg_w16(sp->max_rxframe_size, MAX_FRAME_SIZE);
ipg_w8(IPG_RXDMAPOLLPERIOD_VALUE, RX_DMA_POLL_PERIOD);
ipg_w8(IPG_RXDMAURGENTTHRESH_VALUE, RX_DMA_URGENT_THRESH);
ipg_w8(IPG_RXDMABURSTTHRESH_VALUE, RX_DMA_BURST_THRESH);
ipg_w8(IPG_TXDMAPOLLPERIOD_VALUE, TX_DMA_POLL_PERIOD);
ipg_w8(IPG_TXDMAURGENTTHRESH_VALUE, TX_DMA_URGENT_THRESH);
ipg_w8(IPG_TXDMABURSTTHRESH_VALUE, TX_DMA_BURST_THRESH);
ipg_w16((IPG_IE_HOST_ERROR | IPG_IE_TX_DMA_COMPLETE |
IPG_IE_TX_COMPLETE | IPG_IE_INT_REQUESTED |
IPG_IE_UPDATE_STATS | IPG_IE_LINK_EVENT |
IPG_IE_RX_DMA_COMPLETE | IPG_IE_RX_DMA_PRIORITY), INT_ENABLE);
ipg_w16(IPG_FLOWONTHRESH_VALUE, FLOW_ON_THRESH);
ipg_w16(IPG_FLOWOFFTHRESH_VALUE, FLOW_OFF_THRESH);
/* IPG multi-frag frame bug workaround.
* Per silicon revision B3 eratta.
*/
ipg_w16(ipg_r16(DEBUG_CTRL) | 0x0200, DEBUG_CTRL);
/* IPG TX poll now bug workaround.
* Per silicon revision B3 eratta.
*/
ipg_w16(ipg_r16(DEBUG_CTRL) | 0x0010, DEBUG_CTRL);
/* IPG RX poll now bug workaround.
* Per silicon revision B3 eratta.
*/
ipg_w16(ipg_r16(DEBUG_CTRL) | 0x0020, DEBUG_CTRL);
/* Now restore MACCTRL to original setting. */
ipg_w32(IPG_MC_RSVD_MASK & restoremacctrl, MAC_CTRL);
/* Disable unused RMON statistics. */
ipg_w32(IPG_RZ_ALL, RMON_STATISTICS_MASK);
/* Disable unused MIB statistics. */
ipg_w32(IPG_SM_MACCONTROLFRAMESXMTD | IPG_SM_MACCONTROLFRAMESRCVD |
IPG_SM_BCSTOCTETXMTOK_BCSTFRAMESXMTDOK | IPG_SM_TXJUMBOFRAMES |
IPG_SM_MCSTOCTETXMTOK_MCSTFRAMESXMTDOK | IPG_SM_RXJUMBOFRAMES |
IPG_SM_BCSTOCTETRCVDOK_BCSTFRAMESRCVDOK |
IPG_SM_UDPCHECKSUMERRORS | IPG_SM_TCPCHECKSUMERRORS |
IPG_SM_IPCHECKSUMERRORS, STATISTICS_MASK);
return 0;
}
/*
* Create a receive buffer within system memory and update
* NIC private structure appropriately.
*/
static int ipg_get_rxbuff(struct net_device *dev, int entry)
{
struct ipg_nic_private *sp = netdev_priv(dev);
struct ipg_rx *rxfd = sp->rxd + entry;
struct sk_buff *skb;
u64 rxfragsize;
IPG_DEBUG_MSG("_get_rxbuff\n");
skb = netdev_alloc_skb_ip_align(dev, sp->rxsupport_size);
if (!skb) {
sp->rx_buff[entry] = NULL;
return -ENOMEM;
}
/* Associate the receive buffer with the IPG NIC. */
skb->dev = dev;
/* Save the address of the sk_buff structure. */
sp->rx_buff[entry] = skb;
rxfd->frag_info = cpu_to_le64(pci_map_single(sp->pdev, skb->data,
sp->rx_buf_sz, PCI_DMA_FROMDEVICE));
/* Set the RFD fragment length. */
rxfragsize = sp->rxfrag_size;
rxfd->frag_info |= cpu_to_le64((rxfragsize << 48) & IPG_RFI_FRAGLEN);
return 0;
}
static int init_rfdlist(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
unsigned int i;
IPG_DEBUG_MSG("_init_rfdlist\n");
for (i = 0; i < IPG_RFDLIST_LENGTH; i++) {
struct ipg_rx *rxfd = sp->rxd + i;
if (sp->rx_buff[i]) {
pci_unmap_single(sp->pdev,
le64_to_cpu(rxfd->frag_info) & ~IPG_RFI_FRAGLEN,
sp->rx_buf_sz, PCI_DMA_FROMDEVICE);
dev_kfree_skb_irq(sp->rx_buff[i]);
sp->rx_buff[i] = NULL;
}
/* Clear out the RFS field. */
rxfd->rfs = 0x0000000000000000;
if (ipg_get_rxbuff(dev, i) < 0) {
/*
* A receive buffer was not ready, break the
* RFD list here.
*/
IPG_DEBUG_MSG("Cannot allocate Rx buffer.\n");
/* Just in case we cannot allocate a single RFD.
* Should not occur.
*/
if (i == 0) {
printk(KERN_ERR "%s: No memory available"
" for RFD list.\n", dev->name);
return -ENOMEM;
}
}
rxfd->next_desc = cpu_to_le64(sp->rxd_map +
sizeof(struct ipg_rx)*(i + 1));
}
sp->rxd[i - 1].next_desc = cpu_to_le64(sp->rxd_map);
sp->rx_current = 0;
sp->rx_dirty = 0;
/* Write the location of the RFDList to the IPG. */
ipg_w32((u32) sp->rxd_map, RFD_LIST_PTR_0);
ipg_w32(0x00000000, RFD_LIST_PTR_1);
return 0;
}
static void init_tfdlist(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
unsigned int i;
IPG_DEBUG_MSG("_init_tfdlist\n");
for (i = 0; i < IPG_TFDLIST_LENGTH; i++) {
struct ipg_tx *txfd = sp->txd + i;
txfd->tfc = cpu_to_le64(IPG_TFC_TFDDONE);
if (sp->tx_buff[i]) {
dev_kfree_skb_irq(sp->tx_buff[i]);
sp->tx_buff[i] = NULL;
}
txfd->next_desc = cpu_to_le64(sp->txd_map +
sizeof(struct ipg_tx)*(i + 1));
}
sp->txd[i - 1].next_desc = cpu_to_le64(sp->txd_map);
sp->tx_current = 0;
sp->tx_dirty = 0;
/* Write the location of the TFDList to the IPG. */
IPG_DDEBUG_MSG("Starting TFDListPtr = %8.8x\n",
(u32) sp->txd_map);
ipg_w32((u32) sp->txd_map, TFD_LIST_PTR_0);
ipg_w32(0x00000000, TFD_LIST_PTR_1);
sp->reset_current_tfd = 1;
}
/*
* Free all transmit buffers which have already been transferred
* via DMA to the IPG.
*/
static void ipg_nic_txfree(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
unsigned int released, pending, dirty;
IPG_DEBUG_MSG("_nic_txfree\n");
pending = sp->tx_current - sp->tx_dirty;
dirty = sp->tx_dirty % IPG_TFDLIST_LENGTH;
for (released = 0; released < pending; released++) {
struct sk_buff *skb = sp->tx_buff[dirty];
struct ipg_tx *txfd = sp->txd + dirty;
IPG_DEBUG_MSG("TFC = %16.16lx\n", (unsigned long) txfd->tfc);
/* Look at each TFD's TFC field beginning
* at the last freed TFD up to the current TFD.
* If the TFDDone bit is set, free the associated
* buffer.
*/
if (!(txfd->tfc & cpu_to_le64(IPG_TFC_TFDDONE)))
break;
/* Free the transmit buffer. */
if (skb) {
pci_unmap_single(sp->pdev,
le64_to_cpu(txfd->frag_info) & ~IPG_TFI_FRAGLEN,
skb->len, PCI_DMA_TODEVICE);
dev_kfree_skb_irq(skb);
sp->tx_buff[dirty] = NULL;
}
dirty = (dirty + 1) % IPG_TFDLIST_LENGTH;
}
sp->tx_dirty += released;
if (netif_queue_stopped(dev) &&
(sp->tx_current != (sp->tx_dirty + IPG_TFDLIST_LENGTH))) {
netif_wake_queue(dev);
}
}
static void ipg_tx_timeout(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
ipg_reset(dev, IPG_AC_TX_RESET | IPG_AC_DMA | IPG_AC_NETWORK |
IPG_AC_FIFO);
spin_lock_irq(&sp->lock);
/* Re-configure after DMA reset. */
if (ipg_io_config(dev) < 0) {
printk(KERN_INFO "%s: Error during re-configuration.\n",
dev->name);
}
init_tfdlist(dev);
spin_unlock_irq(&sp->lock);
ipg_w32((ipg_r32(MAC_CTRL) | IPG_MC_TX_ENABLE) & IPG_MC_RSVD_MASK,
MAC_CTRL);
}
/*
* For TxComplete interrupts, free all transmit
* buffers which have already been transferred via DMA
* to the IPG.
*/
static void ipg_nic_txcleanup(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
unsigned int i;
IPG_DEBUG_MSG("_nic_txcleanup\n");
for (i = 0; i < IPG_TFDLIST_LENGTH; i++) {
/* Reading the TXSTATUS register clears the
* TX_COMPLETE interrupt.
*/
u32 txstatusdword = ipg_r32(TX_STATUS);
IPG_DEBUG_MSG("TxStatus = %8.8x\n", txstatusdword);
/* Check for Transmit errors. Error bits only valid if
* TX_COMPLETE bit in the TXSTATUS register is a 1.
*/
if (!(txstatusdword & IPG_TS_TX_COMPLETE))
break;
/* If in 10Mbps mode, indicate transmit is ready. */
if (sp->tenmbpsmode) {
netif_wake_queue(dev);
}
/* Transmit error, increment stat counters. */
if (txstatusdword & IPG_TS_TX_ERROR) {
IPG_DEBUG_MSG("Transmit error.\n");
sp->stats.tx_errors++;
}
/* Late collision, re-enable transmitter. */
if (txstatusdword & IPG_TS_LATE_COLLISION) {
IPG_DEBUG_MSG("Late collision on transmit.\n");
ipg_w32((ipg_r32(MAC_CTRL) | IPG_MC_TX_ENABLE) &
IPG_MC_RSVD_MASK, MAC_CTRL);
}
/* Maximum collisions, re-enable transmitter. */
if (txstatusdword & IPG_TS_TX_MAX_COLL) {
IPG_DEBUG_MSG("Maximum collisions on transmit.\n");
ipg_w32((ipg_r32(MAC_CTRL) | IPG_MC_TX_ENABLE) &
IPG_MC_RSVD_MASK, MAC_CTRL);
}
/* Transmit underrun, reset and re-enable
* transmitter.
*/
if (txstatusdword & IPG_TS_TX_UNDERRUN) {
IPG_DEBUG_MSG("Transmitter underrun.\n");
sp->stats.tx_fifo_errors++;
ipg_reset(dev, IPG_AC_TX_RESET | IPG_AC_DMA |
IPG_AC_NETWORK | IPG_AC_FIFO);
/* Re-configure after DMA reset. */
if (ipg_io_config(dev) < 0) {
printk(KERN_INFO
"%s: Error during re-configuration.\n",
dev->name);
}
init_tfdlist(dev);
ipg_w32((ipg_r32(MAC_CTRL) | IPG_MC_TX_ENABLE) &
IPG_MC_RSVD_MASK, MAC_CTRL);
}
}
ipg_nic_txfree(dev);
}
/* Provides statistical information about the IPG NIC. */
static struct net_device_stats *ipg_nic_get_stats(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
u16 temp1;
u16 temp2;
IPG_DEBUG_MSG("_nic_get_stats\n");
/* Check to see if the NIC has been initialized via nic_open,
* before trying to read statistic registers.
*/
if (!test_bit(__LINK_STATE_START, &dev->state))
return &sp->stats;
sp->stats.rx_packets += ipg_r32(IPG_FRAMESRCVDOK);
sp->stats.tx_packets += ipg_r32(IPG_FRAMESXMTDOK);
sp->stats.rx_bytes += ipg_r32(IPG_OCTETRCVOK);
sp->stats.tx_bytes += ipg_r32(IPG_OCTETXMTOK);
temp1 = ipg_r16(IPG_FRAMESLOSTRXERRORS);
sp->stats.rx_errors += temp1;
sp->stats.rx_missed_errors += temp1;
temp1 = ipg_r32(IPG_SINGLECOLFRAMES) + ipg_r32(IPG_MULTICOLFRAMES) +
ipg_r32(IPG_LATECOLLISIONS);
temp2 = ipg_r16(IPG_CARRIERSENSEERRORS);
sp->stats.collisions += temp1;
sp->stats.tx_dropped += ipg_r16(IPG_FRAMESABORTXSCOLLS);
sp->stats.tx_errors += ipg_r16(IPG_FRAMESWEXDEFERRAL) +
ipg_r32(IPG_FRAMESWDEFERREDXMT) + temp1 + temp2;
sp->stats.multicast += ipg_r32(IPG_MCSTOCTETRCVDOK);
/* detailed tx_errors */
sp->stats.tx_carrier_errors += temp2;
/* detailed rx_errors */
sp->stats.rx_length_errors += ipg_r16(IPG_INRANGELENGTHERRORS) +
ipg_r16(IPG_FRAMETOOLONGERRRORS);
sp->stats.rx_crc_errors += ipg_r16(IPG_FRAMECHECKSEQERRORS);
/* Unutilized IPG statistic registers. */
ipg_r32(IPG_MCSTFRAMESRCVDOK);
return &sp->stats;
}
/* Restore used receive buffers. */
static int ipg_nic_rxrestore(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
const unsigned int curr = sp->rx_current;
unsigned int dirty = sp->rx_dirty;
IPG_DEBUG_MSG("_nic_rxrestore\n");
for (dirty = sp->rx_dirty; curr - dirty > 0; dirty++) {
unsigned int entry = dirty % IPG_RFDLIST_LENGTH;
/* rx_copybreak may poke hole here and there. */
if (sp->rx_buff[entry])
continue;
/* Generate a new receive buffer to replace the
* current buffer (which will be released by the
* Linux system).
*/
if (ipg_get_rxbuff(dev, entry) < 0) {
IPG_DEBUG_MSG("Cannot allocate new Rx buffer.\n");
break;
}
/* Reset the RFS field. */
sp->rxd[entry].rfs = 0x0000000000000000;
}
sp->rx_dirty = dirty;
return 0;
}
/* use jumboindex and jumbosize to control jumbo frame status
* initial status is jumboindex=-1 and jumbosize=0
* 1. jumboindex = -1 and jumbosize=0 : previous jumbo frame has been done.
* 2. jumboindex != -1 and jumbosize != 0 : jumbo frame is not over size and receiving
* 3. jumboindex = -1 and jumbosize != 0 : jumbo frame is over size, already dump
* previous receiving and need to continue dumping the current one
*/
enum {
NORMAL_PACKET,
ERROR_PACKET
};
enum {
FRAME_NO_START_NO_END = 0,
FRAME_WITH_START = 1,
FRAME_WITH_END = 10,
FRAME_WITH_START_WITH_END = 11
};
static void ipg_nic_rx_free_skb(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
unsigned int entry = sp->rx_current % IPG_RFDLIST_LENGTH;
if (sp->rx_buff[entry]) {
struct ipg_rx *rxfd = sp->rxd + entry;
pci_unmap_single(sp->pdev,
le64_to_cpu(rxfd->frag_info) & ~IPG_RFI_FRAGLEN,
sp->rx_buf_sz, PCI_DMA_FROMDEVICE);
dev_kfree_skb_irq(sp->rx_buff[entry]);
sp->rx_buff[entry] = NULL;
}
}
static int ipg_nic_rx_check_frame_type(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
struct ipg_rx *rxfd = sp->rxd + (sp->rx_current % IPG_RFDLIST_LENGTH);
int type = FRAME_NO_START_NO_END;
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_FRAMESTART)
type += FRAME_WITH_START;
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_FRAMEEND)
type += FRAME_WITH_END;
return type;
}
static int ipg_nic_rx_check_error(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
unsigned int entry = sp->rx_current % IPG_RFDLIST_LENGTH;
struct ipg_rx *rxfd = sp->rxd + entry;
if (IPG_DROP_ON_RX_ETH_ERRORS && (le64_to_cpu(rxfd->rfs) &
(IPG_RFS_RXFIFOOVERRUN | IPG_RFS_RXRUNTFRAME |
IPG_RFS_RXALIGNMENTERROR | IPG_RFS_RXFCSERROR |
IPG_RFS_RXOVERSIZEDFRAME | IPG_RFS_RXLENGTHERROR))) {
IPG_DEBUG_MSG("Rx error, RFS = %16.16lx\n",
(unsigned long) rxfd->rfs);
/* Increment general receive error statistic. */
sp->stats.rx_errors++;
/* Increment detailed receive error statistics. */
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_RXFIFOOVERRUN) {
IPG_DEBUG_MSG("RX FIFO overrun occurred.\n");
sp->stats.rx_fifo_errors++;
}
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_RXRUNTFRAME) {
IPG_DEBUG_MSG("RX runt occurred.\n");
sp->stats.rx_length_errors++;
}
/* Do nothing for IPG_RFS_RXOVERSIZEDFRAME,
* error count handled by a IPG statistic register.
*/
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_RXALIGNMENTERROR) {
IPG_DEBUG_MSG("RX alignment error occurred.\n");
sp->stats.rx_frame_errors++;
}
/* Do nothing for IPG_RFS_RXFCSERROR, error count
* handled by a IPG statistic register.
*/
/* Free the memory associated with the RX
* buffer since it is erroneous and we will
* not pass it to higher layer processes.
*/
if (sp->rx_buff[entry]) {
pci_unmap_single(sp->pdev,
le64_to_cpu(rxfd->frag_info) & ~IPG_RFI_FRAGLEN,
sp->rx_buf_sz, PCI_DMA_FROMDEVICE);
dev_kfree_skb_irq(sp->rx_buff[entry]);
sp->rx_buff[entry] = NULL;
}
return ERROR_PACKET;
}
return NORMAL_PACKET;
}
static void ipg_nic_rx_with_start_and_end(struct net_device *dev,
struct ipg_nic_private *sp,
struct ipg_rx *rxfd, unsigned entry)
{
struct ipg_jumbo *jumbo = &sp->jumbo;
struct sk_buff *skb;
int framelen;
if (jumbo->found_start) {
dev_kfree_skb_irq(jumbo->skb);
jumbo->found_start = 0;
jumbo->current_size = 0;
jumbo->skb = NULL;
}
/* 1: found error, 0 no error */
if (ipg_nic_rx_check_error(dev) != NORMAL_PACKET)
return;
skb = sp->rx_buff[entry];
if (!skb)
return;
/* accept this frame and send to upper layer */
framelen = le64_to_cpu(rxfd->rfs) & IPG_RFS_RXFRAMELEN;
if (framelen > sp->rxfrag_size)
framelen = sp->rxfrag_size;
skb_put(skb, framelen);
skb->protocol = eth_type_trans(skb, dev);
skb_checksum_none_assert(skb);
netif_rx(skb);
sp->rx_buff[entry] = NULL;
}
static void ipg_nic_rx_with_start(struct net_device *dev,
struct ipg_nic_private *sp,
struct ipg_rx *rxfd, unsigned entry)
{
struct ipg_jumbo *jumbo = &sp->jumbo;
struct pci_dev *pdev = sp->pdev;
struct sk_buff *skb;
/* 1: found error, 0 no error */
if (ipg_nic_rx_check_error(dev) != NORMAL_PACKET)
return;
/* accept this frame and send to upper layer */
skb = sp->rx_buff[entry];
if (!skb)
return;
if (jumbo->found_start)
dev_kfree_skb_irq(jumbo->skb);
pci_unmap_single(pdev, le64_to_cpu(rxfd->frag_info) & ~IPG_RFI_FRAGLEN,
sp->rx_buf_sz, PCI_DMA_FROMDEVICE);
skb_put(skb, sp->rxfrag_size);
jumbo->found_start = 1;
jumbo->current_size = sp->rxfrag_size;
jumbo->skb = skb;
sp->rx_buff[entry] = NULL;
}
static void ipg_nic_rx_with_end(struct net_device *dev,
struct ipg_nic_private *sp,
struct ipg_rx *rxfd, unsigned entry)
{
struct ipg_jumbo *jumbo = &sp->jumbo;
/* 1: found error, 0 no error */
if (ipg_nic_rx_check_error(dev) == NORMAL_PACKET) {
struct sk_buff *skb = sp->rx_buff[entry];
if (!skb)
return;
if (jumbo->found_start) {
int framelen, endframelen;
framelen = le64_to_cpu(rxfd->rfs) & IPG_RFS_RXFRAMELEN;
endframelen = framelen - jumbo->current_size;
if (framelen > sp->rxsupport_size)
dev_kfree_skb_irq(jumbo->skb);
else {
memcpy(skb_put(jumbo->skb, endframelen),
skb->data, endframelen);
jumbo->skb->protocol =
eth_type_trans(jumbo->skb, dev);
skb_checksum_none_assert(jumbo->skb);
netif_rx(jumbo->skb);
}
}
jumbo->found_start = 0;
jumbo->current_size = 0;
jumbo->skb = NULL;
ipg_nic_rx_free_skb(dev);
} else {
dev_kfree_skb_irq(jumbo->skb);
jumbo->found_start = 0;
jumbo->current_size = 0;
jumbo->skb = NULL;
}
}
static void ipg_nic_rx_no_start_no_end(struct net_device *dev,
struct ipg_nic_private *sp,
struct ipg_rx *rxfd, unsigned entry)
{
struct ipg_jumbo *jumbo = &sp->jumbo;
/* 1: found error, 0 no error */
if (ipg_nic_rx_check_error(dev) == NORMAL_PACKET) {
struct sk_buff *skb = sp->rx_buff[entry];
if (skb) {
if (jumbo->found_start) {
jumbo->current_size += sp->rxfrag_size;
if (jumbo->current_size <= sp->rxsupport_size) {
memcpy(skb_put(jumbo->skb,
sp->rxfrag_size),
skb->data, sp->rxfrag_size);
}
}
ipg_nic_rx_free_skb(dev);
}
} else {
dev_kfree_skb_irq(jumbo->skb);
jumbo->found_start = 0;
jumbo->current_size = 0;
jumbo->skb = NULL;
}
}
static int ipg_nic_rx_jumbo(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
unsigned int curr = sp->rx_current;
void __iomem *ioaddr = sp->ioaddr;
unsigned int i;
IPG_DEBUG_MSG("_nic_rx\n");
for (i = 0; i < IPG_MAXRFDPROCESS_COUNT; i++, curr++) {
unsigned int entry = curr % IPG_RFDLIST_LENGTH;
struct ipg_rx *rxfd = sp->rxd + entry;
if (!(rxfd->rfs & cpu_to_le64(IPG_RFS_RFDDONE)))
break;
switch (ipg_nic_rx_check_frame_type(dev)) {
case FRAME_WITH_START_WITH_END:
ipg_nic_rx_with_start_and_end(dev, sp, rxfd, entry);
break;
case FRAME_WITH_START:
ipg_nic_rx_with_start(dev, sp, rxfd, entry);
break;
case FRAME_WITH_END:
ipg_nic_rx_with_end(dev, sp, rxfd, entry);
break;
case FRAME_NO_START_NO_END:
ipg_nic_rx_no_start_no_end(dev, sp, rxfd, entry);
break;
}
}
sp->rx_current = curr;
if (i == IPG_MAXRFDPROCESS_COUNT) {
/* There are more RFDs to process, however the
* allocated amount of RFD processing time has
* expired. Assert Interrupt Requested to make
* sure we come back to process the remaining RFDs.
*/
ipg_w32(ipg_r32(ASIC_CTRL) | IPG_AC_INT_REQUEST, ASIC_CTRL);
}
ipg_nic_rxrestore(dev);
return 0;
}
static int ipg_nic_rx(struct net_device *dev)
{
/* Transfer received Ethernet frames to higher network layers. */
struct ipg_nic_private *sp = netdev_priv(dev);
unsigned int curr = sp->rx_current;
void __iomem *ioaddr = sp->ioaddr;
struct ipg_rx *rxfd;
unsigned int i;
IPG_DEBUG_MSG("_nic_rx\n");
#define __RFS_MASK \
cpu_to_le64(IPG_RFS_RFDDONE | IPG_RFS_FRAMESTART | IPG_RFS_FRAMEEND)
for (i = 0; i < IPG_MAXRFDPROCESS_COUNT; i++, curr++) {
unsigned int entry = curr % IPG_RFDLIST_LENGTH;
struct sk_buff *skb = sp->rx_buff[entry];
unsigned int framelen;
rxfd = sp->rxd + entry;
if (((rxfd->rfs & __RFS_MASK) != __RFS_MASK) || !skb)
break;
/* Get received frame length. */
framelen = le64_to_cpu(rxfd->rfs) & IPG_RFS_RXFRAMELEN;
/* Check for jumbo frame arrival with too small
* RXFRAG_SIZE.
*/
if (framelen > sp->rxfrag_size) {
IPG_DEBUG_MSG
("RFS FrameLen > allocated fragment size.\n");
framelen = sp->rxfrag_size;
}
if ((IPG_DROP_ON_RX_ETH_ERRORS && (le64_to_cpu(rxfd->rfs) &
(IPG_RFS_RXFIFOOVERRUN | IPG_RFS_RXRUNTFRAME |
IPG_RFS_RXALIGNMENTERROR | IPG_RFS_RXFCSERROR |
IPG_RFS_RXOVERSIZEDFRAME | IPG_RFS_RXLENGTHERROR)))) {
IPG_DEBUG_MSG("Rx error, RFS = %16.16lx\n",
(unsigned long int) rxfd->rfs);
/* Increment general receive error statistic. */
sp->stats.rx_errors++;
/* Increment detailed receive error statistics. */
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_RXFIFOOVERRUN) {
IPG_DEBUG_MSG("RX FIFO overrun occurred.\n");
sp->stats.rx_fifo_errors++;
}
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_RXRUNTFRAME) {
IPG_DEBUG_MSG("RX runt occurred.\n");
sp->stats.rx_length_errors++;
}
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_RXOVERSIZEDFRAME) ;
/* Do nothing, error count handled by a IPG
* statistic register.
*/
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_RXALIGNMENTERROR) {
IPG_DEBUG_MSG("RX alignment error occurred.\n");
sp->stats.rx_frame_errors++;
}
if (le64_to_cpu(rxfd->rfs) & IPG_RFS_RXFCSERROR) ;
/* Do nothing, error count handled by a IPG
* statistic register.
*/
/* Free the memory associated with the RX
* buffer since it is erroneous and we will
* not pass it to higher layer processes.
*/
if (skb) {
__le64 info = rxfd->frag_info;
pci_unmap_single(sp->pdev,
le64_to_cpu(info) & ~IPG_RFI_FRAGLEN,
sp->rx_buf_sz, PCI_DMA_FROMDEVICE);
dev_kfree_skb_irq(skb);
}
} else {
/* Adjust the new buffer length to accommodate the size
* of the received frame.
*/
skb_put(skb, framelen);
/* Set the buffer's protocol field to Ethernet. */
skb->protocol = eth_type_trans(skb, dev);
/* The IPG encountered an error with (or
* there were no) IP/TCP/UDP checksums.
* This may or may not indicate an invalid
* IP/TCP/UDP frame was received. Let the
* upper layer decide.
*/
skb_checksum_none_assert(skb);
/* Hand off frame for higher layer processing.
* The function netif_rx() releases the sk_buff
* when processing completes.
*/
netif_rx(skb);
}
/* Assure RX buffer is not reused by IPG. */
sp->rx_buff[entry] = NULL;
}
/*
* If there are more RFDs to process and the allocated amount of RFD
* processing time has expired, assert Interrupt Requested to make
* sure we come back to process the remaining RFDs.
*/
if (i == IPG_MAXRFDPROCESS_COUNT)
ipg_w32(ipg_r32(ASIC_CTRL) | IPG_AC_INT_REQUEST, ASIC_CTRL);
#ifdef IPG_DEBUG
/* Check if the RFD list contained no receive frame data. */
if (!i)
sp->EmptyRFDListCount++;
#endif
while ((le64_to_cpu(rxfd->rfs) & IPG_RFS_RFDDONE) &&
!((le64_to_cpu(rxfd->rfs) & IPG_RFS_FRAMESTART) &&
(le64_to_cpu(rxfd->rfs) & IPG_RFS_FRAMEEND))) {
unsigned int entry = curr++ % IPG_RFDLIST_LENGTH;
rxfd = sp->rxd + entry;
IPG_DEBUG_MSG("Frame requires multiple RFDs.\n");
/* An unexpected event, additional code needed to handle
* properly. So for the time being, just disregard the
* frame.
*/
/* Free the memory associated with the RX
* buffer since it is erroneous and we will
* not pass it to higher layer processes.
*/
if (sp->rx_buff[entry]) {
pci_unmap_single(sp->pdev,
le64_to_cpu(rxfd->frag_info) & ~IPG_RFI_FRAGLEN,
sp->rx_buf_sz, PCI_DMA_FROMDEVICE);
dev_kfree_skb_irq(sp->rx_buff[entry]);
}
/* Assure RX buffer is not reused by IPG. */
sp->rx_buff[entry] = NULL;
}
sp->rx_current = curr;
/* Check to see if there are a minimum number of used
* RFDs before restoring any (should improve performance.)
*/
if ((curr - sp->rx_dirty) >= IPG_MINUSEDRFDSTOFREE)
ipg_nic_rxrestore(dev);
return 0;
}
static void ipg_reset_after_host_error(struct work_struct *work)
{
struct ipg_nic_private *sp =
container_of(work, struct ipg_nic_private, task.work);
struct net_device *dev = sp->dev;
/*
* Acknowledge HostError interrupt by resetting
* IPG DMA and HOST.
*/
ipg_reset(dev, IPG_AC_GLOBAL_RESET | IPG_AC_HOST | IPG_AC_DMA);
init_rfdlist(dev);
init_tfdlist(dev);
if (ipg_io_config(dev) < 0) {
printk(KERN_INFO "%s: Cannot recover from PCI error.\n",
dev->name);
schedule_delayed_work(&sp->task, HZ);
}
}
static irqreturn_t ipg_interrupt_handler(int irq, void *dev_inst)
{
struct net_device *dev = dev_inst;
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
unsigned int handled = 0;
u16 status;
IPG_DEBUG_MSG("_interrupt_handler\n");
if (sp->is_jumbo)
ipg_nic_rxrestore(dev);
spin_lock(&sp->lock);
/* Get interrupt source information, and acknowledge
* some (i.e. TxDMAComplete, RxDMAComplete, RxEarly,
* IntRequested, MacControlFrame, LinkEvent) interrupts
* if issued. Also, all IPG interrupts are disabled by
* reading IntStatusAck.
*/
status = ipg_r16(INT_STATUS_ACK);
IPG_DEBUG_MSG("IntStatusAck = %4.4x\n", status);
/* Shared IRQ of remove event. */
if (!(status & IPG_IS_RSVD_MASK))
goto out_enable;
handled = 1;
if (unlikely(!netif_running(dev)))
goto out_unlock;
/* If RFDListEnd interrupt, restore all used RFDs. */
if (status & IPG_IS_RFD_LIST_END) {
IPG_DEBUG_MSG("RFDListEnd Interrupt.\n");
/* The RFD list end indicates an RFD was encountered
* with a 0 NextPtr, or with an RFDDone bit set to 1
* (indicating the RFD is not read for use by the
* IPG.) Try to restore all RFDs.
*/
ipg_nic_rxrestore(dev);
#ifdef IPG_DEBUG
/* Increment the RFDlistendCount counter. */
sp->RFDlistendCount++;
#endif
}
/* If RFDListEnd, RxDMAPriority, RxDMAComplete, or
* IntRequested interrupt, process received frames. */
if ((status & IPG_IS_RX_DMA_PRIORITY) ||
(status & IPG_IS_RFD_LIST_END) ||
(status & IPG_IS_RX_DMA_COMPLETE) ||
(status & IPG_IS_INT_REQUESTED)) {
#ifdef IPG_DEBUG
/* Increment the RFD list checked counter if interrupted
* only to check the RFD list. */
if (status & (~(IPG_IS_RX_DMA_PRIORITY | IPG_IS_RFD_LIST_END |
IPG_IS_RX_DMA_COMPLETE | IPG_IS_INT_REQUESTED) &
(IPG_IS_HOST_ERROR | IPG_IS_TX_DMA_COMPLETE |
IPG_IS_LINK_EVENT | IPG_IS_TX_COMPLETE |
IPG_IS_UPDATE_STATS)))
sp->RFDListCheckedCount++;
#endif
if (sp->is_jumbo)
ipg_nic_rx_jumbo(dev);
else
ipg_nic_rx(dev);
}
/* If TxDMAComplete interrupt, free used TFDs. */
if (status & IPG_IS_TX_DMA_COMPLETE)
ipg_nic_txfree(dev);
/* TxComplete interrupts indicate one of numerous actions.
* Determine what action to take based on TXSTATUS register.
*/
if (status & IPG_IS_TX_COMPLETE)
ipg_nic_txcleanup(dev);
/* If UpdateStats interrupt, update Linux Ethernet statistics */
if (status & IPG_IS_UPDATE_STATS)
ipg_nic_get_stats(dev);
/* If HostError interrupt, reset IPG. */
if (status & IPG_IS_HOST_ERROR) {
IPG_DDEBUG_MSG("HostError Interrupt\n");
schedule_delayed_work(&sp->task, 0);
}
/* If LinkEvent interrupt, resolve autonegotiation. */
if (status & IPG_IS_LINK_EVENT) {
if (ipg_config_autoneg(dev) < 0)
printk(KERN_INFO "%s: Auto-negotiation error.\n",
dev->name);
}
/* If MACCtrlFrame interrupt, do nothing. */
if (status & IPG_IS_MAC_CTRL_FRAME)
IPG_DEBUG_MSG("MACCtrlFrame interrupt.\n");
/* If RxComplete interrupt, do nothing. */
if (status & IPG_IS_RX_COMPLETE)
IPG_DEBUG_MSG("RxComplete interrupt.\n");
/* If RxEarly interrupt, do nothing. */
if (status & IPG_IS_RX_EARLY)
IPG_DEBUG_MSG("RxEarly interrupt.\n");
out_enable:
/* Re-enable IPG interrupts. */
ipg_w16(IPG_IE_TX_DMA_COMPLETE | IPG_IE_RX_DMA_COMPLETE |
IPG_IE_HOST_ERROR | IPG_IE_INT_REQUESTED | IPG_IE_TX_COMPLETE |
IPG_IE_LINK_EVENT | IPG_IE_UPDATE_STATS, INT_ENABLE);
out_unlock:
spin_unlock(&sp->lock);
return IRQ_RETVAL(handled);
}
static void ipg_rx_clear(struct ipg_nic_private *sp)
{
unsigned int i;
for (i = 0; i < IPG_RFDLIST_LENGTH; i++) {
if (sp->rx_buff[i]) {
struct ipg_rx *rxfd = sp->rxd + i;
dev_kfree_skb_irq(sp->rx_buff[i]);
sp->rx_buff[i] = NULL;
pci_unmap_single(sp->pdev,
le64_to_cpu(rxfd->frag_info) & ~IPG_RFI_FRAGLEN,
sp->rx_buf_sz, PCI_DMA_FROMDEVICE);
}
}
}
static void ipg_tx_clear(struct ipg_nic_private *sp)
{
unsigned int i;
for (i = 0; i < IPG_TFDLIST_LENGTH; i++) {
if (sp->tx_buff[i]) {
struct ipg_tx *txfd = sp->txd + i;
pci_unmap_single(sp->pdev,
le64_to_cpu(txfd->frag_info) & ~IPG_TFI_FRAGLEN,
sp->tx_buff[i]->len, PCI_DMA_TODEVICE);
dev_kfree_skb_irq(sp->tx_buff[i]);
sp->tx_buff[i] = NULL;
}
}
}
static int ipg_nic_open(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
struct pci_dev *pdev = sp->pdev;
int rc;
IPG_DEBUG_MSG("_nic_open\n");
sp->rx_buf_sz = sp->rxsupport_size;
/* Check for interrupt line conflicts, and request interrupt
* line for IPG.
*
* IMPORTANT: Disable IPG interrupts prior to registering
* IRQ.
*/
ipg_w16(0x0000, INT_ENABLE);
/* Register the interrupt line to be used by the IPG within
* the Linux system.
*/
rc = request_irq(pdev->irq, ipg_interrupt_handler, IRQF_SHARED,
dev->name, dev);
if (rc < 0) {
printk(KERN_INFO "%s: Error when requesting interrupt.\n",
dev->name);
goto out;
}
dev->irq = pdev->irq;
rc = -ENOMEM;
sp->rxd = dma_alloc_coherent(&pdev->dev, IPG_RX_RING_BYTES,
&sp->rxd_map, GFP_KERNEL);
if (!sp->rxd)
goto err_free_irq_0;
sp->txd = dma_alloc_coherent(&pdev->dev, IPG_TX_RING_BYTES,
&sp->txd_map, GFP_KERNEL);
if (!sp->txd)
goto err_free_rx_1;
rc = init_rfdlist(dev);
if (rc < 0) {
printk(KERN_INFO "%s: Error during configuration.\n",
dev->name);
goto err_free_tx_2;
}
init_tfdlist(dev);
rc = ipg_io_config(dev);
if (rc < 0) {
printk(KERN_INFO "%s: Error during configuration.\n",
dev->name);
goto err_release_tfdlist_3;
}
/* Resolve autonegotiation. */
if (ipg_config_autoneg(dev) < 0)
printk(KERN_INFO "%s: Auto-negotiation error.\n", dev->name);
/* initialize JUMBO Frame control variable */
sp->jumbo.found_start = 0;
sp->jumbo.current_size = 0;
sp->jumbo.skb = NULL;
/* Enable transmit and receive operation of the IPG. */
ipg_w32((ipg_r32(MAC_CTRL) | IPG_MC_RX_ENABLE | IPG_MC_TX_ENABLE) &
IPG_MC_RSVD_MASK, MAC_CTRL);
netif_start_queue(dev);
out:
return rc;
err_release_tfdlist_3:
ipg_tx_clear(sp);
ipg_rx_clear(sp);
err_free_tx_2:
dma_free_coherent(&pdev->dev, IPG_TX_RING_BYTES, sp->txd, sp->txd_map);
err_free_rx_1:
dma_free_coherent(&pdev->dev, IPG_RX_RING_BYTES, sp->rxd, sp->rxd_map);
err_free_irq_0:
free_irq(pdev->irq, dev);
goto out;
}
static int ipg_nic_stop(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
struct pci_dev *pdev = sp->pdev;
IPG_DEBUG_MSG("_nic_stop\n");
netif_stop_queue(dev);
IPG_DUMPTFDLIST(dev);
do {
(void) ipg_r16(INT_STATUS_ACK);
ipg_reset(dev, IPG_AC_GLOBAL_RESET | IPG_AC_HOST | IPG_AC_DMA);
synchronize_irq(pdev->irq);
} while (ipg_r16(INT_ENABLE) & IPG_IE_RSVD_MASK);
ipg_rx_clear(sp);
ipg_tx_clear(sp);
pci_free_consistent(pdev, IPG_RX_RING_BYTES, sp->rxd, sp->rxd_map);
pci_free_consistent(pdev, IPG_TX_RING_BYTES, sp->txd, sp->txd_map);
free_irq(pdev->irq, dev);
return 0;
}
static netdev_tx_t ipg_nic_hard_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
unsigned int entry = sp->tx_current % IPG_TFDLIST_LENGTH;
unsigned long flags;
struct ipg_tx *txfd;
IPG_DDEBUG_MSG("_nic_hard_start_xmit\n");
/* If in 10Mbps mode, stop the transmit queue so
* no more transmit frames are accepted.
*/
if (sp->tenmbpsmode)
netif_stop_queue(dev);
if (sp->reset_current_tfd) {
sp->reset_current_tfd = 0;
entry = 0;
}
txfd = sp->txd + entry;
sp->tx_buff[entry] = skb;
/* Clear all TFC fields, except TFDDONE. */
txfd->tfc = cpu_to_le64(IPG_TFC_TFDDONE);
/* Specify the TFC field within the TFD. */
txfd->tfc |= cpu_to_le64(IPG_TFC_WORDALIGNDISABLED |
(IPG_TFC_FRAMEID & sp->tx_current) |
(IPG_TFC_FRAGCOUNT & (1 << 24)));
/*
* 16--17 (WordAlign) <- 3 (disable),
* 0--15 (FrameId) <- sp->tx_current,
* 24--27 (FragCount) <- 1
*/
/* Request TxComplete interrupts at an interval defined
* by the constant IPG_FRAMESBETWEENTXCOMPLETES.
* Request TxComplete interrupt for every frame
* if in 10Mbps mode to accommodate problem with 10Mbps
* processing.
*/
if (sp->tenmbpsmode)
txfd->tfc |= cpu_to_le64(IPG_TFC_TXINDICATE);
txfd->tfc |= cpu_to_le64(IPG_TFC_TXDMAINDICATE);
/* Based on compilation option, determine if FCS is to be
* appended to transmit frame by IPG.
*/
if (!(IPG_APPEND_FCS_ON_TX))
txfd->tfc |= cpu_to_le64(IPG_TFC_FCSAPPENDDISABLE);
/* Based on compilation option, determine if IP, TCP and/or
* UDP checksums are to be added to transmit frame by IPG.
*/
if (IPG_ADD_IPCHECKSUM_ON_TX)
txfd->tfc |= cpu_to_le64(IPG_TFC_IPCHECKSUMENABLE);
if (IPG_ADD_TCPCHECKSUM_ON_TX)
txfd->tfc |= cpu_to_le64(IPG_TFC_TCPCHECKSUMENABLE);
if (IPG_ADD_UDPCHECKSUM_ON_TX)
txfd->tfc |= cpu_to_le64(IPG_TFC_UDPCHECKSUMENABLE);
/* Based on compilation option, determine if VLAN tag info is to be
* inserted into transmit frame by IPG.
*/
if (IPG_INSERT_MANUAL_VLAN_TAG) {
txfd->tfc |= cpu_to_le64(IPG_TFC_VLANTAGINSERT |
((u64) IPG_MANUAL_VLAN_VID << 32) |
((u64) IPG_MANUAL_VLAN_CFI << 44) |
((u64) IPG_MANUAL_VLAN_USERPRIORITY << 45));
}
/* The fragment start location within system memory is defined
* by the sk_buff structure's data field. The physical address
* of this location within the system's virtual memory space
* is determined using the IPG_HOST2BUS_MAP function.
*/
txfd->frag_info = cpu_to_le64(pci_map_single(sp->pdev, skb->data,
skb->len, PCI_DMA_TODEVICE));
/* The length of the fragment within system memory is defined by
* the sk_buff structure's len field.
*/
txfd->frag_info |= cpu_to_le64(IPG_TFI_FRAGLEN &
((u64) (skb->len & 0xffff) << 48));
/* Clear the TFDDone bit last to indicate the TFD is ready
* for transfer to the IPG.
*/
txfd->tfc &= cpu_to_le64(~IPG_TFC_TFDDONE);
spin_lock_irqsave(&sp->lock, flags);
sp->tx_current++;
mmiowb();
ipg_w32(IPG_DC_TX_DMA_POLL_NOW, DMA_CTRL);
if (sp->tx_current == (sp->tx_dirty + IPG_TFDLIST_LENGTH))
netif_stop_queue(dev);
spin_unlock_irqrestore(&sp->lock, flags);
return NETDEV_TX_OK;
}
static void ipg_set_phy_default_param(unsigned char rev,
struct net_device *dev, int phy_address)
{
unsigned short length;
unsigned char revision;
unsigned short *phy_param;
unsigned short address, value;
phy_param = &DefaultPhyParam[0];
length = *phy_param & 0x00FF;
revision = (unsigned char)((*phy_param) >> 8);
phy_param++;
while (length != 0) {
if (rev == revision) {
while (length > 1) {
address = *phy_param;
value = *(phy_param + 1);
phy_param += 2;
mdio_write(dev, phy_address, address, value);
length -= 4;
}
break;
} else {
phy_param += length / 2;
length = *phy_param & 0x00FF;
revision = (unsigned char)((*phy_param) >> 8);
phy_param++;
}
}
}
static int read_eeprom(struct net_device *dev, int eep_addr)
{
void __iomem *ioaddr = ipg_ioaddr(dev);
unsigned int i;
int ret = 0;
u16 value;
value = IPG_EC_EEPROM_READOPCODE | (eep_addr & 0xff);
ipg_w16(value, EEPROM_CTRL);
for (i = 0; i < 1000; i++) {
u16 data;
mdelay(10);
data = ipg_r16(EEPROM_CTRL);
if (!(data & IPG_EC_EEPROM_BUSY)) {
ret = ipg_r16(EEPROM_DATA);
break;
}
}
return ret;
}
static void ipg_init_mii(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
struct mii_if_info *mii_if = &sp->mii_if;
int phyaddr;
mii_if->dev = dev;
mii_if->mdio_read = mdio_read;
mii_if->mdio_write = mdio_write;
mii_if->phy_id_mask = 0x1f;
mii_if->reg_num_mask = 0x1f;
mii_if->phy_id = phyaddr = ipg_find_phyaddr(dev);
if (phyaddr != 0x1f) {
u16 mii_phyctrl, mii_1000cr;
mii_1000cr = mdio_read(dev, phyaddr, MII_CTRL1000);
mii_1000cr |= ADVERTISE_1000FULL | ADVERTISE_1000HALF |
GMII_PHY_1000BASETCONTROL_PreferMaster;
mdio_write(dev, phyaddr, MII_CTRL1000, mii_1000cr);
mii_phyctrl = mdio_read(dev, phyaddr, MII_BMCR);
/* Set default phyparam */
ipg_set_phy_default_param(sp->pdev->revision, dev, phyaddr);
/* Reset PHY */
mii_phyctrl |= BMCR_RESET | BMCR_ANRESTART;
mdio_write(dev, phyaddr, MII_BMCR, mii_phyctrl);
}
}
static int ipg_hw_init(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
void __iomem *ioaddr = sp->ioaddr;
unsigned int i;
int rc;
/* Read/Write and Reset EEPROM Value */
/* Read LED Mode Configuration from EEPROM */
sp->led_mode = read_eeprom(dev, 6);
/* Reset all functions within the IPG. Do not assert
* RST_OUT as not compatible with some PHYs.
*/
rc = ipg_reset(dev, IPG_RESET_MASK);
if (rc < 0)
goto out;
ipg_init_mii(dev);
/* Read MAC Address from EEPROM */
for (i = 0; i < 3; i++)
sp->station_addr[i] = read_eeprom(dev, 16 + i);
for (i = 0; i < 3; i++)
ipg_w16(sp->station_addr[i], STATION_ADDRESS_0 + 2*i);
/* Set station address in ethernet_device structure. */
dev->dev_addr[0] = ipg_r16(STATION_ADDRESS_0) & 0x00ff;
dev->dev_addr[1] = (ipg_r16(STATION_ADDRESS_0) & 0xff00) >> 8;
dev->dev_addr[2] = ipg_r16(STATION_ADDRESS_1) & 0x00ff;
dev->dev_addr[3] = (ipg_r16(STATION_ADDRESS_1) & 0xff00) >> 8;
dev->dev_addr[4] = ipg_r16(STATION_ADDRESS_2) & 0x00ff;
dev->dev_addr[5] = (ipg_r16(STATION_ADDRESS_2) & 0xff00) >> 8;
out:
return rc;
}
static int ipg_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
struct ipg_nic_private *sp = netdev_priv(dev);
int rc;
mutex_lock(&sp->mii_mutex);
rc = generic_mii_ioctl(&sp->mii_if, if_mii(ifr), cmd, NULL);
mutex_unlock(&sp->mii_mutex);
return rc;
}
static int ipg_nic_change_mtu(struct net_device *dev, int new_mtu)
{
struct ipg_nic_private *sp = netdev_priv(dev);
int err;
/* Function to accommodate changes to Maximum Transfer Unit
* (or MTU) of IPG NIC. Cannot use default function since
* the default will not allow for MTU > 1500 bytes.
*/
IPG_DEBUG_MSG("_nic_change_mtu\n");
/*
* Check that the new MTU value is between 68 (14 byte header, 46 byte
* payload, 4 byte FCS) and 10 KB, which is the largest supported MTU.
*/
if (new_mtu < 68 || new_mtu > 10240)
return -EINVAL;
err = ipg_nic_stop(dev);
if (err)
return err;
dev->mtu = new_mtu;
sp->max_rxframe_size = new_mtu;
sp->rxfrag_size = new_mtu;
if (sp->rxfrag_size > 4088)
sp->rxfrag_size = 4088;
sp->rxsupport_size = sp->max_rxframe_size;
if (new_mtu > 0x0600)
sp->is_jumbo = true;
else
sp->is_jumbo = false;
return ipg_nic_open(dev);
}
static int ipg_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct ipg_nic_private *sp = netdev_priv(dev);
int rc;
mutex_lock(&sp->mii_mutex);
rc = mii_ethtool_gset(&sp->mii_if, cmd);
mutex_unlock(&sp->mii_mutex);
return rc;
}
static int ipg_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct ipg_nic_private *sp = netdev_priv(dev);
int rc;
mutex_lock(&sp->mii_mutex);
rc = mii_ethtool_sset(&sp->mii_if, cmd);
mutex_unlock(&sp->mii_mutex);
return rc;
}
static int ipg_nway_reset(struct net_device *dev)
{
struct ipg_nic_private *sp = netdev_priv(dev);
int rc;
mutex_lock(&sp->mii_mutex);
rc = mii_nway_restart(&sp->mii_if);
mutex_unlock(&sp->mii_mutex);
return rc;
}
static const struct ethtool_ops ipg_ethtool_ops = {
.get_settings = ipg_get_settings,
.set_settings = ipg_set_settings,
.nway_reset = ipg_nway_reset,
};
static void __devexit ipg_remove(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct ipg_nic_private *sp = netdev_priv(dev);
IPG_DEBUG_MSG("_remove\n");
/* Un-register Ethernet device. */
unregister_netdev(dev);
pci_iounmap(pdev, sp->ioaddr);
pci_release_regions(pdev);
free_netdev(dev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
}
static const struct net_device_ops ipg_netdev_ops = {
.ndo_open = ipg_nic_open,
.ndo_stop = ipg_nic_stop,
.ndo_start_xmit = ipg_nic_hard_start_xmit,
.ndo_get_stats = ipg_nic_get_stats,
.ndo_set_multicast_list = ipg_nic_set_multicast_list,
.ndo_do_ioctl = ipg_ioctl,
.ndo_tx_timeout = ipg_tx_timeout,
.ndo_change_mtu = ipg_nic_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static int __devinit ipg_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
unsigned int i = id->driver_data;
struct ipg_nic_private *sp;
struct net_device *dev;
void __iomem *ioaddr;
int rc;
rc = pci_enable_device(pdev);
if (rc < 0)
goto out;
printk(KERN_INFO "%s: %s\n", pci_name(pdev), ipg_brand_name[i]);
pci_set_master(pdev);
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(40));
if (rc < 0) {
rc = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (rc < 0) {
printk(KERN_ERR "%s: DMA config failed.\n",
pci_name(pdev));
goto err_disable_0;
}
}
/*
* Initialize net device.
*/
dev = alloc_etherdev(sizeof(struct ipg_nic_private));
if (!dev) {
printk(KERN_ERR "%s: alloc_etherdev failed\n", pci_name(pdev));
rc = -ENOMEM;
goto err_disable_0;
}
sp = netdev_priv(dev);
spin_lock_init(&sp->lock);
mutex_init(&sp->mii_mutex);
sp->is_jumbo = IPG_IS_JUMBO;
sp->rxfrag_size = IPG_RXFRAG_SIZE;
sp->rxsupport_size = IPG_RXSUPPORT_SIZE;
sp->max_rxframe_size = IPG_MAX_RXFRAME_SIZE;
/* Declare IPG NIC functions for Ethernet device methods.
*/
dev->netdev_ops = &ipg_netdev_ops;
SET_NETDEV_DEV(dev, &pdev->dev);
SET_ETHTOOL_OPS(dev, &ipg_ethtool_ops);
rc = pci_request_regions(pdev, DRV_NAME);
if (rc)
goto err_free_dev_1;
ioaddr = pci_iomap(pdev, 1, pci_resource_len(pdev, 1));
if (!ioaddr) {
printk(KERN_ERR "%s cannot map MMIO\n", pci_name(pdev));
rc = -EIO;
goto err_release_regions_2;
}
/* Save the pointer to the PCI device information. */
sp->ioaddr = ioaddr;
sp->pdev = pdev;
sp->dev = dev;
INIT_DELAYED_WORK(&sp->task, ipg_reset_after_host_error);
pci_set_drvdata(pdev, dev);
rc = ipg_hw_init(dev);
if (rc < 0)
goto err_unmap_3;
rc = register_netdev(dev);
if (rc < 0)
goto err_unmap_3;
printk(KERN_INFO "Ethernet device registered as: %s\n", dev->name);
out:
return rc;
err_unmap_3:
pci_iounmap(pdev, ioaddr);
err_release_regions_2:
pci_release_regions(pdev);
err_free_dev_1:
free_netdev(dev);
err_disable_0:
pci_disable_device(pdev);
goto out;
}
static struct pci_driver ipg_pci_driver = {
.name = IPG_DRIVER_NAME,
.id_table = ipg_pci_tbl,
.probe = ipg_probe,
.remove = __devexit_p(ipg_remove),
};
static int __init ipg_init_module(void)
{
return pci_register_driver(&ipg_pci_driver);
}
static void __exit ipg_exit_module(void)
{
pci_unregister_driver(&ipg_pci_driver);
}
module_init(ipg_init_module);
module_exit(ipg_exit_module);
| gpl-2.0 |
nrgmilk/linux | security/tomoyo/securityfs_if.c | 390 | 4275 | /*
* security/tomoyo/securityfs_if.c
*
* Copyright (C) 2005-2011 NTT DATA CORPORATION
*/
#include <linux/security.h>
#include "common.h"
/**
* tomoyo_open - open() for /sys/kernel/security/tomoyo/ interface.
*
* @inode: Pointer to "struct inode".
* @file: Pointer to "struct file".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_open(struct inode *inode, struct file *file)
{
const int key = ((u8 *) file->f_path.dentry->d_inode->i_private)
- ((u8 *) NULL);
return tomoyo_open_control(key, file);
}
/**
* tomoyo_release - close() for /sys/kernel/security/tomoyo/ interface.
*
* @inode: Pointer to "struct inode".
* @file: Pointer to "struct file".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_release(struct inode *inode, struct file *file)
{
return tomoyo_close_control(file->private_data);
}
/**
* tomoyo_poll - poll() for /sys/kernel/security/tomoyo/ interface.
*
* @file: Pointer to "struct file".
* @wait: Pointer to "poll_table".
*
* Returns 0 on success, negative value otherwise.
*/
static unsigned int tomoyo_poll(struct file *file, poll_table *wait)
{
return tomoyo_poll_control(file, wait);
}
/**
* tomoyo_read - read() for /sys/kernel/security/tomoyo/ interface.
*
* @file: Pointer to "struct file".
* @buf: Pointer to buffer.
* @count: Size of @buf.
* @ppos: Unused.
*
* Returns bytes read on success, negative value otherwise.
*/
static ssize_t tomoyo_read(struct file *file, char __user *buf, size_t count,
loff_t *ppos)
{
return tomoyo_read_control(file->private_data, buf, count);
}
/**
* tomoyo_write - write() for /sys/kernel/security/tomoyo/ interface.
*
* @file: Pointer to "struct file".
* @buf: Pointer to buffer.
* @count: Size of @buf.
* @ppos: Unused.
*
* Returns @count on success, negative value otherwise.
*/
static ssize_t tomoyo_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
return tomoyo_write_control(file->private_data, buf, count);
}
/*
* tomoyo_operations is a "struct file_operations" which is used for handling
* /sys/kernel/security/tomoyo/ interface.
*
* Some files under /sys/kernel/security/tomoyo/ directory accept open(O_RDWR).
* See tomoyo_io_buffer for internals.
*/
static const struct file_operations tomoyo_operations = {
.open = tomoyo_open,
.release = tomoyo_release,
.poll = tomoyo_poll,
.read = tomoyo_read,
.write = tomoyo_write,
.llseek = noop_llseek,
};
/**
* tomoyo_create_entry - Create interface files under /sys/kernel/security/tomoyo/ directory.
*
* @name: The name of the interface file.
* @mode: The permission of the interface file.
* @parent: The parent directory.
* @key: Type of interface.
*
* Returns nothing.
*/
static void __init tomoyo_create_entry(const char *name, const mode_t mode,
struct dentry *parent, const u8 key)
{
securityfs_create_file(name, mode, parent, ((u8 *) NULL) + key,
&tomoyo_operations);
}
/**
* tomoyo_initerface_init - Initialize /sys/kernel/security/tomoyo/ interface.
*
* Returns 0.
*/
static int __init tomoyo_initerface_init(void)
{
struct dentry *tomoyo_dir;
/* Don't create securityfs entries unless registered. */
if (current_cred()->security != &tomoyo_kernel_domain)
return 0;
tomoyo_dir = securityfs_create_dir("tomoyo", NULL);
tomoyo_create_entry("query", 0600, tomoyo_dir,
TOMOYO_QUERY);
tomoyo_create_entry("domain_policy", 0600, tomoyo_dir,
TOMOYO_DOMAINPOLICY);
tomoyo_create_entry("exception_policy", 0600, tomoyo_dir,
TOMOYO_EXCEPTIONPOLICY);
tomoyo_create_entry("audit", 0400, tomoyo_dir,
TOMOYO_AUDIT);
tomoyo_create_entry("self_domain", 0400, tomoyo_dir,
TOMOYO_SELFDOMAIN);
tomoyo_create_entry(".process_status", 0600, tomoyo_dir,
TOMOYO_PROCESS_STATUS);
tomoyo_create_entry("stat", 0644, tomoyo_dir,
TOMOYO_STAT);
tomoyo_create_entry("profile", 0600, tomoyo_dir,
TOMOYO_PROFILE);
tomoyo_create_entry("manager", 0600, tomoyo_dir,
TOMOYO_MANAGER);
tomoyo_create_entry("version", 0400, tomoyo_dir,
TOMOYO_VERSION);
return 0;
}
fs_initcall(tomoyo_initerface_init);
| gpl-2.0 |
weboo/kernel-nexus-s | drivers/media/video/v4l2-event.c | 902 | 6679 | /*
* v4l2-event.c
*
* V4L2 events.
*
* Copyright (C) 2009--2010 Nokia Corporation.
*
* Contact: Sakari Ailus <sakari.ailus@maxwell.research.nokia.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 <media/v4l2-dev.h>
#include <media/v4l2-fh.h>
#include <media/v4l2-event.h>
#include <linux/sched.h>
#include <linux/slab.h>
int v4l2_event_init(struct v4l2_fh *fh)
{
fh->events = kzalloc(sizeof(*fh->events), GFP_KERNEL);
if (fh->events == NULL)
return -ENOMEM;
init_waitqueue_head(&fh->events->wait);
INIT_LIST_HEAD(&fh->events->free);
INIT_LIST_HEAD(&fh->events->available);
INIT_LIST_HEAD(&fh->events->subscribed);
fh->events->sequence = -1;
return 0;
}
EXPORT_SYMBOL_GPL(v4l2_event_init);
int v4l2_event_alloc(struct v4l2_fh *fh, unsigned int n)
{
struct v4l2_events *events = fh->events;
unsigned long flags;
if (!events) {
WARN_ON(1);
return -ENOMEM;
}
while (events->nallocated < n) {
struct v4l2_kevent *kev;
kev = kzalloc(sizeof(*kev), GFP_KERNEL);
if (kev == NULL)
return -ENOMEM;
spin_lock_irqsave(&fh->vdev->fh_lock, flags);
list_add_tail(&kev->list, &events->free);
events->nallocated++;
spin_unlock_irqrestore(&fh->vdev->fh_lock, flags);
}
return 0;
}
EXPORT_SYMBOL_GPL(v4l2_event_alloc);
#define list_kfree(list, type, member) \
while (!list_empty(list)) { \
type *hi; \
hi = list_first_entry(list, type, member); \
list_del(&hi->member); \
kfree(hi); \
}
void v4l2_event_free(struct v4l2_fh *fh)
{
struct v4l2_events *events = fh->events;
if (!events)
return;
list_kfree(&events->free, struct v4l2_kevent, list);
list_kfree(&events->available, struct v4l2_kevent, list);
list_kfree(&events->subscribed, struct v4l2_subscribed_event, list);
kfree(events);
fh->events = NULL;
}
EXPORT_SYMBOL_GPL(v4l2_event_free);
static int __v4l2_event_dequeue(struct v4l2_fh *fh, struct v4l2_event *event)
{
struct v4l2_events *events = fh->events;
struct v4l2_kevent *kev;
unsigned long flags;
spin_lock_irqsave(&fh->vdev->fh_lock, flags);
if (list_empty(&events->available)) {
spin_unlock_irqrestore(&fh->vdev->fh_lock, flags);
return -ENOENT;
}
WARN_ON(events->navailable == 0);
kev = list_first_entry(&events->available, struct v4l2_kevent, list);
list_move(&kev->list, &events->free);
events->navailable--;
kev->event.pending = events->navailable;
*event = kev->event;
spin_unlock_irqrestore(&fh->vdev->fh_lock, flags);
return 0;
}
int v4l2_event_dequeue(struct v4l2_fh *fh, struct v4l2_event *event,
int nonblocking)
{
struct v4l2_events *events = fh->events;
int ret;
if (nonblocking)
return __v4l2_event_dequeue(fh, event);
do {
ret = wait_event_interruptible(events->wait,
events->navailable != 0);
if (ret < 0)
return ret;
ret = __v4l2_event_dequeue(fh, event);
} while (ret == -ENOENT);
return ret;
}
EXPORT_SYMBOL_GPL(v4l2_event_dequeue);
/* Caller must hold fh->event->lock! */
static struct v4l2_subscribed_event *v4l2_event_subscribed(
struct v4l2_fh *fh, u32 type)
{
struct v4l2_events *events = fh->events;
struct v4l2_subscribed_event *sev;
assert_spin_locked(&fh->vdev->fh_lock);
list_for_each_entry(sev, &events->subscribed, list) {
if (sev->type == type)
return sev;
}
return NULL;
}
void v4l2_event_queue(struct video_device *vdev, const struct v4l2_event *ev)
{
struct v4l2_fh *fh;
unsigned long flags;
struct timespec timestamp;
ktime_get_ts(×tamp);
spin_lock_irqsave(&vdev->fh_lock, flags);
list_for_each_entry(fh, &vdev->fh_list, list) {
struct v4l2_events *events = fh->events;
struct v4l2_kevent *kev;
/* Are we subscribed? */
if (!v4l2_event_subscribed(fh, ev->type))
continue;
/* Increase event sequence number on fh. */
events->sequence++;
/* Do we have any free events? */
if (list_empty(&events->free))
continue;
/* Take one and fill it. */
kev = list_first_entry(&events->free, struct v4l2_kevent, list);
kev->event.type = ev->type;
kev->event.u = ev->u;
kev->event.timestamp = timestamp;
kev->event.sequence = events->sequence;
list_move_tail(&kev->list, &events->available);
events->navailable++;
wake_up_all(&events->wait);
}
spin_unlock_irqrestore(&vdev->fh_lock, flags);
}
EXPORT_SYMBOL_GPL(v4l2_event_queue);
int v4l2_event_pending(struct v4l2_fh *fh)
{
return fh->events->navailable;
}
EXPORT_SYMBOL_GPL(v4l2_event_pending);
int v4l2_event_subscribe(struct v4l2_fh *fh,
struct v4l2_event_subscription *sub)
{
struct v4l2_events *events = fh->events;
struct v4l2_subscribed_event *sev;
unsigned long flags;
if (fh->events == NULL) {
WARN_ON(1);
return -ENOMEM;
}
sev = kmalloc(sizeof(*sev), GFP_KERNEL);
if (!sev)
return -ENOMEM;
spin_lock_irqsave(&fh->vdev->fh_lock, flags);
if (v4l2_event_subscribed(fh, sub->type) == NULL) {
INIT_LIST_HEAD(&sev->list);
sev->type = sub->type;
list_add(&sev->list, &events->subscribed);
sev = NULL;
}
spin_unlock_irqrestore(&fh->vdev->fh_lock, flags);
kfree(sev);
return 0;
}
EXPORT_SYMBOL_GPL(v4l2_event_subscribe);
static void v4l2_event_unsubscribe_all(struct v4l2_fh *fh)
{
struct v4l2_events *events = fh->events;
struct v4l2_subscribed_event *sev;
unsigned long flags;
do {
sev = NULL;
spin_lock_irqsave(&fh->vdev->fh_lock, flags);
if (!list_empty(&events->subscribed)) {
sev = list_first_entry(&events->subscribed,
struct v4l2_subscribed_event, list);
list_del(&sev->list);
}
spin_unlock_irqrestore(&fh->vdev->fh_lock, flags);
kfree(sev);
} while (sev);
}
int v4l2_event_unsubscribe(struct v4l2_fh *fh,
struct v4l2_event_subscription *sub)
{
struct v4l2_subscribed_event *sev;
unsigned long flags;
if (sub->type == V4L2_EVENT_ALL) {
v4l2_event_unsubscribe_all(fh);
return 0;
}
spin_lock_irqsave(&fh->vdev->fh_lock, flags);
sev = v4l2_event_subscribed(fh, sub->type);
if (sev != NULL)
list_del(&sev->list);
spin_unlock_irqrestore(&fh->vdev->fh_lock, flags);
kfree(sev);
return 0;
}
EXPORT_SYMBOL_GPL(v4l2_event_unsubscribe);
| gpl-2.0 |
Khaon/android_kernel_samsung_a3xelte | arch/tile/kernel/smpboot.c | 1926 | 7268 | /*
* Copyright 2010 Tilera Corporation. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, version 2.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for
* more details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/kernel_stat.h>
#include <linux/bootmem.h>
#include <linux/notifier.h>
#include <linux/cpu.h>
#include <linux/percpu.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/irq.h>
#include <asm/mmu_context.h>
#include <asm/tlbflush.h>
#include <asm/sections.h>
/* State of each CPU. */
static DEFINE_PER_CPU(int, cpu_state) = { 0 };
/* The messaging code jumps to this pointer during boot-up */
unsigned long start_cpu_function_addr;
/* Called very early during startup to mark boot cpu as online */
void __init smp_prepare_boot_cpu(void)
{
int cpu = smp_processor_id();
set_cpu_online(cpu, 1);
set_cpu_present(cpu, 1);
__get_cpu_var(cpu_state) = CPU_ONLINE;
init_messaging();
}
static void start_secondary(void);
/*
* Called at the top of init() to launch all the other CPUs.
* They run free to complete their initialization and then wait
* until they get an IPI from the boot cpu to come online.
*/
void __init smp_prepare_cpus(unsigned int max_cpus)
{
long rc;
int cpu, cpu_count;
int boot_cpu = smp_processor_id();
current_thread_info()->cpu = boot_cpu;
/*
* Pin this task to the boot CPU while we bring up the others,
* just to make sure we don't uselessly migrate as they come up.
*/
rc = sched_setaffinity(current->pid, cpumask_of(boot_cpu));
if (rc != 0)
pr_err("Couldn't set init affinity to boot cpu (%ld)\n", rc);
/* Print information about disabled and dataplane cpus. */
print_disabled_cpus();
/*
* Tell the messaging subsystem how to respond to the
* startup message. We use a level of indirection to avoid
* confusing the linker with the fact that the messaging
* subsystem is calling __init code.
*/
start_cpu_function_addr = (unsigned long) &online_secondary;
/* Set up thread context for all new processors. */
cpu_count = 1;
for (cpu = 0; cpu < NR_CPUS; ++cpu) {
struct task_struct *idle;
if (cpu == boot_cpu)
continue;
if (!cpu_possible(cpu)) {
/*
* Make this processor do nothing on boot.
* Note that we don't give the boot_pc function
* a stack, so it has to be assembly code.
*/
per_cpu(boot_sp, cpu) = 0;
per_cpu(boot_pc, cpu) = (unsigned long) smp_nap;
continue;
}
/* Create a new idle thread to run start_secondary() */
idle = fork_idle(cpu);
if (IS_ERR(idle))
panic("failed fork for CPU %d", cpu);
idle->thread.pc = (unsigned long) start_secondary;
/* Make this thread the boot thread for this processor */
per_cpu(boot_sp, cpu) = task_ksp0(idle);
per_cpu(boot_pc, cpu) = idle->thread.pc;
++cpu_count;
}
BUG_ON(cpu_count > (max_cpus ? max_cpus : 1));
/* Fire up the other tiles, if any */
init_cpu_present(cpu_possible_mask);
if (cpumask_weight(cpu_present_mask) > 1) {
mb(); /* make sure all data is visible to new processors */
hv_start_all_tiles();
}
}
static __initdata struct cpumask init_affinity;
static __init int reset_init_affinity(void)
{
long rc = sched_setaffinity(current->pid, &init_affinity);
if (rc != 0)
pr_warning("couldn't reset init affinity (%ld)\n",
rc);
return 0;
}
late_initcall(reset_init_affinity);
static struct cpumask cpu_started __cpuinitdata;
/*
* Activate a secondary processor. Very minimal; don't add anything
* to this path without knowing what you're doing, since SMP booting
* is pretty fragile.
*/
static void __cpuinit start_secondary(void)
{
int cpuid = smp_processor_id();
/* Set our thread pointer appropriately. */
set_my_cpu_offset(__per_cpu_offset[cpuid]);
preempt_disable();
/*
* In large machines even this will slow us down, since we
* will be contending for for the printk spinlock.
*/
/* printk(KERN_DEBUG "Initializing CPU#%d\n", cpuid); */
/* Initialize the current asid for our first page table. */
__get_cpu_var(current_asid) = min_asid;
/* Set up this thread as another owner of the init_mm */
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
if (current->mm)
BUG();
enter_lazy_tlb(&init_mm, current);
/* Allow hypervisor messages to be received */
init_messaging();
local_irq_enable();
/* Indicate that we're ready to come up. */
/* Must not do this before we're ready to receive messages */
if (cpumask_test_and_set_cpu(cpuid, &cpu_started)) {
pr_warning("CPU#%d already started!\n", cpuid);
for (;;)
local_irq_enable();
}
smp_nap();
}
/*
* Bring a secondary processor online.
*/
void __cpuinit online_secondary(void)
{
/*
* low-memory mappings have been cleared, flush them from
* the local TLBs too.
*/
local_flush_tlb();
BUG_ON(in_interrupt());
/* This must be done before setting cpu_online_mask */
wmb();
notify_cpu_starting(smp_processor_id());
set_cpu_online(smp_processor_id(), 1);
__get_cpu_var(cpu_state) = CPU_ONLINE;
/* Set up tile-specific state for this cpu. */
setup_cpu(0);
/* Set up tile-timer clock-event device on this cpu */
setup_tile_timer();
cpu_startup_entry(CPUHP_ONLINE);
}
int __cpuinit __cpu_up(unsigned int cpu, struct task_struct *tidle)
{
/* Wait 5s total for all CPUs for them to come online */
static int timeout;
for (; !cpumask_test_cpu(cpu, &cpu_started); timeout++) {
if (timeout >= 50000) {
pr_info("skipping unresponsive cpu%d\n", cpu);
local_irq_enable();
return -EIO;
}
udelay(100);
}
local_irq_enable();
per_cpu(cpu_state, cpu) = CPU_UP_PREPARE;
/* Unleash the CPU! */
send_IPI_single(cpu, MSG_TAG_START_CPU);
while (!cpumask_test_cpu(cpu, cpu_online_mask))
cpu_relax();
return 0;
}
static void panic_start_cpu(void)
{
panic("Received a MSG_START_CPU IPI after boot finished.");
}
void __init smp_cpus_done(unsigned int max_cpus)
{
int cpu, next, rc;
/* Reset the response to a (now illegal) MSG_START_CPU IPI. */
start_cpu_function_addr = (unsigned long) &panic_start_cpu;
cpumask_copy(&init_affinity, cpu_online_mask);
/*
* Pin ourselves to a single cpu in the initial affinity set
* so that kernel mappings for the rootfs are not in the dataplane,
* if set, and to avoid unnecessary migrating during bringup.
* Use the last cpu just in case the whole chip has been
* isolated from the scheduler, to keep init away from likely
* more useful user code. This also ensures that work scheduled
* via schedule_delayed_work() in the init routines will land
* on this cpu.
*/
for (cpu = cpumask_first(&init_affinity);
(next = cpumask_next(cpu, &init_affinity)) < nr_cpu_ids;
cpu = next)
;
rc = sched_setaffinity(current->pid, cpumask_of(cpu));
if (rc != 0)
pr_err("Couldn't set init affinity to cpu %d (%d)\n", cpu, rc);
}
| gpl-2.0 |
eoghan2t9/primou-kernel-IRONMAN | drivers/scsi/st.c | 2438 | 127588 | /*
SCSI Tape Driver for Linux version 1.1 and newer. See the accompanying
file Documentation/scsi/st.txt for more information.
History:
Rewritten from Dwayne Forsyth's SCSI tape driver by Kai Makisara.
Contribution and ideas from several people including (in alphabetical
order) Klaus Ehrenfried, Eugene Exarevsky, Eric Lee Green, Wolfgang Denk,
Steve Hirsch, Andreas Koppenh"ofer, Michael Leodolter, Eyal Lebedinsky,
Michael Schaefer, J"org Weule, and Eric Youngdale.
Copyright 1992 - 2010 Kai Makisara
email Kai.Makisara@kolumbus.fi
Some small formal changes - aeb, 950809
Last modified: 18-JAN-1998 Richard Gooch <rgooch@atnf.csiro.au> Devfs support
*/
static const char *verstr = "20101219";
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/mtio.h>
#include <linux/cdrom.h>
#include <linux/ioctl.h>
#include <linux/fcntl.h>
#include <linux/spinlock.h>
#include <linux/blkdev.h>
#include <linux/moduleparam.h>
#include <linux/cdev.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <asm/dma.h>
#include <asm/system.h>
#include <scsi/scsi.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/sg.h>
/* The driver prints some debugging information on the console if DEBUG
is defined and non-zero. */
#define DEBUG 0
#if DEBUG
/* The message level for the debug messages is currently set to KERN_NOTICE
so that people can easily see the messages. Later when the debugging messages
in the drivers are more widely classified, this may be changed to KERN_DEBUG. */
#define ST_DEB_MSG KERN_NOTICE
#define DEB(a) a
#define DEBC(a) if (debugging) { a ; }
#else
#define DEB(a)
#define DEBC(a)
#endif
#define ST_KILOBYTE 1024
#include "st_options.h"
#include "st.h"
static DEFINE_MUTEX(st_mutex);
static int buffer_kbs;
static int max_sg_segs;
static int try_direct_io = TRY_DIRECT_IO;
static int try_rdio = 1;
static int try_wdio = 1;
static int st_dev_max;
static int st_nr_dev;
static struct class *st_sysfs_class;
MODULE_AUTHOR("Kai Makisara");
MODULE_DESCRIPTION("SCSI tape (st) driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV_MAJOR(SCSI_TAPE_MAJOR);
MODULE_ALIAS_SCSI_DEVICE(TYPE_TAPE);
/* Set 'perm' (4th argument) to 0 to disable module_param's definition
* of sysfs parameters (which module_param doesn't yet support).
* Sysfs parameters defined explicitly later.
*/
module_param_named(buffer_kbs, buffer_kbs, int, 0);
MODULE_PARM_DESC(buffer_kbs, "Default driver buffer size for fixed block mode (KB; 32)");
module_param_named(max_sg_segs, max_sg_segs, int, 0);
MODULE_PARM_DESC(max_sg_segs, "Maximum number of scatter/gather segments to use (256)");
module_param_named(try_direct_io, try_direct_io, int, 0);
MODULE_PARM_DESC(try_direct_io, "Try direct I/O between user buffer and tape drive (1)");
/* Extra parameters for testing */
module_param_named(try_rdio, try_rdio, int, 0);
MODULE_PARM_DESC(try_rdio, "Try direct read i/o when possible");
module_param_named(try_wdio, try_wdio, int, 0);
MODULE_PARM_DESC(try_wdio, "Try direct write i/o when possible");
#ifndef MODULE
static int write_threshold_kbs; /* retained for compatibility */
static struct st_dev_parm {
char *name;
int *val;
} parms[] __initdata = {
{
"buffer_kbs", &buffer_kbs
},
{ /* Retained for compatibility with 2.4 */
"write_threshold_kbs", &write_threshold_kbs
},
{
"max_sg_segs", NULL
},
{
"try_direct_io", &try_direct_io
}
};
#endif
/* Restrict the number of modes so that names for all are assigned */
#if ST_NBR_MODES > 16
#error "Maximum number of modes is 16"
#endif
/* Bit reversed order to get same names for same minors with all
mode counts */
static const char *st_formats[] = {
"", "r", "k", "s", "l", "t", "o", "u",
"m", "v", "p", "x", "a", "y", "q", "z"};
/* The default definitions have been moved to st_options.h */
#define ST_FIXED_BUFFER_SIZE (ST_FIXED_BUFFER_BLOCKS * ST_KILOBYTE)
/* The buffer size should fit into the 24 bits for length in the
6-byte SCSI read and write commands. */
#if ST_FIXED_BUFFER_SIZE >= (2 << 24 - 1)
#error "Buffer size should not exceed (2 << 24 - 1) bytes!"
#endif
static int debugging = DEBUG;
#define MAX_RETRIES 0
#define MAX_WRITE_RETRIES 0
#define MAX_READY_RETRIES 0
#define NO_TAPE NOT_READY
#define ST_TIMEOUT (900 * HZ)
#define ST_LONG_TIMEOUT (14000 * HZ)
/* Remove mode bits and auto-rewind bit (7) */
#define TAPE_NR(x) ( ((iminor(x) & ~255) >> (ST_NBR_MODE_BITS + 1)) | \
(iminor(x) & ~(-1 << ST_MODE_SHIFT)) )
#define TAPE_MODE(x) ((iminor(x) & ST_MODE_MASK) >> ST_MODE_SHIFT)
/* Construct the minor number from the device (d), mode (m), and non-rewind (n) data */
#define TAPE_MINOR(d, m, n) (((d & ~(255 >> (ST_NBR_MODE_BITS + 1))) << (ST_NBR_MODE_BITS + 1)) | \
(d & (255 >> (ST_NBR_MODE_BITS + 1))) | (m << ST_MODE_SHIFT) | ((n != 0) << 7) )
/* Internal ioctl to set both density (uppermost 8 bits) and blocksize (lower
24 bits) */
#define SET_DENS_AND_BLK 0x10001
static DEFINE_RWLOCK(st_dev_arr_lock);
static int st_fixed_buffer_size = ST_FIXED_BUFFER_SIZE;
static int st_max_sg_segs = ST_MAX_SG;
static struct scsi_tape **scsi_tapes = NULL;
static int modes_defined;
static int enlarge_buffer(struct st_buffer *, int, int);
static void clear_buffer(struct st_buffer *);
static void normalize_buffer(struct st_buffer *);
static int append_to_buffer(const char __user *, struct st_buffer *, int);
static int from_buffer(struct st_buffer *, char __user *, int);
static void move_buffer_data(struct st_buffer *, int);
static int sgl_map_user_pages(struct st_buffer *, const unsigned int,
unsigned long, size_t, int);
static int sgl_unmap_user_pages(struct st_buffer *, const unsigned int, int);
static int st_probe(struct device *);
static int st_remove(struct device *);
static int do_create_sysfs_files(void);
static void do_remove_sysfs_files(void);
static int do_create_class_files(struct scsi_tape *, int, int);
static struct scsi_driver st_template = {
.owner = THIS_MODULE,
.gendrv = {
.name = "st",
.probe = st_probe,
.remove = st_remove,
},
};
static int st_compression(struct scsi_tape *, int);
static int find_partition(struct scsi_tape *);
static int switch_partition(struct scsi_tape *);
static int st_int_ioctl(struct scsi_tape *, unsigned int, unsigned long);
static void scsi_tape_release(struct kref *);
#define to_scsi_tape(obj) container_of(obj, struct scsi_tape, kref)
static DEFINE_MUTEX(st_ref_mutex);
#include "osst_detect.h"
#ifndef SIGS_FROM_OSST
#define SIGS_FROM_OSST \
{"OnStream", "SC-", "", "osst"}, \
{"OnStream", "DI-", "", "osst"}, \
{"OnStream", "DP-", "", "osst"}, \
{"OnStream", "USB", "", "osst"}, \
{"OnStream", "FW-", "", "osst"}
#endif
static struct scsi_tape *scsi_tape_get(int dev)
{
struct scsi_tape *STp = NULL;
mutex_lock(&st_ref_mutex);
write_lock(&st_dev_arr_lock);
if (dev < st_dev_max && scsi_tapes != NULL)
STp = scsi_tapes[dev];
if (!STp) goto out;
kref_get(&STp->kref);
if (!STp->device)
goto out_put;
if (scsi_device_get(STp->device))
goto out_put;
goto out;
out_put:
kref_put(&STp->kref, scsi_tape_release);
STp = NULL;
out:
write_unlock(&st_dev_arr_lock);
mutex_unlock(&st_ref_mutex);
return STp;
}
static void scsi_tape_put(struct scsi_tape *STp)
{
struct scsi_device *sdev = STp->device;
mutex_lock(&st_ref_mutex);
kref_put(&STp->kref, scsi_tape_release);
scsi_device_put(sdev);
mutex_unlock(&st_ref_mutex);
}
struct st_reject_data {
char *vendor;
char *model;
char *rev;
char *driver_hint; /* Name of the correct driver, NULL if unknown */
};
static struct st_reject_data reject_list[] = {
/* {"XXX", "Yy-", "", NULL}, example */
SIGS_FROM_OSST,
{NULL, }};
/* If the device signature is on the list of incompatible drives, the
function returns a pointer to the name of the correct driver (if known) */
static char * st_incompatible(struct scsi_device* SDp)
{
struct st_reject_data *rp;
for (rp=&(reject_list[0]); rp->vendor != NULL; rp++)
if (!strncmp(rp->vendor, SDp->vendor, strlen(rp->vendor)) &&
!strncmp(rp->model, SDp->model, strlen(rp->model)) &&
!strncmp(rp->rev, SDp->rev, strlen(rp->rev))) {
if (rp->driver_hint)
return rp->driver_hint;
else
return "unknown";
}
return NULL;
}
static inline char *tape_name(struct scsi_tape *tape)
{
return tape->disk->disk_name;
}
static void st_analyze_sense(struct st_request *SRpnt, struct st_cmdstatus *s)
{
const u8 *ucp;
const u8 *sense = SRpnt->sense;
s->have_sense = scsi_normalize_sense(SRpnt->sense,
SCSI_SENSE_BUFFERSIZE, &s->sense_hdr);
s->flags = 0;
if (s->have_sense) {
s->deferred = 0;
s->remainder_valid =
scsi_get_sense_info_fld(sense, SCSI_SENSE_BUFFERSIZE, &s->uremainder64);
switch (sense[0] & 0x7f) {
case 0x71:
s->deferred = 1;
case 0x70:
s->fixed_format = 1;
s->flags = sense[2] & 0xe0;
break;
case 0x73:
s->deferred = 1;
case 0x72:
s->fixed_format = 0;
ucp = scsi_sense_desc_find(sense, SCSI_SENSE_BUFFERSIZE, 4);
s->flags = ucp ? (ucp[3] & 0xe0) : 0;
break;
}
}
}
/* Convert the result to success code */
static int st_chk_result(struct scsi_tape *STp, struct st_request * SRpnt)
{
int result = SRpnt->result;
u8 scode;
DEB(const char *stp;)
char *name = tape_name(STp);
struct st_cmdstatus *cmdstatp;
if (!result)
return 0;
cmdstatp = &STp->buffer->cmdstat;
st_analyze_sense(SRpnt, cmdstatp);
if (cmdstatp->have_sense)
scode = STp->buffer->cmdstat.sense_hdr.sense_key;
else
scode = 0;
DEB(
if (debugging) {
printk(ST_DEB_MSG "%s: Error: %x, cmd: %x %x %x %x %x %x\n",
name, result,
SRpnt->cmd[0], SRpnt->cmd[1], SRpnt->cmd[2],
SRpnt->cmd[3], SRpnt->cmd[4], SRpnt->cmd[5]);
if (cmdstatp->have_sense)
__scsi_print_sense(name, SRpnt->sense, SCSI_SENSE_BUFFERSIZE);
} ) /* end DEB */
if (!debugging) { /* Abnormal conditions for tape */
if (!cmdstatp->have_sense)
printk(KERN_WARNING
"%s: Error %x (driver bt 0x%x, host bt 0x%x).\n",
name, result, driver_byte(result),
host_byte(result));
else if (cmdstatp->have_sense &&
scode != NO_SENSE &&
scode != RECOVERED_ERROR &&
/* scode != UNIT_ATTENTION && */
scode != BLANK_CHECK &&
scode != VOLUME_OVERFLOW &&
SRpnt->cmd[0] != MODE_SENSE &&
SRpnt->cmd[0] != TEST_UNIT_READY) {
__scsi_print_sense(name, SRpnt->sense, SCSI_SENSE_BUFFERSIZE);
}
}
if (cmdstatp->fixed_format &&
STp->cln_mode >= EXTENDED_SENSE_START) { /* Only fixed format sense */
if (STp->cln_sense_value)
STp->cleaning_req |= ((SRpnt->sense[STp->cln_mode] &
STp->cln_sense_mask) == STp->cln_sense_value);
else
STp->cleaning_req |= ((SRpnt->sense[STp->cln_mode] &
STp->cln_sense_mask) != 0);
}
if (cmdstatp->have_sense &&
cmdstatp->sense_hdr.asc == 0 && cmdstatp->sense_hdr.ascq == 0x17)
STp->cleaning_req = 1; /* ASC and ASCQ => cleaning requested */
STp->pos_unknown |= STp->device->was_reset;
if (cmdstatp->have_sense &&
scode == RECOVERED_ERROR
#if ST_RECOVERED_WRITE_FATAL
&& SRpnt->cmd[0] != WRITE_6
&& SRpnt->cmd[0] != WRITE_FILEMARKS
#endif
) {
STp->recover_count++;
STp->recover_reg++;
DEB(
if (debugging) {
if (SRpnt->cmd[0] == READ_6)
stp = "read";
else if (SRpnt->cmd[0] == WRITE_6)
stp = "write";
else
stp = "ioctl";
printk(ST_DEB_MSG "%s: Recovered %s error (%d).\n", name, stp,
STp->recover_count);
} ) /* end DEB */
if (cmdstatp->flags == 0)
return 0;
}
return (-EIO);
}
static struct st_request *st_allocate_request(struct scsi_tape *stp)
{
struct st_request *streq;
streq = kzalloc(sizeof(*streq), GFP_KERNEL);
if (streq)
streq->stp = stp;
else {
DEBC(printk(KERN_ERR "%s: Can't get SCSI request.\n",
tape_name(stp)););
if (signal_pending(current))
stp->buffer->syscall_result = -EINTR;
else
stp->buffer->syscall_result = -EBUSY;
}
return streq;
}
static void st_release_request(struct st_request *streq)
{
kfree(streq);
}
static void st_scsi_execute_end(struct request *req, int uptodate)
{
struct st_request *SRpnt = req->end_io_data;
struct scsi_tape *STp = SRpnt->stp;
struct bio *tmp;
STp->buffer->cmdstat.midlevel_result = SRpnt->result = req->errors;
STp->buffer->cmdstat.residual = req->resid_len;
tmp = SRpnt->bio;
if (SRpnt->waiting)
complete(SRpnt->waiting);
blk_rq_unmap_user(tmp);
__blk_put_request(req->q, req);
}
static int st_scsi_execute(struct st_request *SRpnt, const unsigned char *cmd,
int data_direction, void *buffer, unsigned bufflen,
int timeout, int retries)
{
struct request *req;
struct rq_map_data *mdata = &SRpnt->stp->buffer->map_data;
int err = 0;
int write = (data_direction == DMA_TO_DEVICE);
req = blk_get_request(SRpnt->stp->device->request_queue, write,
GFP_KERNEL);
if (!req)
return DRIVER_ERROR << 24;
req->cmd_type = REQ_TYPE_BLOCK_PC;
req->cmd_flags |= REQ_QUIET;
mdata->null_mapped = 1;
if (bufflen) {
err = blk_rq_map_user(req->q, req, mdata, NULL, bufflen,
GFP_KERNEL);
if (err) {
blk_put_request(req);
return DRIVER_ERROR << 24;
}
}
SRpnt->bio = req->bio;
req->cmd_len = COMMAND_SIZE(cmd[0]);
memset(req->cmd, 0, BLK_MAX_CDB);
memcpy(req->cmd, cmd, req->cmd_len);
req->sense = SRpnt->sense;
req->sense_len = 0;
req->timeout = timeout;
req->retries = retries;
req->end_io_data = SRpnt;
blk_execute_rq_nowait(req->q, NULL, req, 1, st_scsi_execute_end);
return 0;
}
/* Do the scsi command. Waits until command performed if do_wait is true.
Otherwise write_behind_check() is used to check that the command
has finished. */
static struct st_request *
st_do_scsi(struct st_request * SRpnt, struct scsi_tape * STp, unsigned char *cmd,
int bytes, int direction, int timeout, int retries, int do_wait)
{
struct completion *waiting;
struct rq_map_data *mdata = &STp->buffer->map_data;
int ret;
/* if async, make sure there's no command outstanding */
if (!do_wait && ((STp->buffer)->last_SRpnt)) {
printk(KERN_ERR "%s: Async command already active.\n",
tape_name(STp));
if (signal_pending(current))
(STp->buffer)->syscall_result = (-EINTR);
else
(STp->buffer)->syscall_result = (-EBUSY);
return NULL;
}
if (!SRpnt) {
SRpnt = st_allocate_request(STp);
if (!SRpnt)
return NULL;
}
/* If async IO, set last_SRpnt. This ptr tells write_behind_check
which IO is outstanding. It's nulled out when the IO completes. */
if (!do_wait)
(STp->buffer)->last_SRpnt = SRpnt;
waiting = &STp->wait;
init_completion(waiting);
SRpnt->waiting = waiting;
if (STp->buffer->do_dio) {
mdata->page_order = 0;
mdata->nr_entries = STp->buffer->sg_segs;
mdata->pages = STp->buffer->mapped_pages;
} else {
mdata->page_order = STp->buffer->reserved_page_order;
mdata->nr_entries =
DIV_ROUND_UP(bytes, PAGE_SIZE << mdata->page_order);
mdata->pages = STp->buffer->reserved_pages;
mdata->offset = 0;
}
memcpy(SRpnt->cmd, cmd, sizeof(SRpnt->cmd));
STp->buffer->cmdstat.have_sense = 0;
STp->buffer->syscall_result = 0;
ret = st_scsi_execute(SRpnt, cmd, direction, NULL, bytes, timeout,
retries);
if (ret) {
/* could not allocate the buffer or request was too large */
(STp->buffer)->syscall_result = (-EBUSY);
(STp->buffer)->last_SRpnt = NULL;
} else if (do_wait) {
wait_for_completion(waiting);
SRpnt->waiting = NULL;
(STp->buffer)->syscall_result = st_chk_result(STp, SRpnt);
}
return SRpnt;
}
/* Handle the write-behind checking (waits for completion). Returns -ENOSPC if
write has been correct but EOM early warning reached, -EIO if write ended in
error or zero if write successful. Asynchronous writes are used only in
variable block mode. */
static int write_behind_check(struct scsi_tape * STp)
{
int retval = 0;
struct st_buffer *STbuffer;
struct st_partstat *STps;
struct st_cmdstatus *cmdstatp;
struct st_request *SRpnt;
STbuffer = STp->buffer;
if (!STbuffer->writing)
return 0;
DEB(
if (STp->write_pending)
STp->nbr_waits++;
else
STp->nbr_finished++;
) /* end DEB */
wait_for_completion(&(STp->wait));
SRpnt = STbuffer->last_SRpnt;
STbuffer->last_SRpnt = NULL;
SRpnt->waiting = NULL;
(STp->buffer)->syscall_result = st_chk_result(STp, SRpnt);
st_release_request(SRpnt);
STbuffer->buffer_bytes -= STbuffer->writing;
STps = &(STp->ps[STp->partition]);
if (STps->drv_block >= 0) {
if (STp->block_size == 0)
STps->drv_block++;
else
STps->drv_block += STbuffer->writing / STp->block_size;
}
cmdstatp = &STbuffer->cmdstat;
if (STbuffer->syscall_result) {
retval = -EIO;
if (cmdstatp->have_sense && !cmdstatp->deferred &&
(cmdstatp->flags & SENSE_EOM) &&
(cmdstatp->sense_hdr.sense_key == NO_SENSE ||
cmdstatp->sense_hdr.sense_key == RECOVERED_ERROR)) {
/* EOM at write-behind, has all data been written? */
if (!cmdstatp->remainder_valid ||
cmdstatp->uremainder64 == 0)
retval = -ENOSPC;
}
if (retval == -EIO)
STps->drv_block = -1;
}
STbuffer->writing = 0;
DEB(if (debugging && retval)
printk(ST_DEB_MSG "%s: Async write error %x, return value %d.\n",
tape_name(STp), STbuffer->cmdstat.midlevel_result, retval);) /* end DEB */
return retval;
}
/* Step over EOF if it has been inadvertently crossed (ioctl not used because
it messes up the block number). */
static int cross_eof(struct scsi_tape * STp, int forward)
{
struct st_request *SRpnt;
unsigned char cmd[MAX_COMMAND_SIZE];
cmd[0] = SPACE;
cmd[1] = 0x01; /* Space FileMarks */
if (forward) {
cmd[2] = cmd[3] = 0;
cmd[4] = 1;
} else
cmd[2] = cmd[3] = cmd[4] = 0xff; /* -1 filemarks */
cmd[5] = 0;
DEBC(printk(ST_DEB_MSG "%s: Stepping over filemark %s.\n",
tape_name(STp), forward ? "forward" : "backward"));
SRpnt = st_do_scsi(NULL, STp, cmd, 0, DMA_NONE,
STp->device->request_queue->rq_timeout,
MAX_RETRIES, 1);
if (!SRpnt)
return (STp->buffer)->syscall_result;
st_release_request(SRpnt);
SRpnt = NULL;
if ((STp->buffer)->cmdstat.midlevel_result != 0)
printk(KERN_ERR "%s: Stepping over filemark %s failed.\n",
tape_name(STp), forward ? "forward" : "backward");
return (STp->buffer)->syscall_result;
}
/* Flush the write buffer (never need to write if variable blocksize). */
static int st_flush_write_buffer(struct scsi_tape * STp)
{
int transfer, blks;
int result;
unsigned char cmd[MAX_COMMAND_SIZE];
struct st_request *SRpnt;
struct st_partstat *STps;
result = write_behind_check(STp);
if (result)
return result;
result = 0;
if (STp->dirty == 1) {
transfer = STp->buffer->buffer_bytes;
DEBC(printk(ST_DEB_MSG "%s: Flushing %d bytes.\n",
tape_name(STp), transfer));
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_6;
cmd[1] = 1;
blks = transfer / STp->block_size;
cmd[2] = blks >> 16;
cmd[3] = blks >> 8;
cmd[4] = blks;
SRpnt = st_do_scsi(NULL, STp, cmd, transfer, DMA_TO_DEVICE,
STp->device->request_queue->rq_timeout,
MAX_WRITE_RETRIES, 1);
if (!SRpnt)
return (STp->buffer)->syscall_result;
STps = &(STp->ps[STp->partition]);
if ((STp->buffer)->syscall_result != 0) {
struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
if (cmdstatp->have_sense && !cmdstatp->deferred &&
(cmdstatp->flags & SENSE_EOM) &&
(cmdstatp->sense_hdr.sense_key == NO_SENSE ||
cmdstatp->sense_hdr.sense_key == RECOVERED_ERROR) &&
(!cmdstatp->remainder_valid ||
cmdstatp->uremainder64 == 0)) { /* All written at EOM early warning */
STp->dirty = 0;
(STp->buffer)->buffer_bytes = 0;
if (STps->drv_block >= 0)
STps->drv_block += blks;
result = (-ENOSPC);
} else {
printk(KERN_ERR "%s: Error on flush.\n",
tape_name(STp));
STps->drv_block = (-1);
result = (-EIO);
}
} else {
if (STps->drv_block >= 0)
STps->drv_block += blks;
STp->dirty = 0;
(STp->buffer)->buffer_bytes = 0;
}
st_release_request(SRpnt);
SRpnt = NULL;
}
return result;
}
/* Flush the tape buffer. The tape will be positioned correctly unless
seek_next is true. */
static int flush_buffer(struct scsi_tape *STp, int seek_next)
{
int backspace, result;
struct st_buffer *STbuffer;
struct st_partstat *STps;
STbuffer = STp->buffer;
/*
* If there was a bus reset, block further access
* to this device.
*/
if (STp->pos_unknown)
return (-EIO);
if (STp->ready != ST_READY)
return 0;
STps = &(STp->ps[STp->partition]);
if (STps->rw == ST_WRITING) /* Writing */
return st_flush_write_buffer(STp);
if (STp->block_size == 0)
return 0;
backspace = ((STp->buffer)->buffer_bytes +
(STp->buffer)->read_pointer) / STp->block_size -
((STp->buffer)->read_pointer + STp->block_size - 1) /
STp->block_size;
(STp->buffer)->buffer_bytes = 0;
(STp->buffer)->read_pointer = 0;
result = 0;
if (!seek_next) {
if (STps->eof == ST_FM_HIT) {
result = cross_eof(STp, 0); /* Back over the EOF hit */
if (!result)
STps->eof = ST_NOEOF;
else {
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
}
}
if (!result && backspace > 0)
result = st_int_ioctl(STp, MTBSR, backspace);
} else if (STps->eof == ST_FM_HIT) {
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
STps->eof = ST_NOEOF;
}
return result;
}
/* Set the mode parameters */
static int set_mode_densblk(struct scsi_tape * STp, struct st_modedef * STm)
{
int set_it = 0;
unsigned long arg;
char *name = tape_name(STp);
if (!STp->density_changed &&
STm->default_density >= 0 &&
STm->default_density != STp->density) {
arg = STm->default_density;
set_it = 1;
} else
arg = STp->density;
arg <<= MT_ST_DENSITY_SHIFT;
if (!STp->blksize_changed &&
STm->default_blksize >= 0 &&
STm->default_blksize != STp->block_size) {
arg |= STm->default_blksize;
set_it = 1;
} else
arg |= STp->block_size;
if (set_it &&
st_int_ioctl(STp, SET_DENS_AND_BLK, arg)) {
printk(KERN_WARNING
"%s: Can't set default block size to %d bytes and density %x.\n",
name, STm->default_blksize, STm->default_density);
if (modes_defined)
return (-EINVAL);
}
return 0;
}
/* Lock or unlock the drive door. Don't use when st_request allocated. */
static int do_door_lock(struct scsi_tape * STp, int do_lock)
{
int retval, cmd;
DEB(char *name = tape_name(STp);)
cmd = do_lock ? SCSI_IOCTL_DOORLOCK : SCSI_IOCTL_DOORUNLOCK;
DEBC(printk(ST_DEB_MSG "%s: %socking drive door.\n", name,
do_lock ? "L" : "Unl"));
retval = scsi_ioctl(STp->device, cmd, NULL);
if (!retval) {
STp->door_locked = do_lock ? ST_LOCKED_EXPLICIT : ST_UNLOCKED;
}
else {
STp->door_locked = ST_LOCK_FAILS;
}
return retval;
}
/* Set the internal state after reset */
static void reset_state(struct scsi_tape *STp)
{
int i;
struct st_partstat *STps;
STp->pos_unknown = 0;
for (i = 0; i < ST_NBR_PARTITIONS; i++) {
STps = &(STp->ps[i]);
STps->rw = ST_IDLE;
STps->eof = ST_NOEOF;
STps->at_sm = 0;
STps->last_block_valid = 0;
STps->drv_block = -1;
STps->drv_file = -1;
}
if (STp->can_partitions) {
STp->partition = find_partition(STp);
if (STp->partition < 0)
STp->partition = 0;
STp->new_partition = STp->partition;
}
}
/* Test if the drive is ready. Returns either one of the codes below or a negative system
error code. */
#define CHKRES_READY 0
#define CHKRES_NEW_SESSION 1
#define CHKRES_NOT_READY 2
#define CHKRES_NO_TAPE 3
#define MAX_ATTENTIONS 10
static int test_ready(struct scsi_tape *STp, int do_wait)
{
int attentions, waits, max_wait, scode;
int retval = CHKRES_READY, new_session = 0;
unsigned char cmd[MAX_COMMAND_SIZE];
struct st_request *SRpnt = NULL;
struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
max_wait = do_wait ? ST_BLOCK_SECONDS : 0;
for (attentions=waits=0; ; ) {
memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
cmd[0] = TEST_UNIT_READY;
SRpnt = st_do_scsi(SRpnt, STp, cmd, 0, DMA_NONE,
STp->long_timeout, MAX_READY_RETRIES, 1);
if (!SRpnt) {
retval = (STp->buffer)->syscall_result;
break;
}
if (cmdstatp->have_sense) {
scode = cmdstatp->sense_hdr.sense_key;
if (scode == UNIT_ATTENTION) { /* New media? */
new_session = 1;
if (attentions < MAX_ATTENTIONS) {
attentions++;
continue;
}
else {
retval = (-EIO);
break;
}
}
if (scode == NOT_READY) {
if (waits < max_wait) {
if (msleep_interruptible(1000)) {
retval = (-EINTR);
break;
}
waits++;
continue;
}
else {
if ((STp->device)->scsi_level >= SCSI_2 &&
cmdstatp->sense_hdr.asc == 0x3a) /* Check ASC */
retval = CHKRES_NO_TAPE;
else
retval = CHKRES_NOT_READY;
break;
}
}
}
retval = (STp->buffer)->syscall_result;
if (!retval)
retval = new_session ? CHKRES_NEW_SESSION : CHKRES_READY;
break;
}
if (SRpnt != NULL)
st_release_request(SRpnt);
return retval;
}
/* See if the drive is ready and gather information about the tape. Return values:
< 0 negative error code from errno.h
0 drive ready
1 drive not ready (possibly no tape)
*/
static int check_tape(struct scsi_tape *STp, struct file *filp)
{
int i, retval, new_session = 0, do_wait;
unsigned char cmd[MAX_COMMAND_SIZE], saved_cleaning;
unsigned short st_flags = filp->f_flags;
struct st_request *SRpnt = NULL;
struct st_modedef *STm;
struct st_partstat *STps;
char *name = tape_name(STp);
struct inode *inode = filp->f_path.dentry->d_inode;
int mode = TAPE_MODE(inode);
STp->ready = ST_READY;
if (mode != STp->current_mode) {
DEBC(printk(ST_DEB_MSG "%s: Mode change from %d to %d.\n",
name, STp->current_mode, mode));
new_session = 1;
STp->current_mode = mode;
}
STm = &(STp->modes[STp->current_mode]);
saved_cleaning = STp->cleaning_req;
STp->cleaning_req = 0;
do_wait = ((filp->f_flags & O_NONBLOCK) == 0);
retval = test_ready(STp, do_wait);
if (retval < 0)
goto err_out;
if (retval == CHKRES_NEW_SESSION) {
STp->pos_unknown = 0;
STp->partition = STp->new_partition = 0;
if (STp->can_partitions)
STp->nbr_partitions = 1; /* This guess will be updated later
if necessary */
for (i = 0; i < ST_NBR_PARTITIONS; i++) {
STps = &(STp->ps[i]);
STps->rw = ST_IDLE;
STps->eof = ST_NOEOF;
STps->at_sm = 0;
STps->last_block_valid = 0;
STps->drv_block = 0;
STps->drv_file = 0;
}
new_session = 1;
}
else {
STp->cleaning_req |= saved_cleaning;
if (retval == CHKRES_NOT_READY || retval == CHKRES_NO_TAPE) {
if (retval == CHKRES_NO_TAPE)
STp->ready = ST_NO_TAPE;
else
STp->ready = ST_NOT_READY;
STp->density = 0; /* Clear the erroneous "residue" */
STp->write_prot = 0;
STp->block_size = 0;
STp->ps[0].drv_file = STp->ps[0].drv_block = (-1);
STp->partition = STp->new_partition = 0;
STp->door_locked = ST_UNLOCKED;
return CHKRES_NOT_READY;
}
}
if (STp->omit_blklims)
STp->min_block = STp->max_block = (-1);
else {
memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
cmd[0] = READ_BLOCK_LIMITS;
SRpnt = st_do_scsi(SRpnt, STp, cmd, 6, DMA_FROM_DEVICE,
STp->device->request_queue->rq_timeout,
MAX_READY_RETRIES, 1);
if (!SRpnt) {
retval = (STp->buffer)->syscall_result;
goto err_out;
}
if (!SRpnt->result && !STp->buffer->cmdstat.have_sense) {
STp->max_block = ((STp->buffer)->b_data[1] << 16) |
((STp->buffer)->b_data[2] << 8) | (STp->buffer)->b_data[3];
STp->min_block = ((STp->buffer)->b_data[4] << 8) |
(STp->buffer)->b_data[5];
if ( DEB( debugging || ) !STp->inited)
printk(KERN_INFO
"%s: Block limits %d - %d bytes.\n", name,
STp->min_block, STp->max_block);
} else {
STp->min_block = STp->max_block = (-1);
DEBC(printk(ST_DEB_MSG "%s: Can't read block limits.\n",
name));
}
}
memset((void *) &cmd[0], 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SENSE;
cmd[4] = 12;
SRpnt = st_do_scsi(SRpnt, STp, cmd, 12, DMA_FROM_DEVICE,
STp->device->request_queue->rq_timeout,
MAX_READY_RETRIES, 1);
if (!SRpnt) {
retval = (STp->buffer)->syscall_result;
goto err_out;
}
if ((STp->buffer)->syscall_result != 0) {
DEBC(printk(ST_DEB_MSG "%s: No Mode Sense.\n", name));
STp->block_size = ST_DEFAULT_BLOCK; /* Educated guess (?) */
(STp->buffer)->syscall_result = 0; /* Prevent error propagation */
STp->drv_write_prot = 0;
} else {
DEBC(printk(ST_DEB_MSG
"%s: Mode sense. Length %d, medium %x, WBS %x, BLL %d\n",
name,
(STp->buffer)->b_data[0], (STp->buffer)->b_data[1],
(STp->buffer)->b_data[2], (STp->buffer)->b_data[3]));
if ((STp->buffer)->b_data[3] >= 8) {
STp->drv_buffer = ((STp->buffer)->b_data[2] >> 4) & 7;
STp->density = (STp->buffer)->b_data[4];
STp->block_size = (STp->buffer)->b_data[9] * 65536 +
(STp->buffer)->b_data[10] * 256 + (STp->buffer)->b_data[11];
DEBC(printk(ST_DEB_MSG
"%s: Density %x, tape length: %x, drv buffer: %d\n",
name, STp->density, (STp->buffer)->b_data[5] * 65536 +
(STp->buffer)->b_data[6] * 256 + (STp->buffer)->b_data[7],
STp->drv_buffer));
}
STp->drv_write_prot = ((STp->buffer)->b_data[2] & 0x80) != 0;
}
st_release_request(SRpnt);
SRpnt = NULL;
STp->inited = 1;
if (STp->block_size > 0)
(STp->buffer)->buffer_blocks =
(STp->buffer)->buffer_size / STp->block_size;
else
(STp->buffer)->buffer_blocks = 1;
(STp->buffer)->buffer_bytes = (STp->buffer)->read_pointer = 0;
DEBC(printk(ST_DEB_MSG
"%s: Block size: %d, buffer size: %d (%d blocks).\n", name,
STp->block_size, (STp->buffer)->buffer_size,
(STp->buffer)->buffer_blocks));
if (STp->drv_write_prot) {
STp->write_prot = 1;
DEBC(printk(ST_DEB_MSG "%s: Write protected\n", name));
if (do_wait &&
((st_flags & O_ACCMODE) == O_WRONLY ||
(st_flags & O_ACCMODE) == O_RDWR)) {
retval = (-EROFS);
goto err_out;
}
}
if (STp->can_partitions && STp->nbr_partitions < 1) {
/* This code is reached when the device is opened for the first time
after the driver has been initialized with tape in the drive and the
partition support has been enabled. */
DEBC(printk(ST_DEB_MSG
"%s: Updating partition number in status.\n", name));
if ((STp->partition = find_partition(STp)) < 0) {
retval = STp->partition;
goto err_out;
}
STp->new_partition = STp->partition;
STp->nbr_partitions = 1; /* This guess will be updated when necessary */
}
if (new_session) { /* Change the drive parameters for the new mode */
STp->density_changed = STp->blksize_changed = 0;
STp->compression_changed = 0;
if (!(STm->defaults_for_writes) &&
(retval = set_mode_densblk(STp, STm)) < 0)
goto err_out;
if (STp->default_drvbuffer != 0xff) {
if (st_int_ioctl(STp, MTSETDRVBUFFER, STp->default_drvbuffer))
printk(KERN_WARNING
"%s: Can't set default drive buffering to %d.\n",
name, STp->default_drvbuffer);
}
}
return CHKRES_READY;
err_out:
return retval;
}
/* Open the device. Needs to take the BKL only because of incrementing the SCSI host
module count. */
static int st_open(struct inode *inode, struct file *filp)
{
int i, retval = (-EIO);
struct scsi_tape *STp;
struct st_partstat *STps;
int dev = TAPE_NR(inode);
char *name;
mutex_lock(&st_mutex);
/*
* We really want to do nonseekable_open(inode, filp); here, but some
* versions of tar incorrectly call lseek on tapes and bail out if that
* fails. So we disallow pread() and pwrite(), but permit lseeks.
*/
filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
if (!(STp = scsi_tape_get(dev))) {
mutex_unlock(&st_mutex);
return -ENXIO;
}
write_lock(&st_dev_arr_lock);
filp->private_data = STp;
name = tape_name(STp);
if (STp->in_use) {
write_unlock(&st_dev_arr_lock);
scsi_tape_put(STp);
mutex_unlock(&st_mutex);
DEB( printk(ST_DEB_MSG "%s: Device already in use.\n", name); )
return (-EBUSY);
}
STp->in_use = 1;
write_unlock(&st_dev_arr_lock);
STp->rew_at_close = STp->autorew_dev = (iminor(inode) & 0x80) == 0;
if (!scsi_block_when_processing_errors(STp->device)) {
retval = (-ENXIO);
goto err_out;
}
/* See that we have at least a one page buffer available */
if (!enlarge_buffer(STp->buffer, PAGE_SIZE, STp->restr_dma)) {
printk(KERN_WARNING "%s: Can't allocate one page tape buffer.\n",
name);
retval = (-EOVERFLOW);
goto err_out;
}
(STp->buffer)->cleared = 0;
(STp->buffer)->writing = 0;
(STp->buffer)->syscall_result = 0;
STp->write_prot = ((filp->f_flags & O_ACCMODE) == O_RDONLY);
STp->dirty = 0;
for (i = 0; i < ST_NBR_PARTITIONS; i++) {
STps = &(STp->ps[i]);
STps->rw = ST_IDLE;
}
STp->try_dio_now = STp->try_dio;
STp->recover_count = 0;
DEB( STp->nbr_waits = STp->nbr_finished = 0;
STp->nbr_requests = STp->nbr_dio = STp->nbr_pages = 0; )
retval = check_tape(STp, filp);
if (retval < 0)
goto err_out;
if ((filp->f_flags & O_NONBLOCK) == 0 &&
retval != CHKRES_READY) {
if (STp->ready == NO_TAPE)
retval = (-ENOMEDIUM);
else
retval = (-EIO);
goto err_out;
}
mutex_unlock(&st_mutex);
return 0;
err_out:
normalize_buffer(STp->buffer);
STp->in_use = 0;
scsi_tape_put(STp);
mutex_unlock(&st_mutex);
return retval;
}
/* Flush the tape buffer before close */
static int st_flush(struct file *filp, fl_owner_t id)
{
int result = 0, result2;
unsigned char cmd[MAX_COMMAND_SIZE];
struct st_request *SRpnt;
struct scsi_tape *STp = filp->private_data;
struct st_modedef *STm = &(STp->modes[STp->current_mode]);
struct st_partstat *STps = &(STp->ps[STp->partition]);
char *name = tape_name(STp);
if (file_count(filp) > 1)
return 0;
if (STps->rw == ST_WRITING && !STp->pos_unknown) {
result = st_flush_write_buffer(STp);
if (result != 0 && result != (-ENOSPC))
goto out;
}
if (STp->can_partitions &&
(result2 = switch_partition(STp)) < 0) {
DEBC(printk(ST_DEB_MSG
"%s: switch_partition at close failed.\n", name));
if (result == 0)
result = result2;
goto out;
}
DEBC( if (STp->nbr_requests)
printk(KERN_DEBUG "%s: Number of r/w requests %d, dio used in %d, pages %d.\n",
name, STp->nbr_requests, STp->nbr_dio, STp->nbr_pages));
if (STps->rw == ST_WRITING && !STp->pos_unknown) {
struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
DEBC(printk(ST_DEB_MSG "%s: Async write waits %d, finished %d.\n",
name, STp->nbr_waits, STp->nbr_finished);
)
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_FILEMARKS;
cmd[4] = 1 + STp->two_fm;
SRpnt = st_do_scsi(NULL, STp, cmd, 0, DMA_NONE,
STp->device->request_queue->rq_timeout,
MAX_WRITE_RETRIES, 1);
if (!SRpnt) {
result = (STp->buffer)->syscall_result;
goto out;
}
if (STp->buffer->syscall_result == 0 ||
(cmdstatp->have_sense && !cmdstatp->deferred &&
(cmdstatp->flags & SENSE_EOM) &&
(cmdstatp->sense_hdr.sense_key == NO_SENSE ||
cmdstatp->sense_hdr.sense_key == RECOVERED_ERROR) &&
(!cmdstatp->remainder_valid || cmdstatp->uremainder64 == 0))) {
/* Write successful at EOM */
st_release_request(SRpnt);
SRpnt = NULL;
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
if (STp->two_fm)
cross_eof(STp, 0);
STps->eof = ST_FM;
}
else { /* Write error */
st_release_request(SRpnt);
SRpnt = NULL;
printk(KERN_ERR "%s: Error on write filemark.\n", name);
if (result == 0)
result = (-EIO);
}
DEBC(printk(ST_DEB_MSG "%s: Buffer flushed, %d EOF(s) written\n",
name, cmd[4]));
} else if (!STp->rew_at_close) {
STps = &(STp->ps[STp->partition]);
if (!STm->sysv || STps->rw != ST_READING) {
if (STp->can_bsr)
result = flush_buffer(STp, 0);
else if (STps->eof == ST_FM_HIT) {
result = cross_eof(STp, 0);
if (result) {
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
STps->eof = ST_FM;
} else
STps->eof = ST_NOEOF;
}
} else if ((STps->eof == ST_NOEOF &&
!(result = cross_eof(STp, 1))) ||
STps->eof == ST_FM_HIT) {
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
STps->eof = ST_FM;
}
}
out:
if (STp->rew_at_close) {
result2 = st_int_ioctl(STp, MTREW, 1);
if (result == 0)
result = result2;
}
return result;
}
/* Close the device and release it. BKL is not needed: this is the only thread
accessing this tape. */
static int st_release(struct inode *inode, struct file *filp)
{
int result = 0;
struct scsi_tape *STp = filp->private_data;
if (STp->door_locked == ST_LOCKED_AUTO)
do_door_lock(STp, 0);
normalize_buffer(STp->buffer);
write_lock(&st_dev_arr_lock);
STp->in_use = 0;
write_unlock(&st_dev_arr_lock);
scsi_tape_put(STp);
return result;
}
/* The checks common to both reading and writing */
static ssize_t rw_checks(struct scsi_tape *STp, struct file *filp, size_t count)
{
ssize_t retval = 0;
/*
* If we are in the middle of error recovery, don't let anyone
* else try and use this device. Also, if error recovery fails, it
* may try and take the device offline, in which case all further
* access to the device is prohibited.
*/
if (!scsi_block_when_processing_errors(STp->device)) {
retval = (-ENXIO);
goto out;
}
if (STp->ready != ST_READY) {
if (STp->ready == ST_NO_TAPE)
retval = (-ENOMEDIUM);
else
retval = (-EIO);
goto out;
}
if (! STp->modes[STp->current_mode].defined) {
retval = (-ENXIO);
goto out;
}
/*
* If there was a bus reset, block further access
* to this device.
*/
if (STp->pos_unknown) {
retval = (-EIO);
goto out;
}
if (count == 0)
goto out;
DEB(
if (!STp->in_use) {
printk(ST_DEB_MSG "%s: Incorrect device.\n", tape_name(STp));
retval = (-EIO);
goto out;
} ) /* end DEB */
if (STp->can_partitions &&
(retval = switch_partition(STp)) < 0)
goto out;
if (STp->block_size == 0 && STp->max_block > 0 &&
(count < STp->min_block || count > STp->max_block)) {
retval = (-EINVAL);
goto out;
}
if (STp->do_auto_lock && STp->door_locked == ST_UNLOCKED &&
!do_door_lock(STp, 1))
STp->door_locked = ST_LOCKED_AUTO;
out:
return retval;
}
static int setup_buffering(struct scsi_tape *STp, const char __user *buf,
size_t count, int is_read)
{
int i, bufsize, retval = 0;
struct st_buffer *STbp = STp->buffer;
if (is_read)
i = STp->try_dio_now && try_rdio;
else
i = STp->try_dio_now && try_wdio;
if (i && ((unsigned long)buf & queue_dma_alignment(
STp->device->request_queue)) == 0) {
i = sgl_map_user_pages(STbp, STbp->use_sg, (unsigned long)buf,
count, (is_read ? READ : WRITE));
if (i > 0) {
STbp->do_dio = i;
STbp->buffer_bytes = 0; /* can be used as transfer counter */
}
else
STbp->do_dio = 0; /* fall back to buffering with any error */
STbp->sg_segs = STbp->do_dio;
DEB(
if (STbp->do_dio) {
STp->nbr_dio++;
STp->nbr_pages += STbp->do_dio;
}
)
} else
STbp->do_dio = 0;
DEB( STp->nbr_requests++; )
if (!STbp->do_dio) {
if (STp->block_size)
bufsize = STp->block_size > st_fixed_buffer_size ?
STp->block_size : st_fixed_buffer_size;
else {
bufsize = count;
/* Make sure that data from previous user is not leaked even if
HBA does not return correct residual */
if (is_read && STp->sili && !STbp->cleared)
clear_buffer(STbp);
}
if (bufsize > STbp->buffer_size &&
!enlarge_buffer(STbp, bufsize, STp->restr_dma)) {
printk(KERN_WARNING "%s: Can't allocate %d byte tape buffer.\n",
tape_name(STp), bufsize);
retval = (-EOVERFLOW);
goto out;
}
if (STp->block_size)
STbp->buffer_blocks = bufsize / STp->block_size;
}
out:
return retval;
}
/* Can be called more than once after each setup_buffer() */
static void release_buffering(struct scsi_tape *STp, int is_read)
{
struct st_buffer *STbp;
STbp = STp->buffer;
if (STbp->do_dio) {
sgl_unmap_user_pages(STbp, STbp->do_dio, is_read);
STbp->do_dio = 0;
STbp->sg_segs = 0;
}
}
/* Write command */
static ssize_t
st_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
{
ssize_t total;
ssize_t i, do_count, blks, transfer;
ssize_t retval;
int undone, retry_eot = 0, scode;
int async_write;
unsigned char cmd[MAX_COMMAND_SIZE];
const char __user *b_point;
struct st_request *SRpnt = NULL;
struct scsi_tape *STp = filp->private_data;
struct st_modedef *STm;
struct st_partstat *STps;
struct st_buffer *STbp;
char *name = tape_name(STp);
if (mutex_lock_interruptible(&STp->lock))
return -ERESTARTSYS;
retval = rw_checks(STp, filp, count);
if (retval || count == 0)
goto out;
/* Write must be integral number of blocks */
if (STp->block_size != 0 && (count % STp->block_size) != 0) {
printk(KERN_WARNING "%s: Write not multiple of tape block size.\n",
name);
retval = (-EINVAL);
goto out;
}
STm = &(STp->modes[STp->current_mode]);
STps = &(STp->ps[STp->partition]);
if (STp->write_prot) {
retval = (-EACCES);
goto out;
}
if (STps->rw == ST_READING) {
retval = flush_buffer(STp, 0);
if (retval)
goto out;
STps->rw = ST_WRITING;
} else if (STps->rw != ST_WRITING &&
STps->drv_file == 0 && STps->drv_block == 0) {
if ((retval = set_mode_densblk(STp, STm)) < 0)
goto out;
if (STm->default_compression != ST_DONT_TOUCH &&
!(STp->compression_changed)) {
if (st_compression(STp, (STm->default_compression == ST_YES))) {
printk(KERN_WARNING "%s: Can't set default compression.\n",
name);
if (modes_defined) {
retval = (-EINVAL);
goto out;
}
}
}
}
STbp = STp->buffer;
i = write_behind_check(STp);
if (i) {
if (i == -ENOSPC)
STps->eof = ST_EOM_OK;
else
STps->eof = ST_EOM_ERROR;
}
if (STps->eof == ST_EOM_OK) {
STps->eof = ST_EOD_1; /* allow next write */
retval = (-ENOSPC);
goto out;
}
else if (STps->eof == ST_EOM_ERROR) {
retval = (-EIO);
goto out;
}
/* Check the buffer readability in cases where copy_user might catch
the problems after some tape movement. */
if (STp->block_size != 0 &&
!STbp->do_dio &&
(copy_from_user(&i, buf, 1) != 0 ||
copy_from_user(&i, buf + count - 1, 1) != 0)) {
retval = (-EFAULT);
goto out;
}
retval = setup_buffering(STp, buf, count, 0);
if (retval)
goto out;
total = count;
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = WRITE_6;
cmd[1] = (STp->block_size != 0);
STps->rw = ST_WRITING;
b_point = buf;
while (count > 0 && !retry_eot) {
if (STbp->do_dio) {
do_count = count;
}
else {
if (STp->block_size == 0)
do_count = count;
else {
do_count = STbp->buffer_blocks * STp->block_size -
STbp->buffer_bytes;
if (do_count > count)
do_count = count;
}
i = append_to_buffer(b_point, STbp, do_count);
if (i) {
retval = i;
goto out;
}
}
count -= do_count;
b_point += do_count;
async_write = STp->block_size == 0 && !STbp->do_dio &&
STm->do_async_writes && STps->eof < ST_EOM_OK;
if (STp->block_size != 0 && STm->do_buffer_writes &&
!(STp->try_dio_now && try_wdio) && STps->eof < ST_EOM_OK &&
STbp->buffer_bytes < STbp->buffer_size) {
STp->dirty = 1;
/* Don't write a buffer that is not full enough. */
if (!async_write && count == 0)
break;
}
retry_write:
if (STp->block_size == 0)
blks = transfer = do_count;
else {
if (!STbp->do_dio)
blks = STbp->buffer_bytes;
else
blks = do_count;
blks /= STp->block_size;
transfer = blks * STp->block_size;
}
cmd[2] = blks >> 16;
cmd[3] = blks >> 8;
cmd[4] = blks;
SRpnt = st_do_scsi(SRpnt, STp, cmd, transfer, DMA_TO_DEVICE,
STp->device->request_queue->rq_timeout,
MAX_WRITE_RETRIES, !async_write);
if (!SRpnt) {
retval = STbp->syscall_result;
goto out;
}
if (async_write && !STbp->syscall_result) {
STbp->writing = transfer;
STp->dirty = !(STbp->writing ==
STbp->buffer_bytes);
SRpnt = NULL; /* Prevent releasing this request! */
DEB( STp->write_pending = 1; )
break;
}
if (STbp->syscall_result != 0) {
struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
DEBC(printk(ST_DEB_MSG "%s: Error on write:\n", name));
if (cmdstatp->have_sense && (cmdstatp->flags & SENSE_EOM)) {
scode = cmdstatp->sense_hdr.sense_key;
if (cmdstatp->remainder_valid)
undone = (int)cmdstatp->uremainder64;
else if (STp->block_size == 0 &&
scode == VOLUME_OVERFLOW)
undone = transfer;
else
undone = 0;
if (STp->block_size != 0)
undone *= STp->block_size;
if (undone <= do_count) {
/* Only data from this write is not written */
count += undone;
b_point -= undone;
do_count -= undone;
if (STp->block_size)
blks = (transfer - undone) / STp->block_size;
STps->eof = ST_EOM_OK;
/* Continue in fixed block mode if all written
in this request but still something left to write
(retval left to zero)
*/
if (STp->block_size == 0 ||
undone > 0 || count == 0)
retval = (-ENOSPC); /* EOM within current request */
DEBC(printk(ST_DEB_MSG
"%s: EOM with %d bytes unwritten.\n",
name, (int)count));
} else {
/* EOT within data buffered earlier (possible only
in fixed block mode without direct i/o) */
if (!retry_eot && !cmdstatp->deferred &&
(scode == NO_SENSE || scode == RECOVERED_ERROR)) {
move_buffer_data(STp->buffer, transfer - undone);
retry_eot = 1;
if (STps->drv_block >= 0) {
STps->drv_block += (transfer - undone) /
STp->block_size;
}
STps->eof = ST_EOM_OK;
DEBC(printk(ST_DEB_MSG
"%s: Retry write of %d bytes at EOM.\n",
name, STp->buffer->buffer_bytes));
goto retry_write;
}
else {
/* Either error within data buffered by driver or
failed retry */
count -= do_count;
blks = do_count = 0;
STps->eof = ST_EOM_ERROR;
STps->drv_block = (-1); /* Too cautious? */
retval = (-EIO); /* EOM for old data */
DEBC(printk(ST_DEB_MSG
"%s: EOM with lost data.\n",
name));
}
}
} else {
count += do_count;
STps->drv_block = (-1); /* Too cautious? */
retval = STbp->syscall_result;
}
}
if (STps->drv_block >= 0) {
if (STp->block_size == 0)
STps->drv_block += (do_count > 0);
else
STps->drv_block += blks;
}
STbp->buffer_bytes = 0;
STp->dirty = 0;
if (retval || retry_eot) {
if (count < total)
retval = total - count;
goto out;
}
}
if (STps->eof == ST_EOD_1)
STps->eof = ST_EOM_OK;
else if (STps->eof != ST_EOM_OK)
STps->eof = ST_NOEOF;
retval = total - count;
out:
if (SRpnt != NULL)
st_release_request(SRpnt);
release_buffering(STp, 0);
mutex_unlock(&STp->lock);
return retval;
}
/* Read data from the tape. Returns zero in the normal case, one if the
eof status has changed, and the negative error code in case of a
fatal error. Otherwise updates the buffer and the eof state.
Does release user buffer mapping if it is set.
*/
static long read_tape(struct scsi_tape *STp, long count,
struct st_request ** aSRpnt)
{
int transfer, blks, bytes;
unsigned char cmd[MAX_COMMAND_SIZE];
struct st_request *SRpnt;
struct st_modedef *STm;
struct st_partstat *STps;
struct st_buffer *STbp;
int retval = 0;
char *name = tape_name(STp);
if (count == 0)
return 0;
STm = &(STp->modes[STp->current_mode]);
STps = &(STp->ps[STp->partition]);
if (STps->eof == ST_FM_HIT)
return 1;
STbp = STp->buffer;
if (STp->block_size == 0)
blks = bytes = count;
else {
if (!(STp->try_dio_now && try_rdio) && STm->do_read_ahead) {
blks = (STp->buffer)->buffer_blocks;
bytes = blks * STp->block_size;
} else {
bytes = count;
if (!STbp->do_dio && bytes > (STp->buffer)->buffer_size)
bytes = (STp->buffer)->buffer_size;
blks = bytes / STp->block_size;
bytes = blks * STp->block_size;
}
}
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = READ_6;
cmd[1] = (STp->block_size != 0);
if (!cmd[1] && STp->sili)
cmd[1] |= 2;
cmd[2] = blks >> 16;
cmd[3] = blks >> 8;
cmd[4] = blks;
SRpnt = *aSRpnt;
SRpnt = st_do_scsi(SRpnt, STp, cmd, bytes, DMA_FROM_DEVICE,
STp->device->request_queue->rq_timeout,
MAX_RETRIES, 1);
release_buffering(STp, 1);
*aSRpnt = SRpnt;
if (!SRpnt)
return STbp->syscall_result;
STbp->read_pointer = 0;
STps->at_sm = 0;
/* Something to check */
if (STbp->syscall_result) {
struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
retval = 1;
DEBC(printk(ST_DEB_MSG "%s: Sense: %2x %2x %2x %2x %2x %2x %2x %2x\n",
name,
SRpnt->sense[0], SRpnt->sense[1],
SRpnt->sense[2], SRpnt->sense[3],
SRpnt->sense[4], SRpnt->sense[5],
SRpnt->sense[6], SRpnt->sense[7]));
if (cmdstatp->have_sense) {
if (cmdstatp->sense_hdr.sense_key == BLANK_CHECK)
cmdstatp->flags &= 0xcf; /* No need for EOM in this case */
if (cmdstatp->flags != 0) { /* EOF, EOM, or ILI */
/* Compute the residual count */
if (cmdstatp->remainder_valid)
transfer = (int)cmdstatp->uremainder64;
else
transfer = 0;
if (STp->block_size == 0 &&
cmdstatp->sense_hdr.sense_key == MEDIUM_ERROR)
transfer = bytes;
if (cmdstatp->flags & SENSE_ILI) { /* ILI */
if (STp->block_size == 0) {
if (transfer <= 0) {
if (transfer < 0)
printk(KERN_NOTICE
"%s: Failed to read %d byte block with %d byte transfer.\n",
name, bytes - transfer, bytes);
if (STps->drv_block >= 0)
STps->drv_block += 1;
STbp->buffer_bytes = 0;
return (-ENOMEM);
}
STbp->buffer_bytes = bytes - transfer;
} else {
st_release_request(SRpnt);
SRpnt = *aSRpnt = NULL;
if (transfer == blks) { /* We did not get anything, error */
printk(KERN_NOTICE "%s: Incorrect block size.\n", name);
if (STps->drv_block >= 0)
STps->drv_block += blks - transfer + 1;
st_int_ioctl(STp, MTBSR, 1);
return (-EIO);
}
/* We have some data, deliver it */
STbp->buffer_bytes = (blks - transfer) *
STp->block_size;
DEBC(printk(ST_DEB_MSG
"%s: ILI but enough data received %ld %d.\n",
name, count, STbp->buffer_bytes));
if (STps->drv_block >= 0)
STps->drv_block += 1;
if (st_int_ioctl(STp, MTBSR, 1))
return (-EIO);
}
} else if (cmdstatp->flags & SENSE_FMK) { /* FM overrides EOM */
if (STps->eof != ST_FM_HIT)
STps->eof = ST_FM_HIT;
else
STps->eof = ST_EOD_2;
if (STp->block_size == 0)
STbp->buffer_bytes = 0;
else
STbp->buffer_bytes =
bytes - transfer * STp->block_size;
DEBC(printk(ST_DEB_MSG
"%s: EOF detected (%d bytes read).\n",
name, STbp->buffer_bytes));
} else if (cmdstatp->flags & SENSE_EOM) {
if (STps->eof == ST_FM)
STps->eof = ST_EOD_1;
else
STps->eof = ST_EOM_OK;
if (STp->block_size == 0)
STbp->buffer_bytes = bytes - transfer;
else
STbp->buffer_bytes =
bytes - transfer * STp->block_size;
DEBC(printk(ST_DEB_MSG "%s: EOM detected (%d bytes read).\n",
name, STbp->buffer_bytes));
}
}
/* end of EOF, EOM, ILI test */
else { /* nonzero sense key */
DEBC(printk(ST_DEB_MSG
"%s: Tape error while reading.\n", name));
STps->drv_block = (-1);
if (STps->eof == ST_FM &&
cmdstatp->sense_hdr.sense_key == BLANK_CHECK) {
DEBC(printk(ST_DEB_MSG
"%s: Zero returned for first BLANK CHECK after EOF.\n",
name));
STps->eof = ST_EOD_2; /* First BLANK_CHECK after FM */
} else /* Some other extended sense code */
retval = (-EIO);
}
if (STbp->buffer_bytes < 0) /* Caused by bogus sense data */
STbp->buffer_bytes = 0;
}
/* End of extended sense test */
else { /* Non-extended sense */
retval = STbp->syscall_result;
}
}
/* End of error handling */
else { /* Read successful */
STbp->buffer_bytes = bytes;
if (STp->sili) /* In fixed block mode residual is always zero here */
STbp->buffer_bytes -= STp->buffer->cmdstat.residual;
}
if (STps->drv_block >= 0) {
if (STp->block_size == 0)
STps->drv_block++;
else
STps->drv_block += STbp->buffer_bytes / STp->block_size;
}
return retval;
}
/* Read command */
static ssize_t
st_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
{
ssize_t total;
ssize_t retval = 0;
ssize_t i, transfer;
int special, do_dio = 0;
struct st_request *SRpnt = NULL;
struct scsi_tape *STp = filp->private_data;
struct st_modedef *STm;
struct st_partstat *STps;
struct st_buffer *STbp = STp->buffer;
DEB( char *name = tape_name(STp); )
if (mutex_lock_interruptible(&STp->lock))
return -ERESTARTSYS;
retval = rw_checks(STp, filp, count);
if (retval || count == 0)
goto out;
STm = &(STp->modes[STp->current_mode]);
if (STp->block_size != 0 && (count % STp->block_size) != 0) {
if (!STm->do_read_ahead) {
retval = (-EINVAL); /* Read must be integral number of blocks */
goto out;
}
STp->try_dio_now = 0; /* Direct i/o can't handle split blocks */
}
STps = &(STp->ps[STp->partition]);
if (STps->rw == ST_WRITING) {
retval = flush_buffer(STp, 0);
if (retval)
goto out;
STps->rw = ST_READING;
}
DEB(
if (debugging && STps->eof != ST_NOEOF)
printk(ST_DEB_MSG "%s: EOF/EOM flag up (%d). Bytes %d\n", name,
STps->eof, STbp->buffer_bytes);
) /* end DEB */
retval = setup_buffering(STp, buf, count, 1);
if (retval)
goto out;
do_dio = STbp->do_dio;
if (STbp->buffer_bytes == 0 &&
STps->eof >= ST_EOD_1) {
if (STps->eof < ST_EOD) {
STps->eof += 1;
retval = 0;
goto out;
}
retval = (-EIO); /* EOM or Blank Check */
goto out;
}
if (do_dio) {
/* Check the buffer writability before any tape movement. Don't alter
buffer data. */
if (copy_from_user(&i, buf, 1) != 0 ||
copy_to_user(buf, &i, 1) != 0 ||
copy_from_user(&i, buf + count - 1, 1) != 0 ||
copy_to_user(buf + count - 1, &i, 1) != 0) {
retval = (-EFAULT);
goto out;
}
}
STps->rw = ST_READING;
/* Loop until enough data in buffer or a special condition found */
for (total = 0, special = 0; total < count && !special;) {
/* Get new data if the buffer is empty */
if (STbp->buffer_bytes == 0) {
special = read_tape(STp, count - total, &SRpnt);
if (special < 0) { /* No need to continue read */
retval = special;
goto out;
}
}
/* Move the data from driver buffer to user buffer */
if (STbp->buffer_bytes > 0) {
DEB(
if (debugging && STps->eof != ST_NOEOF)
printk(ST_DEB_MSG
"%s: EOF up (%d). Left %d, needed %d.\n", name,
STps->eof, STbp->buffer_bytes,
(int)(count - total));
) /* end DEB */
transfer = STbp->buffer_bytes < count - total ?
STbp->buffer_bytes : count - total;
if (!do_dio) {
i = from_buffer(STbp, buf, transfer);
if (i) {
retval = i;
goto out;
}
}
buf += transfer;
total += transfer;
}
if (STp->block_size == 0)
break; /* Read only one variable length block */
} /* for (total = 0, special = 0;
total < count && !special; ) */
/* Change the eof state if no data from tape or buffer */
if (total == 0) {
if (STps->eof == ST_FM_HIT) {
STps->eof = ST_FM;
STps->drv_block = 0;
if (STps->drv_file >= 0)
STps->drv_file++;
} else if (STps->eof == ST_EOD_1) {
STps->eof = ST_EOD_2;
STps->drv_block = 0;
if (STps->drv_file >= 0)
STps->drv_file++;
} else if (STps->eof == ST_EOD_2)
STps->eof = ST_EOD;
} else if (STps->eof == ST_FM)
STps->eof = ST_NOEOF;
retval = total;
out:
if (SRpnt != NULL) {
st_release_request(SRpnt);
SRpnt = NULL;
}
if (do_dio) {
release_buffering(STp, 1);
STbp->buffer_bytes = 0;
}
mutex_unlock(&STp->lock);
return retval;
}
DEB(
/* Set the driver options */
static void st_log_options(struct scsi_tape * STp, struct st_modedef * STm, char *name)
{
if (debugging) {
printk(KERN_INFO
"%s: Mode %d options: buffer writes: %d, async writes: %d, read ahead: %d\n",
name, STp->current_mode, STm->do_buffer_writes, STm->do_async_writes,
STm->do_read_ahead);
printk(KERN_INFO
"%s: can bsr: %d, two FMs: %d, fast mteom: %d, auto lock: %d,\n",
name, STp->can_bsr, STp->two_fm, STp->fast_mteom, STp->do_auto_lock);
printk(KERN_INFO
"%s: defs for wr: %d, no block limits: %d, partitions: %d, s2 log: %d\n",
name, STm->defaults_for_writes, STp->omit_blklims, STp->can_partitions,
STp->scsi2_logical);
printk(KERN_INFO
"%s: sysv: %d nowait: %d sili: %d\n", name, STm->sysv, STp->immediate,
STp->sili);
printk(KERN_INFO "%s: debugging: %d\n",
name, debugging);
}
}
)
static int st_set_options(struct scsi_tape *STp, long options)
{
int value;
long code;
struct st_modedef *STm;
char *name = tape_name(STp);
struct cdev *cd0, *cd1;
STm = &(STp->modes[STp->current_mode]);
if (!STm->defined) {
cd0 = STm->cdevs[0]; cd1 = STm->cdevs[1];
memcpy(STm, &(STp->modes[0]), sizeof(struct st_modedef));
STm->cdevs[0] = cd0; STm->cdevs[1] = cd1;
modes_defined = 1;
DEBC(printk(ST_DEB_MSG
"%s: Initialized mode %d definition from mode 0\n",
name, STp->current_mode));
}
code = options & MT_ST_OPTIONS;
if (code == MT_ST_BOOLEANS) {
STm->do_buffer_writes = (options & MT_ST_BUFFER_WRITES) != 0;
STm->do_async_writes = (options & MT_ST_ASYNC_WRITES) != 0;
STm->defaults_for_writes = (options & MT_ST_DEF_WRITES) != 0;
STm->do_read_ahead = (options & MT_ST_READ_AHEAD) != 0;
STp->two_fm = (options & MT_ST_TWO_FM) != 0;
STp->fast_mteom = (options & MT_ST_FAST_MTEOM) != 0;
STp->do_auto_lock = (options & MT_ST_AUTO_LOCK) != 0;
STp->can_bsr = (options & MT_ST_CAN_BSR) != 0;
STp->omit_blklims = (options & MT_ST_NO_BLKLIMS) != 0;
if ((STp->device)->scsi_level >= SCSI_2)
STp->can_partitions = (options & MT_ST_CAN_PARTITIONS) != 0;
STp->scsi2_logical = (options & MT_ST_SCSI2LOGICAL) != 0;
STp->immediate = (options & MT_ST_NOWAIT) != 0;
STm->sysv = (options & MT_ST_SYSV) != 0;
STp->sili = (options & MT_ST_SILI) != 0;
DEB( debugging = (options & MT_ST_DEBUGGING) != 0;
st_log_options(STp, STm, name); )
} else if (code == MT_ST_SETBOOLEANS || code == MT_ST_CLEARBOOLEANS) {
value = (code == MT_ST_SETBOOLEANS);
if ((options & MT_ST_BUFFER_WRITES) != 0)
STm->do_buffer_writes = value;
if ((options & MT_ST_ASYNC_WRITES) != 0)
STm->do_async_writes = value;
if ((options & MT_ST_DEF_WRITES) != 0)
STm->defaults_for_writes = value;
if ((options & MT_ST_READ_AHEAD) != 0)
STm->do_read_ahead = value;
if ((options & MT_ST_TWO_FM) != 0)
STp->two_fm = value;
if ((options & MT_ST_FAST_MTEOM) != 0)
STp->fast_mteom = value;
if ((options & MT_ST_AUTO_LOCK) != 0)
STp->do_auto_lock = value;
if ((options & MT_ST_CAN_BSR) != 0)
STp->can_bsr = value;
if ((options & MT_ST_NO_BLKLIMS) != 0)
STp->omit_blklims = value;
if ((STp->device)->scsi_level >= SCSI_2 &&
(options & MT_ST_CAN_PARTITIONS) != 0)
STp->can_partitions = value;
if ((options & MT_ST_SCSI2LOGICAL) != 0)
STp->scsi2_logical = value;
if ((options & MT_ST_NOWAIT) != 0)
STp->immediate = value;
if ((options & MT_ST_SYSV) != 0)
STm->sysv = value;
if ((options & MT_ST_SILI) != 0)
STp->sili = value;
DEB(
if ((options & MT_ST_DEBUGGING) != 0)
debugging = value;
st_log_options(STp, STm, name); )
} else if (code == MT_ST_WRITE_THRESHOLD) {
/* Retained for compatibility */
} else if (code == MT_ST_DEF_BLKSIZE) {
value = (options & ~MT_ST_OPTIONS);
if (value == ~MT_ST_OPTIONS) {
STm->default_blksize = (-1);
DEBC( printk(KERN_INFO "%s: Default block size disabled.\n", name));
} else {
STm->default_blksize = value;
DEBC( printk(KERN_INFO "%s: Default block size set to %d bytes.\n",
name, STm->default_blksize));
if (STp->ready == ST_READY) {
STp->blksize_changed = 0;
set_mode_densblk(STp, STm);
}
}
} else if (code == MT_ST_TIMEOUTS) {
value = (options & ~MT_ST_OPTIONS);
if ((value & MT_ST_SET_LONG_TIMEOUT) != 0) {
STp->long_timeout = (value & ~MT_ST_SET_LONG_TIMEOUT) * HZ;
DEBC( printk(KERN_INFO "%s: Long timeout set to %d seconds.\n", name,
(value & ~MT_ST_SET_LONG_TIMEOUT)));
} else {
blk_queue_rq_timeout(STp->device->request_queue,
value * HZ);
DEBC( printk(KERN_INFO "%s: Normal timeout set to %d seconds.\n",
name, value) );
}
} else if (code == MT_ST_SET_CLN) {
value = (options & ~MT_ST_OPTIONS) & 0xff;
if (value != 0 &&
(value < EXTENDED_SENSE_START ||
value >= SCSI_SENSE_BUFFERSIZE))
return (-EINVAL);
STp->cln_mode = value;
STp->cln_sense_mask = (options >> 8) & 0xff;
STp->cln_sense_value = (options >> 16) & 0xff;
printk(KERN_INFO
"%s: Cleaning request mode %d, mask %02x, value %02x\n",
name, value, STp->cln_sense_mask, STp->cln_sense_value);
} else if (code == MT_ST_DEF_OPTIONS) {
code = (options & ~MT_ST_CLEAR_DEFAULT);
value = (options & MT_ST_CLEAR_DEFAULT);
if (code == MT_ST_DEF_DENSITY) {
if (value == MT_ST_CLEAR_DEFAULT) {
STm->default_density = (-1);
DEBC( printk(KERN_INFO "%s: Density default disabled.\n",
name));
} else {
STm->default_density = value & 0xff;
DEBC( printk(KERN_INFO "%s: Density default set to %x\n",
name, STm->default_density));
if (STp->ready == ST_READY) {
STp->density_changed = 0;
set_mode_densblk(STp, STm);
}
}
} else if (code == MT_ST_DEF_DRVBUFFER) {
if (value == MT_ST_CLEAR_DEFAULT) {
STp->default_drvbuffer = 0xff;
DEBC( printk(KERN_INFO
"%s: Drive buffer default disabled.\n", name));
} else {
STp->default_drvbuffer = value & 7;
DEBC( printk(KERN_INFO
"%s: Drive buffer default set to %x\n",
name, STp->default_drvbuffer));
if (STp->ready == ST_READY)
st_int_ioctl(STp, MTSETDRVBUFFER, STp->default_drvbuffer);
}
} else if (code == MT_ST_DEF_COMPRESSION) {
if (value == MT_ST_CLEAR_DEFAULT) {
STm->default_compression = ST_DONT_TOUCH;
DEBC( printk(KERN_INFO
"%s: Compression default disabled.\n", name));
} else {
if ((value & 0xff00) != 0) {
STp->c_algo = (value & 0xff00) >> 8;
DEBC( printk(KERN_INFO "%s: Compression algorithm set to 0x%x.\n",
name, STp->c_algo));
}
if ((value & 0xff) != 0xff) {
STm->default_compression = (value & 1 ? ST_YES : ST_NO);
DEBC( printk(KERN_INFO "%s: Compression default set to %x\n",
name, (value & 1)));
if (STp->ready == ST_READY) {
STp->compression_changed = 0;
st_compression(STp, (STm->default_compression == ST_YES));
}
}
}
}
} else
return (-EIO);
return 0;
}
#define MODE_HEADER_LENGTH 4
/* Mode header and page byte offsets */
#define MH_OFF_DATA_LENGTH 0
#define MH_OFF_MEDIUM_TYPE 1
#define MH_OFF_DEV_SPECIFIC 2
#define MH_OFF_BDESCS_LENGTH 3
#define MP_OFF_PAGE_NBR 0
#define MP_OFF_PAGE_LENGTH 1
/* Mode header and page bit masks */
#define MH_BIT_WP 0x80
#define MP_MSK_PAGE_NBR 0x3f
/* Don't return block descriptors */
#define MODE_SENSE_OMIT_BDESCS 0x08
#define MODE_SELECT_PAGE_FORMAT 0x10
/* Read a mode page into the tape buffer. The block descriptors are included
if incl_block_descs is true. The page control is ored to the page number
parameter, if necessary. */
static int read_mode_page(struct scsi_tape *STp, int page, int omit_block_descs)
{
unsigned char cmd[MAX_COMMAND_SIZE];
struct st_request *SRpnt;
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SENSE;
if (omit_block_descs)
cmd[1] = MODE_SENSE_OMIT_BDESCS;
cmd[2] = page;
cmd[4] = 255;
SRpnt = st_do_scsi(NULL, STp, cmd, cmd[4], DMA_FROM_DEVICE,
STp->device->request_queue->rq_timeout, 0, 1);
if (SRpnt == NULL)
return (STp->buffer)->syscall_result;
st_release_request(SRpnt);
return STp->buffer->syscall_result;
}
/* Send the mode page in the tape buffer to the drive. Assumes that the mode data
in the buffer is correctly formatted. The long timeout is used if slow is non-zero. */
static int write_mode_page(struct scsi_tape *STp, int page, int slow)
{
int pgo;
unsigned char cmd[MAX_COMMAND_SIZE];
struct st_request *SRpnt;
int timeout;
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = MODE_SELECT;
cmd[1] = MODE_SELECT_PAGE_FORMAT;
pgo = MODE_HEADER_LENGTH + (STp->buffer)->b_data[MH_OFF_BDESCS_LENGTH];
cmd[4] = pgo + (STp->buffer)->b_data[pgo + MP_OFF_PAGE_LENGTH] + 2;
/* Clear reserved fields */
(STp->buffer)->b_data[MH_OFF_DATA_LENGTH] = 0;
(STp->buffer)->b_data[MH_OFF_MEDIUM_TYPE] = 0;
(STp->buffer)->b_data[MH_OFF_DEV_SPECIFIC] &= ~MH_BIT_WP;
(STp->buffer)->b_data[pgo + MP_OFF_PAGE_NBR] &= MP_MSK_PAGE_NBR;
timeout = slow ?
STp->long_timeout : STp->device->request_queue->rq_timeout;
SRpnt = st_do_scsi(NULL, STp, cmd, cmd[4], DMA_TO_DEVICE,
timeout, 0, 1);
if (SRpnt == NULL)
return (STp->buffer)->syscall_result;
st_release_request(SRpnt);
return STp->buffer->syscall_result;
}
#define COMPRESSION_PAGE 0x0f
#define COMPRESSION_PAGE_LENGTH 16
#define CP_OFF_DCE_DCC 2
#define CP_OFF_C_ALGO 7
#define DCE_MASK 0x80
#define DCC_MASK 0x40
#define RED_MASK 0x60
/* Control the compression with mode page 15. Algorithm not changed if zero.
The block descriptors are read and written because Sony SDT-7000 does not
work without this (suggestion from Michael Schaefer <Michael.Schaefer@dlr.de>).
Including block descriptors should not cause any harm to other drives. */
static int st_compression(struct scsi_tape * STp, int state)
{
int retval;
int mpoffs; /* Offset to mode page start */
unsigned char *b_data = (STp->buffer)->b_data;
DEB( char *name = tape_name(STp); )
if (STp->ready != ST_READY)
return (-EIO);
/* Read the current page contents */
retval = read_mode_page(STp, COMPRESSION_PAGE, 0);
if (retval) {
DEBC(printk(ST_DEB_MSG "%s: Compression mode page not supported.\n",
name));
return (-EIO);
}
mpoffs = MODE_HEADER_LENGTH + b_data[MH_OFF_BDESCS_LENGTH];
DEBC(printk(ST_DEB_MSG "%s: Compression state is %d.\n", name,
(b_data[mpoffs + CP_OFF_DCE_DCC] & DCE_MASK ? 1 : 0)));
/* Check if compression can be changed */
if ((b_data[mpoffs + CP_OFF_DCE_DCC] & DCC_MASK) == 0) {
DEBC(printk(ST_DEB_MSG "%s: Compression not supported.\n", name));
return (-EIO);
}
/* Do the change */
if (state) {
b_data[mpoffs + CP_OFF_DCE_DCC] |= DCE_MASK;
if (STp->c_algo != 0)
b_data[mpoffs + CP_OFF_C_ALGO] = STp->c_algo;
}
else {
b_data[mpoffs + CP_OFF_DCE_DCC] &= ~DCE_MASK;
if (STp->c_algo != 0)
b_data[mpoffs + CP_OFF_C_ALGO] = 0; /* no compression */
}
retval = write_mode_page(STp, COMPRESSION_PAGE, 0);
if (retval) {
DEBC(printk(ST_DEB_MSG "%s: Compression change failed.\n", name));
return (-EIO);
}
DEBC(printk(ST_DEB_MSG "%s: Compression state changed to %d.\n",
name, state));
STp->compression_changed = 1;
return 0;
}
/* Process the load and unload commands (does unload if the load code is zero) */
static int do_load_unload(struct scsi_tape *STp, struct file *filp, int load_code)
{
int retval = (-EIO), timeout;
DEB( char *name = tape_name(STp); )
unsigned char cmd[MAX_COMMAND_SIZE];
struct st_partstat *STps;
struct st_request *SRpnt;
if (STp->ready != ST_READY && !load_code) {
if (STp->ready == ST_NO_TAPE)
return (-ENOMEDIUM);
else
return (-EIO);
}
memset(cmd, 0, MAX_COMMAND_SIZE);
cmd[0] = START_STOP;
if (load_code)
cmd[4] |= 1;
/*
* If arg >= 1 && arg <= 6 Enhanced load/unload in HP C1553A
*/
if (load_code >= 1 + MT_ST_HPLOADER_OFFSET
&& load_code <= 6 + MT_ST_HPLOADER_OFFSET) {
DEBC(printk(ST_DEB_MSG "%s: Enhanced %sload slot %2d.\n",
name, (cmd[4]) ? "" : "un",
load_code - MT_ST_HPLOADER_OFFSET));
cmd[3] = load_code - MT_ST_HPLOADER_OFFSET; /* MediaID field of C1553A */
}
if (STp->immediate) {
cmd[1] = 1; /* Don't wait for completion */
timeout = STp->device->request_queue->rq_timeout;
}
else
timeout = STp->long_timeout;
DEBC(
if (!load_code)
printk(ST_DEB_MSG "%s: Unloading tape.\n", name);
else
printk(ST_DEB_MSG "%s: Loading tape.\n", name);
);
SRpnt = st_do_scsi(NULL, STp, cmd, 0, DMA_NONE,
timeout, MAX_RETRIES, 1);
if (!SRpnt)
return (STp->buffer)->syscall_result;
retval = (STp->buffer)->syscall_result;
st_release_request(SRpnt);
if (!retval) { /* SCSI command successful */
if (!load_code) {
STp->rew_at_close = 0;
STp->ready = ST_NO_TAPE;
}
else {
STp->rew_at_close = STp->autorew_dev;
retval = check_tape(STp, filp);
if (retval > 0)
retval = 0;
}
}
else {
STps = &(STp->ps[STp->partition]);
STps->drv_file = STps->drv_block = (-1);
}
return retval;
}
#if DEBUG
#define ST_DEB_FORWARD 0
#define ST_DEB_BACKWARD 1
static void deb_space_print(char *name, int direction, char *units, unsigned char *cmd)
{
s32 sc;
sc = cmd[2] & 0x80 ? 0xff000000 : 0;
sc |= (cmd[2] << 16) | (cmd[3] << 8) | cmd[4];
if (direction)
sc = -sc;
printk(ST_DEB_MSG "%s: Spacing tape %s over %d %s.\n", name,
direction ? "backward" : "forward", sc, units);
}
#endif
/* Internal ioctl function */
static int st_int_ioctl(struct scsi_tape *STp, unsigned int cmd_in, unsigned long arg)
{
int timeout;
long ltmp;
int ioctl_result;
int chg_eof = 1;
unsigned char cmd[MAX_COMMAND_SIZE];
struct st_request *SRpnt;
struct st_partstat *STps;
int fileno, blkno, at_sm, undone;
int datalen = 0, direction = DMA_NONE;
char *name = tape_name(STp);
WARN_ON(STp->buffer->do_dio != 0);
if (STp->ready != ST_READY) {
if (STp->ready == ST_NO_TAPE)
return (-ENOMEDIUM);
else
return (-EIO);
}
timeout = STp->long_timeout;
STps = &(STp->ps[STp->partition]);
fileno = STps->drv_file;
blkno = STps->drv_block;
at_sm = STps->at_sm;
memset(cmd, 0, MAX_COMMAND_SIZE);
switch (cmd_in) {
case MTFSFM:
chg_eof = 0; /* Changed from the FSF after this */
case MTFSF:
cmd[0] = SPACE;
cmd[1] = 0x01; /* Space FileMarks */
cmd[2] = (arg >> 16);
cmd[3] = (arg >> 8);
cmd[4] = arg;
DEBC(deb_space_print(name, ST_DEB_FORWARD, "filemarks", cmd);)
if (fileno >= 0)
fileno += arg;
blkno = 0;
at_sm &= (arg == 0);
break;
case MTBSFM:
chg_eof = 0; /* Changed from the FSF after this */
case MTBSF:
cmd[0] = SPACE;
cmd[1] = 0x01; /* Space FileMarks */
ltmp = (-arg);
cmd[2] = (ltmp >> 16);
cmd[3] = (ltmp >> 8);
cmd[4] = ltmp;
DEBC(deb_space_print(name, ST_DEB_BACKWARD, "filemarks", cmd);)
if (fileno >= 0)
fileno -= arg;
blkno = (-1); /* We can't know the block number */
at_sm &= (arg == 0);
break;
case MTFSR:
cmd[0] = SPACE;
cmd[1] = 0x00; /* Space Blocks */
cmd[2] = (arg >> 16);
cmd[3] = (arg >> 8);
cmd[4] = arg;
DEBC(deb_space_print(name, ST_DEB_FORWARD, "blocks", cmd);)
if (blkno >= 0)
blkno += arg;
at_sm &= (arg == 0);
break;
case MTBSR:
cmd[0] = SPACE;
cmd[1] = 0x00; /* Space Blocks */
ltmp = (-arg);
cmd[2] = (ltmp >> 16);
cmd[3] = (ltmp >> 8);
cmd[4] = ltmp;
DEBC(deb_space_print(name, ST_DEB_BACKWARD, "blocks", cmd);)
if (blkno >= 0)
blkno -= arg;
at_sm &= (arg == 0);
break;
case MTFSS:
cmd[0] = SPACE;
cmd[1] = 0x04; /* Space Setmarks */
cmd[2] = (arg >> 16);
cmd[3] = (arg >> 8);
cmd[4] = arg;
DEBC(deb_space_print(name, ST_DEB_FORWARD, "setmarks", cmd);)
if (arg != 0) {
blkno = fileno = (-1);
at_sm = 1;
}
break;
case MTBSS:
cmd[0] = SPACE;
cmd[1] = 0x04; /* Space Setmarks */
ltmp = (-arg);
cmd[2] = (ltmp >> 16);
cmd[3] = (ltmp >> 8);
cmd[4] = ltmp;
DEBC(deb_space_print(name, ST_DEB_BACKWARD, "setmarks", cmd);)
if (arg != 0) {
blkno = fileno = (-1);
at_sm = 1;
}
break;
case MTWEOF:
case MTWEOFI:
case MTWSM:
if (STp->write_prot)
return (-EACCES);
cmd[0] = WRITE_FILEMARKS;
if (cmd_in == MTWSM)
cmd[1] = 2;
if (cmd_in == MTWEOFI)
cmd[1] |= 1;
cmd[2] = (arg >> 16);
cmd[3] = (arg >> 8);
cmd[4] = arg;
timeout = STp->device->request_queue->rq_timeout;
DEBC(
if (cmd_in != MTWSM)
printk(ST_DEB_MSG "%s: Writing %d filemarks.\n", name,
cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
else
printk(ST_DEB_MSG "%s: Writing %d setmarks.\n", name,
cmd[2] * 65536 + cmd[3] * 256 + cmd[4]);
)
if (fileno >= 0)
fileno += arg;
blkno = 0;
at_sm = (cmd_in == MTWSM);
break;
case MTREW:
cmd[0] = REZERO_UNIT;
if (STp->immediate) {
cmd[1] = 1; /* Don't wait for completion */
timeout = STp->device->request_queue->rq_timeout;
}
DEBC(printk(ST_DEB_MSG "%s: Rewinding tape.\n", name));
fileno = blkno = at_sm = 0;
break;
case MTNOP:
DEBC(printk(ST_DEB_MSG "%s: No op on tape.\n", name));
return 0; /* Should do something ? */
break;
case MTRETEN:
cmd[0] = START_STOP;
if (STp->immediate) {
cmd[1] = 1; /* Don't wait for completion */
timeout = STp->device->request_queue->rq_timeout;
}
cmd[4] = 3;
DEBC(printk(ST_DEB_MSG "%s: Retensioning tape.\n", name));
fileno = blkno = at_sm = 0;
break;
case MTEOM:
if (!STp->fast_mteom) {
/* space to the end of tape */
ioctl_result = st_int_ioctl(STp, MTFSF, 0x7fffff);
fileno = STps->drv_file;
if (STps->eof >= ST_EOD_1)
return 0;
/* The next lines would hide the number of spaced FileMarks
That's why I inserted the previous lines. I had no luck
with detecting EOM with FSF, so we go now to EOM.
Joerg Weule */
} else
fileno = (-1);
cmd[0] = SPACE;
cmd[1] = 3;
DEBC(printk(ST_DEB_MSG "%s: Spacing to end of recorded medium.\n",
name));
blkno = -1;
at_sm = 0;
break;
case MTERASE:
if (STp->write_prot)
return (-EACCES);
cmd[0] = ERASE;
cmd[1] = (arg ? 1 : 0); /* Long erase with non-zero argument */
if (STp->immediate) {
cmd[1] |= 2; /* Don't wait for completion */
timeout = STp->device->request_queue->rq_timeout;
}
else
timeout = STp->long_timeout * 8;
DEBC(printk(ST_DEB_MSG "%s: Erasing tape.\n", name));
fileno = blkno = at_sm = 0;
break;
case MTSETBLK: /* Set block length */
case MTSETDENSITY: /* Set tape density */
case MTSETDRVBUFFER: /* Set drive buffering */
case SET_DENS_AND_BLK: /* Set density and block size */
chg_eof = 0;
if (STp->dirty || (STp->buffer)->buffer_bytes != 0)
return (-EIO); /* Not allowed if data in buffer */
if ((cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) &&
(arg & MT_ST_BLKSIZE_MASK) != 0 &&
STp->max_block > 0 &&
((arg & MT_ST_BLKSIZE_MASK) < STp->min_block ||
(arg & MT_ST_BLKSIZE_MASK) > STp->max_block)) {
printk(KERN_WARNING "%s: Illegal block size.\n", name);
return (-EINVAL);
}
cmd[0] = MODE_SELECT;
if ((STp->use_pf & USE_PF))
cmd[1] = MODE_SELECT_PAGE_FORMAT;
cmd[4] = datalen = 12;
direction = DMA_TO_DEVICE;
memset((STp->buffer)->b_data, 0, 12);
if (cmd_in == MTSETDRVBUFFER)
(STp->buffer)->b_data[2] = (arg & 7) << 4;
else
(STp->buffer)->b_data[2] =
STp->drv_buffer << 4;
(STp->buffer)->b_data[3] = 8; /* block descriptor length */
if (cmd_in == MTSETDENSITY) {
(STp->buffer)->b_data[4] = arg;
STp->density_changed = 1; /* At least we tried ;-) */
} else if (cmd_in == SET_DENS_AND_BLK)
(STp->buffer)->b_data[4] = arg >> 24;
else
(STp->buffer)->b_data[4] = STp->density;
if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) {
ltmp = arg & MT_ST_BLKSIZE_MASK;
if (cmd_in == MTSETBLK)
STp->blksize_changed = 1; /* At least we tried ;-) */
} else
ltmp = STp->block_size;
(STp->buffer)->b_data[9] = (ltmp >> 16);
(STp->buffer)->b_data[10] = (ltmp >> 8);
(STp->buffer)->b_data[11] = ltmp;
timeout = STp->device->request_queue->rq_timeout;
DEBC(
if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK)
printk(ST_DEB_MSG
"%s: Setting block size to %d bytes.\n", name,
(STp->buffer)->b_data[9] * 65536 +
(STp->buffer)->b_data[10] * 256 +
(STp->buffer)->b_data[11]);
if (cmd_in == MTSETDENSITY || cmd_in == SET_DENS_AND_BLK)
printk(ST_DEB_MSG
"%s: Setting density code to %x.\n", name,
(STp->buffer)->b_data[4]);
if (cmd_in == MTSETDRVBUFFER)
printk(ST_DEB_MSG
"%s: Setting drive buffer code to %d.\n", name,
((STp->buffer)->b_data[2] >> 4) & 7);
)
break;
default:
return (-ENOSYS);
}
SRpnt = st_do_scsi(NULL, STp, cmd, datalen, direction,
timeout, MAX_RETRIES, 1);
if (!SRpnt)
return (STp->buffer)->syscall_result;
ioctl_result = (STp->buffer)->syscall_result;
if (!ioctl_result) { /* SCSI command successful */
st_release_request(SRpnt);
SRpnt = NULL;
STps->drv_block = blkno;
STps->drv_file = fileno;
STps->at_sm = at_sm;
if (cmd_in == MTBSFM)
ioctl_result = st_int_ioctl(STp, MTFSF, 1);
else if (cmd_in == MTFSFM)
ioctl_result = st_int_ioctl(STp, MTBSF, 1);
if (cmd_in == MTSETBLK || cmd_in == SET_DENS_AND_BLK) {
STp->block_size = arg & MT_ST_BLKSIZE_MASK;
if (STp->block_size != 0) {
(STp->buffer)->buffer_blocks =
(STp->buffer)->buffer_size / STp->block_size;
}
(STp->buffer)->buffer_bytes = (STp->buffer)->read_pointer = 0;
if (cmd_in == SET_DENS_AND_BLK)
STp->density = arg >> MT_ST_DENSITY_SHIFT;
} else if (cmd_in == MTSETDRVBUFFER)
STp->drv_buffer = (arg & 7);
else if (cmd_in == MTSETDENSITY)
STp->density = arg;
if (cmd_in == MTEOM)
STps->eof = ST_EOD;
else if (cmd_in == MTFSF)
STps->eof = ST_FM;
else if (chg_eof)
STps->eof = ST_NOEOF;
if (cmd_in == MTWEOF || cmd_in == MTWEOFI)
STps->rw = ST_IDLE; /* prevent automatic WEOF at close */
} else { /* SCSI command was not completely successful. Don't return
from this block without releasing the SCSI command block! */
struct st_cmdstatus *cmdstatp = &STp->buffer->cmdstat;
if (cmdstatp->flags & SENSE_EOM) {
if (cmd_in != MTBSF && cmd_in != MTBSFM &&
cmd_in != MTBSR && cmd_in != MTBSS)
STps->eof = ST_EOM_OK;
STps->drv_block = 0;
}
if (cmdstatp->remainder_valid)
undone = (int)cmdstatp->uremainder64;
else
undone = 0;
if ((cmd_in == MTWEOF || cmd_in == MTWEOFI) &&
cmdstatp->have_sense &&
(cmdstatp->flags & SENSE_EOM)) {
if (cmdstatp->sense_hdr.sense_key == NO_SENSE ||
cmdstatp->sense_hdr.sense_key == RECOVERED_ERROR) {
ioctl_result = 0; /* EOF(s) written successfully at EOM */
STps->eof = ST_NOEOF;
} else { /* Writing EOF(s) failed */
if (fileno >= 0)
fileno -= undone;
if (undone < arg)
STps->eof = ST_NOEOF;
}
STps->drv_file = fileno;
} else if ((cmd_in == MTFSF) || (cmd_in == MTFSFM)) {
if (fileno >= 0)
STps->drv_file = fileno - undone;
else
STps->drv_file = fileno;
STps->drv_block = -1;
STps->eof = ST_NOEOF;
} else if ((cmd_in == MTBSF) || (cmd_in == MTBSFM)) {
if (arg > 0 && undone < 0) /* Some drives get this wrong */
undone = (-undone);
if (STps->drv_file >= 0)
STps->drv_file = fileno + undone;
STps->drv_block = 0;
STps->eof = ST_NOEOF;
} else if (cmd_in == MTFSR) {
if (cmdstatp->flags & SENSE_FMK) { /* Hit filemark */
if (STps->drv_file >= 0)
STps->drv_file++;
STps->drv_block = 0;
STps->eof = ST_FM;
} else {
if (blkno >= undone)
STps->drv_block = blkno - undone;
else
STps->drv_block = (-1);
STps->eof = ST_NOEOF;
}
} else if (cmd_in == MTBSR) {
if (cmdstatp->flags & SENSE_FMK) { /* Hit filemark */
STps->drv_file--;
STps->drv_block = (-1);
} else {
if (arg > 0 && undone < 0) /* Some drives get this wrong */
undone = (-undone);
if (STps->drv_block >= 0)
STps->drv_block = blkno + undone;
}
STps->eof = ST_NOEOF;
} else if (cmd_in == MTEOM) {
STps->drv_file = (-1);
STps->drv_block = (-1);
STps->eof = ST_EOD;
} else if (cmd_in == MTSETBLK ||
cmd_in == MTSETDENSITY ||
cmd_in == MTSETDRVBUFFER ||
cmd_in == SET_DENS_AND_BLK) {
if (cmdstatp->sense_hdr.sense_key == ILLEGAL_REQUEST &&
!(STp->use_pf & PF_TESTED)) {
/* Try the other possible state of Page Format if not
already tried */
STp->use_pf = (STp->use_pf ^ USE_PF) | PF_TESTED;
st_release_request(SRpnt);
SRpnt = NULL;
return st_int_ioctl(STp, cmd_in, arg);
}
} else if (chg_eof)
STps->eof = ST_NOEOF;
if (cmdstatp->sense_hdr.sense_key == BLANK_CHECK)
STps->eof = ST_EOD;
st_release_request(SRpnt);
SRpnt = NULL;
}
return ioctl_result;
}
/* Get the tape position. If bt == 2, arg points into a kernel space mt_loc
structure. */
static int get_location(struct scsi_tape *STp, unsigned int *block, int *partition,
int logical)
{
int result;
unsigned char scmd[MAX_COMMAND_SIZE];
struct st_request *SRpnt;
DEB( char *name = tape_name(STp); )
if (STp->ready != ST_READY)
return (-EIO);
memset(scmd, 0, MAX_COMMAND_SIZE);
if ((STp->device)->scsi_level < SCSI_2) {
scmd[0] = QFA_REQUEST_BLOCK;
scmd[4] = 3;
} else {
scmd[0] = READ_POSITION;
if (!logical && !STp->scsi2_logical)
scmd[1] = 1;
}
SRpnt = st_do_scsi(NULL, STp, scmd, 20, DMA_FROM_DEVICE,
STp->device->request_queue->rq_timeout,
MAX_READY_RETRIES, 1);
if (!SRpnt)
return (STp->buffer)->syscall_result;
if ((STp->buffer)->syscall_result != 0 ||
(STp->device->scsi_level >= SCSI_2 &&
((STp->buffer)->b_data[0] & 4) != 0)) {
*block = *partition = 0;
DEBC(printk(ST_DEB_MSG "%s: Can't read tape position.\n", name));
result = (-EIO);
} else {
result = 0;
if ((STp->device)->scsi_level < SCSI_2) {
*block = ((STp->buffer)->b_data[0] << 16)
+ ((STp->buffer)->b_data[1] << 8)
+ (STp->buffer)->b_data[2];
*partition = 0;
} else {
*block = ((STp->buffer)->b_data[4] << 24)
+ ((STp->buffer)->b_data[5] << 16)
+ ((STp->buffer)->b_data[6] << 8)
+ (STp->buffer)->b_data[7];
*partition = (STp->buffer)->b_data[1];
if (((STp->buffer)->b_data[0] & 0x80) &&
(STp->buffer)->b_data[1] == 0) /* BOP of partition 0 */
STp->ps[0].drv_block = STp->ps[0].drv_file = 0;
}
DEBC(printk(ST_DEB_MSG "%s: Got tape pos. blk %d part %d.\n", name,
*block, *partition));
}
st_release_request(SRpnt);
SRpnt = NULL;
return result;
}
/* Set the tape block and partition. Negative partition means that only the
block should be set in vendor specific way. */
static int set_location(struct scsi_tape *STp, unsigned int block, int partition,
int logical)
{
struct st_partstat *STps;
int result, p;
unsigned int blk;
int timeout;
unsigned char scmd[MAX_COMMAND_SIZE];
struct st_request *SRpnt;
DEB( char *name = tape_name(STp); )
if (STp->ready != ST_READY)
return (-EIO);
timeout = STp->long_timeout;
STps = &(STp->ps[STp->partition]);
DEBC(printk(ST_DEB_MSG "%s: Setting block to %d and partition to %d.\n",
name, block, partition));
DEB(if (partition < 0)
return (-EIO); )
/* Update the location at the partition we are leaving */
if ((!STp->can_partitions && partition != 0) ||
partition >= ST_NBR_PARTITIONS)
return (-EINVAL);
if (partition != STp->partition) {
if (get_location(STp, &blk, &p, 1))
STps->last_block_valid = 0;
else {
STps->last_block_valid = 1;
STps->last_block_visited = blk;
DEBC(printk(ST_DEB_MSG
"%s: Visited block %d for partition %d saved.\n",
name, blk, STp->partition));
}
}
memset(scmd, 0, MAX_COMMAND_SIZE);
if ((STp->device)->scsi_level < SCSI_2) {
scmd[0] = QFA_SEEK_BLOCK;
scmd[2] = (block >> 16);
scmd[3] = (block >> 8);
scmd[4] = block;
scmd[5] = 0;
} else {
scmd[0] = SEEK_10;
scmd[3] = (block >> 24);
scmd[4] = (block >> 16);
scmd[5] = (block >> 8);
scmd[6] = block;
if (!logical && !STp->scsi2_logical)
scmd[1] = 4;
if (STp->partition != partition) {
scmd[1] |= 2;
scmd[8] = partition;
DEBC(printk(ST_DEB_MSG
"%s: Trying to change partition from %d to %d\n",
name, STp->partition, partition));
}
}
if (STp->immediate) {
scmd[1] |= 1; /* Don't wait for completion */
timeout = STp->device->request_queue->rq_timeout;
}
SRpnt = st_do_scsi(NULL, STp, scmd, 0, DMA_NONE,
timeout, MAX_READY_RETRIES, 1);
if (!SRpnt)
return (STp->buffer)->syscall_result;
STps->drv_block = STps->drv_file = (-1);
STps->eof = ST_NOEOF;
if ((STp->buffer)->syscall_result != 0) {
result = (-EIO);
if (STp->can_partitions &&
(STp->device)->scsi_level >= SCSI_2 &&
(p = find_partition(STp)) >= 0)
STp->partition = p;
} else {
if (STp->can_partitions) {
STp->partition = partition;
STps = &(STp->ps[partition]);
if (!STps->last_block_valid ||
STps->last_block_visited != block) {
STps->at_sm = 0;
STps->rw = ST_IDLE;
}
} else
STps->at_sm = 0;
if (block == 0)
STps->drv_block = STps->drv_file = 0;
result = 0;
}
st_release_request(SRpnt);
SRpnt = NULL;
return result;
}
/* Find the current partition number for the drive status. Called from open and
returns either partition number of negative error code. */
static int find_partition(struct scsi_tape *STp)
{
int i, partition;
unsigned int block;
if ((i = get_location(STp, &block, &partition, 1)) < 0)
return i;
if (partition >= ST_NBR_PARTITIONS)
return (-EIO);
return partition;
}
/* Change the partition if necessary */
static int switch_partition(struct scsi_tape *STp)
{
struct st_partstat *STps;
if (STp->partition == STp->new_partition)
return 0;
STps = &(STp->ps[STp->new_partition]);
if (!STps->last_block_valid)
STps->last_block_visited = 0;
return set_location(STp, STps->last_block_visited, STp->new_partition, 1);
}
/* Functions for reading and writing the medium partition mode page. */
#define PART_PAGE 0x11
#define PART_PAGE_FIXED_LENGTH 8
#define PP_OFF_MAX_ADD_PARTS 2
#define PP_OFF_NBR_ADD_PARTS 3
#define PP_OFF_FLAGS 4
#define PP_OFF_PART_UNITS 6
#define PP_OFF_RESERVED 7
#define PP_BIT_IDP 0x20
#define PP_MSK_PSUM_MB 0x10
/* Get the number of partitions on the tape. As a side effect reads the
mode page into the tape buffer. */
static int nbr_partitions(struct scsi_tape *STp)
{
int result;
DEB( char *name = tape_name(STp); )
if (STp->ready != ST_READY)
return (-EIO);
result = read_mode_page(STp, PART_PAGE, 1);
if (result) {
DEBC(printk(ST_DEB_MSG "%s: Can't read medium partition page.\n",
name));
result = (-EIO);
} else {
result = (STp->buffer)->b_data[MODE_HEADER_LENGTH +
PP_OFF_NBR_ADD_PARTS] + 1;
DEBC(printk(ST_DEB_MSG "%s: Number of partitions %d.\n", name, result));
}
return result;
}
/* Partition the tape into two partitions if size > 0 or one partition if
size == 0.
The block descriptors are read and written because Sony SDT-7000 does not
work without this (suggestion from Michael Schaefer <Michael.Schaefer@dlr.de>).
My HP C1533A drive returns only one partition size field. This is used to
set the size of partition 1. There is no size field for the default partition.
Michael Schaefer's Sony SDT-7000 returns two descriptors and the second is
used to set the size of partition 1 (this is what the SCSI-3 standard specifies).
The following algorithm is used to accommodate both drives: if the number of
partition size fields is greater than the maximum number of additional partitions
in the mode page, the second field is used. Otherwise the first field is used.
For Seagate DDS drives the page length must be 8 when no partitions is defined
and 10 when 1 partition is defined (information from Eric Lee Green). This is
is acceptable also to some other old drives and enforced if the first partition
size field is used for the first additional partition size.
*/
static int partition_tape(struct scsi_tape *STp, int size)
{
char *name = tape_name(STp);
int result;
int pgo, psd_cnt, psdo;
unsigned char *bp;
result = read_mode_page(STp, PART_PAGE, 0);
if (result) {
DEBC(printk(ST_DEB_MSG "%s: Can't read partition mode page.\n", name));
return result;
}
/* The mode page is in the buffer. Let's modify it and write it. */
bp = (STp->buffer)->b_data;
pgo = MODE_HEADER_LENGTH + bp[MH_OFF_BDESCS_LENGTH];
DEBC(printk(ST_DEB_MSG "%s: Partition page length is %d bytes.\n",
name, bp[pgo + MP_OFF_PAGE_LENGTH] + 2));
psd_cnt = (bp[pgo + MP_OFF_PAGE_LENGTH] + 2 - PART_PAGE_FIXED_LENGTH) / 2;
psdo = pgo + PART_PAGE_FIXED_LENGTH;
if (psd_cnt > bp[pgo + PP_OFF_MAX_ADD_PARTS]) {
bp[psdo] = bp[psdo + 1] = 0xff; /* Rest of the tape */
psdo += 2;
}
memset(bp + psdo, 0, bp[pgo + PP_OFF_NBR_ADD_PARTS] * 2);
DEBC(printk("%s: psd_cnt %d, max.parts %d, nbr_parts %d\n", name,
psd_cnt, bp[pgo + PP_OFF_MAX_ADD_PARTS],
bp[pgo + PP_OFF_NBR_ADD_PARTS]));
if (size <= 0) {
bp[pgo + PP_OFF_NBR_ADD_PARTS] = 0;
if (psd_cnt <= bp[pgo + PP_OFF_MAX_ADD_PARTS])
bp[pgo + MP_OFF_PAGE_LENGTH] = 6;
DEBC(printk(ST_DEB_MSG "%s: Formatting tape with one partition.\n",
name));
} else {
bp[psdo] = (size >> 8) & 0xff;
bp[psdo + 1] = size & 0xff;
bp[pgo + 3] = 1;
if (bp[pgo + MP_OFF_PAGE_LENGTH] < 8)
bp[pgo + MP_OFF_PAGE_LENGTH] = 8;
DEBC(printk(ST_DEB_MSG
"%s: Formatting tape with two partitions (1 = %d MB).\n",
name, size));
}
bp[pgo + PP_OFF_PART_UNITS] = 0;
bp[pgo + PP_OFF_RESERVED] = 0;
bp[pgo + PP_OFF_FLAGS] = PP_BIT_IDP | PP_MSK_PSUM_MB;
result = write_mode_page(STp, PART_PAGE, 1);
if (result) {
printk(KERN_INFO "%s: Partitioning of tape failed.\n", name);
result = (-EIO);
}
return result;
}
/* The ioctl command */
static long st_ioctl(struct file *file, unsigned int cmd_in, unsigned long arg)
{
int i, cmd_nr, cmd_type, bt;
int retval = 0;
unsigned int blk;
struct scsi_tape *STp = file->private_data;
struct st_modedef *STm;
struct st_partstat *STps;
char *name = tape_name(STp);
void __user *p = (void __user *)arg;
if (mutex_lock_interruptible(&STp->lock))
return -ERESTARTSYS;
DEB(
if (debugging && !STp->in_use) {
printk(ST_DEB_MSG "%s: Incorrect device.\n", name);
retval = (-EIO);
goto out;
} ) /* end DEB */
STm = &(STp->modes[STp->current_mode]);
STps = &(STp->ps[STp->partition]);
/*
* If we are in the middle of error recovery, don't let anyone
* else try and use this device. Also, if error recovery fails, it
* may try and take the device offline, in which case all further
* access to the device is prohibited.
*/
retval = scsi_nonblockable_ioctl(STp->device, cmd_in, p,
file->f_flags & O_NDELAY);
if (!scsi_block_when_processing_errors(STp->device) || retval != -ENODEV)
goto out;
retval = 0;
cmd_type = _IOC_TYPE(cmd_in);
cmd_nr = _IOC_NR(cmd_in);
if (cmd_type == _IOC_TYPE(MTIOCTOP) && cmd_nr == _IOC_NR(MTIOCTOP)) {
struct mtop mtc;
if (_IOC_SIZE(cmd_in) != sizeof(mtc)) {
retval = (-EINVAL);
goto out;
}
i = copy_from_user(&mtc, p, sizeof(struct mtop));
if (i) {
retval = (-EFAULT);
goto out;
}
if (mtc.mt_op == MTSETDRVBUFFER && !capable(CAP_SYS_ADMIN)) {
printk(KERN_WARNING
"%s: MTSETDRVBUFFER only allowed for root.\n", name);
retval = (-EPERM);
goto out;
}
if (!STm->defined &&
(mtc.mt_op != MTSETDRVBUFFER &&
(mtc.mt_count & MT_ST_OPTIONS) == 0)) {
retval = (-ENXIO);
goto out;
}
if (!STp->pos_unknown) {
if (STps->eof == ST_FM_HIT) {
if (mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM ||
mtc.mt_op == MTEOM) {
mtc.mt_count -= 1;
if (STps->drv_file >= 0)
STps->drv_file += 1;
} else if (mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM) {
mtc.mt_count += 1;
if (STps->drv_file >= 0)
STps->drv_file += 1;
}
}
if (mtc.mt_op == MTSEEK) {
/* Old position must be restored if partition will be
changed */
i = !STp->can_partitions ||
(STp->new_partition != STp->partition);
} else {
i = mtc.mt_op == MTREW || mtc.mt_op == MTOFFL ||
mtc.mt_op == MTRETEN || mtc.mt_op == MTEOM ||
mtc.mt_op == MTLOCK || mtc.mt_op == MTLOAD ||
mtc.mt_op == MTFSF || mtc.mt_op == MTFSFM ||
mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM ||
mtc.mt_op == MTCOMPRESSION;
}
i = flush_buffer(STp, i);
if (i < 0) {
retval = i;
goto out;
}
if (STps->rw == ST_WRITING &&
(mtc.mt_op == MTREW || mtc.mt_op == MTOFFL ||
mtc.mt_op == MTSEEK ||
mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM)) {
i = st_int_ioctl(STp, MTWEOF, 1);
if (i < 0) {
retval = i;
goto out;
}
if (mtc.mt_op == MTBSF || mtc.mt_op == MTBSFM)
mtc.mt_count++;
STps->rw = ST_IDLE;
}
} else {
/*
* If there was a bus reset, block further access
* to this device. If the user wants to rewind the tape,
* then reset the flag and allow access again.
*/
if (mtc.mt_op != MTREW &&
mtc.mt_op != MTOFFL &&
mtc.mt_op != MTRETEN &&
mtc.mt_op != MTERASE &&
mtc.mt_op != MTSEEK &&
mtc.mt_op != MTEOM) {
retval = (-EIO);
goto out;
}
reset_state(STp);
/* remove this when the midlevel properly clears was_reset */
STp->device->was_reset = 0;
}
if (mtc.mt_op != MTNOP && mtc.mt_op != MTSETBLK &&
mtc.mt_op != MTSETDENSITY && mtc.mt_op != MTWSM &&
mtc.mt_op != MTSETDRVBUFFER && mtc.mt_op != MTSETPART)
STps->rw = ST_IDLE; /* Prevent automatic WEOF and fsf */
if (mtc.mt_op == MTOFFL && STp->door_locked != ST_UNLOCKED)
do_door_lock(STp, 0); /* Ignore result! */
if (mtc.mt_op == MTSETDRVBUFFER &&
(mtc.mt_count & MT_ST_OPTIONS) != 0) {
retval = st_set_options(STp, mtc.mt_count);
goto out;
}
if (mtc.mt_op == MTSETPART) {
if (!STp->can_partitions ||
mtc.mt_count < 0 || mtc.mt_count >= ST_NBR_PARTITIONS) {
retval = (-EINVAL);
goto out;
}
if (mtc.mt_count >= STp->nbr_partitions &&
(STp->nbr_partitions = nbr_partitions(STp)) < 0) {
retval = (-EIO);
goto out;
}
if (mtc.mt_count >= STp->nbr_partitions) {
retval = (-EINVAL);
goto out;
}
STp->new_partition = mtc.mt_count;
retval = 0;
goto out;
}
if (mtc.mt_op == MTMKPART) {
if (!STp->can_partitions) {
retval = (-EINVAL);
goto out;
}
if ((i = st_int_ioctl(STp, MTREW, 0)) < 0 ||
(i = partition_tape(STp, mtc.mt_count)) < 0) {
retval = i;
goto out;
}
for (i = 0; i < ST_NBR_PARTITIONS; i++) {
STp->ps[i].rw = ST_IDLE;
STp->ps[i].at_sm = 0;
STp->ps[i].last_block_valid = 0;
}
STp->partition = STp->new_partition = 0;
STp->nbr_partitions = 1; /* Bad guess ?-) */
STps->drv_block = STps->drv_file = 0;
retval = 0;
goto out;
}
if (mtc.mt_op == MTSEEK) {
i = set_location(STp, mtc.mt_count, STp->new_partition, 0);
if (!STp->can_partitions)
STp->ps[0].rw = ST_IDLE;
retval = i;
goto out;
}
if (mtc.mt_op == MTUNLOAD || mtc.mt_op == MTOFFL) {
retval = do_load_unload(STp, file, 0);
goto out;
}
if (mtc.mt_op == MTLOAD) {
retval = do_load_unload(STp, file, max(1, mtc.mt_count));
goto out;
}
if (mtc.mt_op == MTLOCK || mtc.mt_op == MTUNLOCK) {
retval = do_door_lock(STp, (mtc.mt_op == MTLOCK));
goto out;
}
if (STp->can_partitions && STp->ready == ST_READY &&
(i = switch_partition(STp)) < 0) {
retval = i;
goto out;
}
if (mtc.mt_op == MTCOMPRESSION)
retval = st_compression(STp, (mtc.mt_count & 1));
else
retval = st_int_ioctl(STp, mtc.mt_op, mtc.mt_count);
goto out;
}
if (!STm->defined) {
retval = (-ENXIO);
goto out;
}
if ((i = flush_buffer(STp, 0)) < 0) {
retval = i;
goto out;
}
if (STp->can_partitions &&
(i = switch_partition(STp)) < 0) {
retval = i;
goto out;
}
if (cmd_type == _IOC_TYPE(MTIOCGET) && cmd_nr == _IOC_NR(MTIOCGET)) {
struct mtget mt_status;
if (_IOC_SIZE(cmd_in) != sizeof(struct mtget)) {
retval = (-EINVAL);
goto out;
}
mt_status.mt_type = STp->tape_type;
mt_status.mt_dsreg =
((STp->block_size << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK) |
((STp->density << MT_ST_DENSITY_SHIFT) & MT_ST_DENSITY_MASK);
mt_status.mt_blkno = STps->drv_block;
mt_status.mt_fileno = STps->drv_file;
if (STp->block_size != 0) {
if (STps->rw == ST_WRITING)
mt_status.mt_blkno +=
(STp->buffer)->buffer_bytes / STp->block_size;
else if (STps->rw == ST_READING)
mt_status.mt_blkno -=
((STp->buffer)->buffer_bytes +
STp->block_size - 1) / STp->block_size;
}
mt_status.mt_gstat = 0;
if (STp->drv_write_prot)
mt_status.mt_gstat |= GMT_WR_PROT(0xffffffff);
if (mt_status.mt_blkno == 0) {
if (mt_status.mt_fileno == 0)
mt_status.mt_gstat |= GMT_BOT(0xffffffff);
else
mt_status.mt_gstat |= GMT_EOF(0xffffffff);
}
mt_status.mt_erreg = (STp->recover_reg << MT_ST_SOFTERR_SHIFT);
mt_status.mt_resid = STp->partition;
if (STps->eof == ST_EOM_OK || STps->eof == ST_EOM_ERROR)
mt_status.mt_gstat |= GMT_EOT(0xffffffff);
else if (STps->eof >= ST_EOM_OK)
mt_status.mt_gstat |= GMT_EOD(0xffffffff);
if (STp->density == 1)
mt_status.mt_gstat |= GMT_D_800(0xffffffff);
else if (STp->density == 2)
mt_status.mt_gstat |= GMT_D_1600(0xffffffff);
else if (STp->density == 3)
mt_status.mt_gstat |= GMT_D_6250(0xffffffff);
if (STp->ready == ST_READY)
mt_status.mt_gstat |= GMT_ONLINE(0xffffffff);
if (STp->ready == ST_NO_TAPE)
mt_status.mt_gstat |= GMT_DR_OPEN(0xffffffff);
if (STps->at_sm)
mt_status.mt_gstat |= GMT_SM(0xffffffff);
if (STm->do_async_writes ||
(STm->do_buffer_writes && STp->block_size != 0) ||
STp->drv_buffer != 0)
mt_status.mt_gstat |= GMT_IM_REP_EN(0xffffffff);
if (STp->cleaning_req)
mt_status.mt_gstat |= GMT_CLN(0xffffffff);
i = copy_to_user(p, &mt_status, sizeof(struct mtget));
if (i) {
retval = (-EFAULT);
goto out;
}
STp->recover_reg = 0; /* Clear after read */
retval = 0;
goto out;
} /* End of MTIOCGET */
if (cmd_type == _IOC_TYPE(MTIOCPOS) && cmd_nr == _IOC_NR(MTIOCPOS)) {
struct mtpos mt_pos;
if (_IOC_SIZE(cmd_in) != sizeof(struct mtpos)) {
retval = (-EINVAL);
goto out;
}
if ((i = get_location(STp, &blk, &bt, 0)) < 0) {
retval = i;
goto out;
}
mt_pos.mt_blkno = blk;
i = copy_to_user(p, &mt_pos, sizeof(struct mtpos));
if (i)
retval = (-EFAULT);
goto out;
}
mutex_unlock(&STp->lock);
switch (cmd_in) {
case SCSI_IOCTL_GET_IDLUN:
case SCSI_IOCTL_GET_BUS_NUMBER:
break;
default:
if ((cmd_in == SG_IO ||
cmd_in == SCSI_IOCTL_SEND_COMMAND ||
cmd_in == CDROM_SEND_PACKET) &&
!capable(CAP_SYS_RAWIO))
i = -EPERM;
else
i = scsi_cmd_ioctl(STp->disk->queue, STp->disk,
file->f_mode, cmd_in, p);
if (i != -ENOTTY)
return i;
break;
}
retval = scsi_ioctl(STp->device, cmd_in, p);
if (!retval && cmd_in == SCSI_IOCTL_STOP_UNIT) { /* unload */
STp->rew_at_close = 0;
STp->ready = ST_NO_TAPE;
}
return retval;
out:
mutex_unlock(&STp->lock);
return retval;
}
#ifdef CONFIG_COMPAT
static long st_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct scsi_tape *STp = file->private_data;
struct scsi_device *sdev = STp->device;
int ret = -ENOIOCTLCMD;
if (sdev->host->hostt->compat_ioctl) {
ret = sdev->host->hostt->compat_ioctl(sdev, cmd, (void __user *)arg);
}
return ret;
}
#endif
/* Try to allocate a new tape buffer. Calling function must not hold
dev_arr_lock. */
static struct st_buffer *new_tape_buffer(int need_dma, int max_sg)
{
struct st_buffer *tb;
tb = kzalloc(sizeof(struct st_buffer), GFP_ATOMIC);
if (!tb) {
printk(KERN_NOTICE "st: Can't allocate new tape buffer.\n");
return NULL;
}
tb->frp_segs = 0;
tb->use_sg = max_sg;
tb->dma = need_dma;
tb->buffer_size = 0;
tb->reserved_pages = kzalloc(max_sg * sizeof(struct page *),
GFP_ATOMIC);
if (!tb->reserved_pages) {
kfree(tb);
return NULL;
}
return tb;
}
/* Try to allocate enough space in the tape buffer */
#define ST_MAX_ORDER 6
static int enlarge_buffer(struct st_buffer * STbuffer, int new_size, int need_dma)
{
int segs, nbr, max_segs, b_size, order, got;
gfp_t priority;
if (new_size <= STbuffer->buffer_size)
return 1;
if (STbuffer->buffer_size <= PAGE_SIZE)
normalize_buffer(STbuffer); /* Avoid extra segment */
max_segs = STbuffer->use_sg;
nbr = max_segs - STbuffer->frp_segs;
if (nbr <= 0)
return 0;
priority = GFP_KERNEL | __GFP_NOWARN;
if (need_dma)
priority |= GFP_DMA;
if (STbuffer->cleared)
priority |= __GFP_ZERO;
if (STbuffer->frp_segs) {
order = STbuffer->reserved_page_order;
b_size = PAGE_SIZE << order;
} else {
for (b_size = PAGE_SIZE, order = 0;
order < ST_MAX_ORDER &&
max_segs * (PAGE_SIZE << order) < new_size;
order++, b_size *= 2)
; /* empty */
STbuffer->reserved_page_order = order;
}
if (max_segs * (PAGE_SIZE << order) < new_size) {
if (order == ST_MAX_ORDER)
return 0;
normalize_buffer(STbuffer);
return enlarge_buffer(STbuffer, new_size, need_dma);
}
for (segs = STbuffer->frp_segs, got = STbuffer->buffer_size;
segs < max_segs && got < new_size;) {
struct page *page;
page = alloc_pages(priority, order);
if (!page) {
DEB(STbuffer->buffer_size = got);
normalize_buffer(STbuffer);
return 0;
}
STbuffer->frp_segs += 1;
got += b_size;
STbuffer->buffer_size = got;
STbuffer->reserved_pages[segs] = page;
segs++;
}
STbuffer->b_data = page_address(STbuffer->reserved_pages[0]);
return 1;
}
/* Make sure that no data from previous user is in the internal buffer */
static void clear_buffer(struct st_buffer * st_bp)
{
int i;
for (i=0; i < st_bp->frp_segs; i++)
memset(page_address(st_bp->reserved_pages[i]), 0,
PAGE_SIZE << st_bp->reserved_page_order);
st_bp->cleared = 1;
}
/* Release the extra buffer */
static void normalize_buffer(struct st_buffer * STbuffer)
{
int i, order = STbuffer->reserved_page_order;
for (i = 0; i < STbuffer->frp_segs; i++) {
__free_pages(STbuffer->reserved_pages[i], order);
STbuffer->buffer_size -= (PAGE_SIZE << order);
}
STbuffer->frp_segs = 0;
STbuffer->sg_segs = 0;
STbuffer->reserved_page_order = 0;
STbuffer->map_data.offset = 0;
}
/* Move data from the user buffer to the tape buffer. Returns zero (success) or
negative error code. */
static int append_to_buffer(const char __user *ubp, struct st_buffer * st_bp, int do_count)
{
int i, cnt, res, offset;
int length = PAGE_SIZE << st_bp->reserved_page_order;
for (i = 0, offset = st_bp->buffer_bytes;
i < st_bp->frp_segs && offset >= length; i++)
offset -= length;
if (i == st_bp->frp_segs) { /* Should never happen */
printk(KERN_WARNING "st: append_to_buffer offset overflow.\n");
return (-EIO);
}
for (; i < st_bp->frp_segs && do_count > 0; i++) {
struct page *page = st_bp->reserved_pages[i];
cnt = length - offset < do_count ? length - offset : do_count;
res = copy_from_user(page_address(page) + offset, ubp, cnt);
if (res)
return (-EFAULT);
do_count -= cnt;
st_bp->buffer_bytes += cnt;
ubp += cnt;
offset = 0;
}
if (do_count) /* Should never happen */
return (-EIO);
return 0;
}
/* Move data from the tape buffer to the user buffer. Returns zero (success) or
negative error code. */
static int from_buffer(struct st_buffer * st_bp, char __user *ubp, int do_count)
{
int i, cnt, res, offset;
int length = PAGE_SIZE << st_bp->reserved_page_order;
for (i = 0, offset = st_bp->read_pointer;
i < st_bp->frp_segs && offset >= length; i++)
offset -= length;
if (i == st_bp->frp_segs) { /* Should never happen */
printk(KERN_WARNING "st: from_buffer offset overflow.\n");
return (-EIO);
}
for (; i < st_bp->frp_segs && do_count > 0; i++) {
struct page *page = st_bp->reserved_pages[i];
cnt = length - offset < do_count ? length - offset : do_count;
res = copy_to_user(ubp, page_address(page) + offset, cnt);
if (res)
return (-EFAULT);
do_count -= cnt;
st_bp->buffer_bytes -= cnt;
st_bp->read_pointer += cnt;
ubp += cnt;
offset = 0;
}
if (do_count) /* Should never happen */
return (-EIO);
return 0;
}
/* Move data towards start of buffer */
static void move_buffer_data(struct st_buffer * st_bp, int offset)
{
int src_seg, dst_seg, src_offset = 0, dst_offset;
int count, total;
int length = PAGE_SIZE << st_bp->reserved_page_order;
if (offset == 0)
return;
total=st_bp->buffer_bytes - offset;
for (src_seg=0; src_seg < st_bp->frp_segs; src_seg++) {
src_offset = offset;
if (src_offset < length)
break;
offset -= length;
}
st_bp->buffer_bytes = st_bp->read_pointer = total;
for (dst_seg=dst_offset=0; total > 0; ) {
struct page *dpage = st_bp->reserved_pages[dst_seg];
struct page *spage = st_bp->reserved_pages[src_seg];
count = min(length - dst_offset, length - src_offset);
memmove(page_address(dpage) + dst_offset,
page_address(spage) + src_offset, count);
src_offset += count;
if (src_offset >= length) {
src_seg++;
src_offset = 0;
}
dst_offset += count;
if (dst_offset >= length) {
dst_seg++;
dst_offset = 0;
}
total -= count;
}
}
/* Validate the options from command line or module parameters */
static void validate_options(void)
{
if (buffer_kbs > 0)
st_fixed_buffer_size = buffer_kbs * ST_KILOBYTE;
if (max_sg_segs >= ST_FIRST_SG)
st_max_sg_segs = max_sg_segs;
}
#ifndef MODULE
/* Set the boot options. Syntax is defined in Documenation/scsi/st.txt.
*/
static int __init st_setup(char *str)
{
int i, len, ints[5];
char *stp;
stp = get_options(str, ARRAY_SIZE(ints), ints);
if (ints[0] > 0) {
for (i = 0; i < ints[0] && i < ARRAY_SIZE(parms); i++)
if (parms[i].val)
*parms[i].val = ints[i + 1];
} else {
while (stp != NULL) {
for (i = 0; i < ARRAY_SIZE(parms); i++) {
len = strlen(parms[i].name);
if (!strncmp(stp, parms[i].name, len) &&
(*(stp + len) == ':' || *(stp + len) == '=')) {
if (parms[i].val)
*parms[i].val =
simple_strtoul(stp + len + 1, NULL, 0);
else
printk(KERN_WARNING "st: Obsolete parameter %s\n",
parms[i].name);
break;
}
}
if (i >= ARRAY_SIZE(parms))
printk(KERN_WARNING "st: invalid parameter in '%s'\n",
stp);
stp = strchr(stp, ',');
if (stp)
stp++;
}
}
validate_options();
return 1;
}
__setup("st=", st_setup);
#endif
static const struct file_operations st_fops =
{
.owner = THIS_MODULE,
.read = st_read,
.write = st_write,
.unlocked_ioctl = st_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = st_compat_ioctl,
#endif
.open = st_open,
.flush = st_flush,
.release = st_release,
.llseek = noop_llseek,
};
static int st_probe(struct device *dev)
{
struct scsi_device *SDp = to_scsi_device(dev);
struct gendisk *disk = NULL;
struct cdev *cdev = NULL;
struct scsi_tape *tpnt = NULL;
struct st_modedef *STm;
struct st_partstat *STps;
struct st_buffer *buffer;
int i, j, mode, dev_num, error;
char *stp;
if (SDp->type != TYPE_TAPE)
return -ENODEV;
if ((stp = st_incompatible(SDp))) {
sdev_printk(KERN_INFO, SDp, "Found incompatible tape\n");
printk(KERN_INFO "st: The suggested driver is %s.\n", stp);
return -ENODEV;
}
i = queue_max_segments(SDp->request_queue);
if (st_max_sg_segs < i)
i = st_max_sg_segs;
buffer = new_tape_buffer((SDp->host)->unchecked_isa_dma, i);
if (buffer == NULL) {
printk(KERN_ERR
"st: Can't allocate new tape buffer. Device not attached.\n");
goto out;
}
disk = alloc_disk(1);
if (!disk) {
printk(KERN_ERR "st: out of memory. Device not attached.\n");
goto out_buffer_free;
}
write_lock(&st_dev_arr_lock);
if (st_nr_dev >= st_dev_max) {
struct scsi_tape **tmp_da;
int tmp_dev_max;
tmp_dev_max = max(st_nr_dev * 2, 8);
if (tmp_dev_max > ST_MAX_TAPES)
tmp_dev_max = ST_MAX_TAPES;
if (tmp_dev_max <= st_nr_dev) {
write_unlock(&st_dev_arr_lock);
printk(KERN_ERR "st: Too many tape devices (max. %d).\n",
ST_MAX_TAPES);
goto out_put_disk;
}
tmp_da = kzalloc(tmp_dev_max * sizeof(struct scsi_tape *), GFP_ATOMIC);
if (tmp_da == NULL) {
write_unlock(&st_dev_arr_lock);
printk(KERN_ERR "st: Can't extend device array.\n");
goto out_put_disk;
}
if (scsi_tapes != NULL) {
memcpy(tmp_da, scsi_tapes,
st_dev_max * sizeof(struct scsi_tape *));
kfree(scsi_tapes);
}
scsi_tapes = tmp_da;
st_dev_max = tmp_dev_max;
}
for (i = 0; i < st_dev_max; i++)
if (scsi_tapes[i] == NULL)
break;
if (i >= st_dev_max)
panic("scsi_devices corrupt (st)");
tpnt = kzalloc(sizeof(struct scsi_tape), GFP_ATOMIC);
if (tpnt == NULL) {
write_unlock(&st_dev_arr_lock);
printk(KERN_ERR "st: Can't allocate device descriptor.\n");
goto out_put_disk;
}
kref_init(&tpnt->kref);
tpnt->disk = disk;
sprintf(disk->disk_name, "st%d", i);
disk->private_data = &tpnt->driver;
disk->queue = SDp->request_queue;
tpnt->driver = &st_template;
scsi_tapes[i] = tpnt;
dev_num = i;
tpnt->device = SDp;
if (SDp->scsi_level <= 2)
tpnt->tape_type = MT_ISSCSI1;
else
tpnt->tape_type = MT_ISSCSI2;
tpnt->buffer = buffer;
tpnt->buffer->last_SRpnt = NULL;
tpnt->inited = 0;
tpnt->dirty = 0;
tpnt->in_use = 0;
tpnt->drv_buffer = 1; /* Try buffering if no mode sense */
tpnt->restr_dma = (SDp->host)->unchecked_isa_dma;
tpnt->use_pf = (SDp->scsi_level >= SCSI_2);
tpnt->density = 0;
tpnt->do_auto_lock = ST_AUTO_LOCK;
tpnt->can_bsr = (SDp->scsi_level > 2 ? 1 : ST_IN_FILE_POS); /* BSR mandatory in SCSI3 */
tpnt->can_partitions = 0;
tpnt->two_fm = ST_TWO_FM;
tpnt->fast_mteom = ST_FAST_MTEOM;
tpnt->scsi2_logical = ST_SCSI2LOGICAL;
tpnt->sili = ST_SILI;
tpnt->immediate = ST_NOWAIT;
tpnt->default_drvbuffer = 0xff; /* No forced buffering */
tpnt->partition = 0;
tpnt->new_partition = 0;
tpnt->nbr_partitions = 0;
blk_queue_rq_timeout(tpnt->device->request_queue, ST_TIMEOUT);
tpnt->long_timeout = ST_LONG_TIMEOUT;
tpnt->try_dio = try_direct_io && !SDp->host->unchecked_isa_dma;
for (i = 0; i < ST_NBR_MODES; i++) {
STm = &(tpnt->modes[i]);
STm->defined = 0;
STm->sysv = ST_SYSV;
STm->defaults_for_writes = 0;
STm->do_async_writes = ST_ASYNC_WRITES;
STm->do_buffer_writes = ST_BUFFER_WRITES;
STm->do_read_ahead = ST_READ_AHEAD;
STm->default_compression = ST_DONT_TOUCH;
STm->default_blksize = (-1); /* No forced size */
STm->default_density = (-1); /* No forced density */
}
for (i = 0; i < ST_NBR_PARTITIONS; i++) {
STps = &(tpnt->ps[i]);
STps->rw = ST_IDLE;
STps->eof = ST_NOEOF;
STps->at_sm = 0;
STps->last_block_valid = 0;
STps->drv_block = (-1);
STps->drv_file = (-1);
}
tpnt->current_mode = 0;
tpnt->modes[0].defined = 1;
tpnt->density_changed = tpnt->compression_changed =
tpnt->blksize_changed = 0;
mutex_init(&tpnt->lock);
st_nr_dev++;
write_unlock(&st_dev_arr_lock);
for (mode = 0; mode < ST_NBR_MODES; ++mode) {
STm = &(tpnt->modes[mode]);
for (j=0; j < 2; j++) {
cdev = cdev_alloc();
if (!cdev) {
printk(KERN_ERR
"st%d: out of memory. Device not attached.\n",
dev_num);
goto out_free_tape;
}
cdev->owner = THIS_MODULE;
cdev->ops = &st_fops;
error = cdev_add(cdev,
MKDEV(SCSI_TAPE_MAJOR, TAPE_MINOR(dev_num, mode, j)),
1);
if (error) {
printk(KERN_ERR "st%d: Can't add %s-rewind mode %d\n",
dev_num, j ? "non" : "auto", mode);
printk(KERN_ERR "st%d: Device not attached.\n", dev_num);
goto out_free_tape;
}
STm->cdevs[j] = cdev;
}
error = do_create_class_files(tpnt, dev_num, mode);
if (error)
goto out_free_tape;
}
sdev_printk(KERN_NOTICE, SDp,
"Attached scsi tape %s\n", tape_name(tpnt));
sdev_printk(KERN_INFO, SDp, "%s: try direct i/o: %s (alignment %d B)\n",
tape_name(tpnt), tpnt->try_dio ? "yes" : "no",
queue_dma_alignment(SDp->request_queue) + 1);
return 0;
out_free_tape:
for (mode=0; mode < ST_NBR_MODES; mode++) {
STm = &(tpnt->modes[mode]);
sysfs_remove_link(&tpnt->device->sdev_gendev.kobj,
"tape");
for (j=0; j < 2; j++) {
if (STm->cdevs[j]) {
if (cdev == STm->cdevs[j])
cdev = NULL;
device_destroy(st_sysfs_class,
MKDEV(SCSI_TAPE_MAJOR,
TAPE_MINOR(i, mode, j)));
cdev_del(STm->cdevs[j]);
}
}
}
if (cdev)
cdev_del(cdev);
write_lock(&st_dev_arr_lock);
scsi_tapes[dev_num] = NULL;
st_nr_dev--;
write_unlock(&st_dev_arr_lock);
out_put_disk:
put_disk(disk);
kfree(tpnt);
out_buffer_free:
kfree(buffer);
out:
return -ENODEV;
};
static int st_remove(struct device *dev)
{
struct scsi_device *SDp = to_scsi_device(dev);
struct scsi_tape *tpnt;
int i, j, mode;
write_lock(&st_dev_arr_lock);
for (i = 0; i < st_dev_max; i++) {
tpnt = scsi_tapes[i];
if (tpnt != NULL && tpnt->device == SDp) {
scsi_tapes[i] = NULL;
st_nr_dev--;
write_unlock(&st_dev_arr_lock);
sysfs_remove_link(&tpnt->device->sdev_gendev.kobj,
"tape");
for (mode = 0; mode < ST_NBR_MODES; ++mode) {
for (j=0; j < 2; j++) {
device_destroy(st_sysfs_class,
MKDEV(SCSI_TAPE_MAJOR,
TAPE_MINOR(i, mode, j)));
cdev_del(tpnt->modes[mode].cdevs[j]);
tpnt->modes[mode].cdevs[j] = NULL;
}
}
mutex_lock(&st_ref_mutex);
kref_put(&tpnt->kref, scsi_tape_release);
mutex_unlock(&st_ref_mutex);
return 0;
}
}
write_unlock(&st_dev_arr_lock);
return 0;
}
/**
* scsi_tape_release - Called to free the Scsi_Tape structure
* @kref: pointer to embedded kref
*
* st_ref_mutex must be held entering this routine. Because it is
* called on last put, you should always use the scsi_tape_get()
* scsi_tape_put() helpers which manipulate the semaphore directly
* and never do a direct kref_put().
**/
static void scsi_tape_release(struct kref *kref)
{
struct scsi_tape *tpnt = to_scsi_tape(kref);
struct gendisk *disk = tpnt->disk;
tpnt->device = NULL;
if (tpnt->buffer) {
normalize_buffer(tpnt->buffer);
kfree(tpnt->buffer->reserved_pages);
kfree(tpnt->buffer);
}
disk->private_data = NULL;
put_disk(disk);
kfree(tpnt);
return;
}
static int __init init_st(void)
{
int err;
validate_options();
printk(KERN_INFO "st: Version %s, fixed bufsize %d, s/g segs %d\n",
verstr, st_fixed_buffer_size, st_max_sg_segs);
st_sysfs_class = class_create(THIS_MODULE, "scsi_tape");
if (IS_ERR(st_sysfs_class)) {
printk(KERN_ERR "Unable create sysfs class for SCSI tapes\n");
return PTR_ERR(st_sysfs_class);
}
err = register_chrdev_region(MKDEV(SCSI_TAPE_MAJOR, 0),
ST_MAX_TAPE_ENTRIES, "st");
if (err) {
printk(KERN_ERR "Unable to get major %d for SCSI tapes\n",
SCSI_TAPE_MAJOR);
goto err_class;
}
err = scsi_register_driver(&st_template.gendrv);
if (err)
goto err_chrdev;
err = do_create_sysfs_files();
if (err)
goto err_scsidrv;
return 0;
err_scsidrv:
scsi_unregister_driver(&st_template.gendrv);
err_chrdev:
unregister_chrdev_region(MKDEV(SCSI_TAPE_MAJOR, 0),
ST_MAX_TAPE_ENTRIES);
err_class:
class_destroy(st_sysfs_class);
return err;
}
static void __exit exit_st(void)
{
do_remove_sysfs_files();
scsi_unregister_driver(&st_template.gendrv);
unregister_chrdev_region(MKDEV(SCSI_TAPE_MAJOR, 0),
ST_MAX_TAPE_ENTRIES);
class_destroy(st_sysfs_class);
kfree(scsi_tapes);
printk(KERN_INFO "st: Unloaded.\n");
}
module_init(init_st);
module_exit(exit_st);
/* The sysfs driver interface. Read-only at the moment */
static ssize_t st_try_direct_io_show(struct device_driver *ddp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", try_direct_io);
}
static DRIVER_ATTR(try_direct_io, S_IRUGO, st_try_direct_io_show, NULL);
static ssize_t st_fixed_buffer_size_show(struct device_driver *ddp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", st_fixed_buffer_size);
}
static DRIVER_ATTR(fixed_buffer_size, S_IRUGO, st_fixed_buffer_size_show, NULL);
static ssize_t st_max_sg_segs_show(struct device_driver *ddp, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", st_max_sg_segs);
}
static DRIVER_ATTR(max_sg_segs, S_IRUGO, st_max_sg_segs_show, NULL);
static ssize_t st_version_show(struct device_driver *ddd, char *buf)
{
return snprintf(buf, PAGE_SIZE, "[%s]\n", verstr);
}
static DRIVER_ATTR(version, S_IRUGO, st_version_show, NULL);
static int do_create_sysfs_files(void)
{
struct device_driver *sysfs = &st_template.gendrv;
int err;
err = driver_create_file(sysfs, &driver_attr_try_direct_io);
if (err)
return err;
err = driver_create_file(sysfs, &driver_attr_fixed_buffer_size);
if (err)
goto err_try_direct_io;
err = driver_create_file(sysfs, &driver_attr_max_sg_segs);
if (err)
goto err_attr_fixed_buf;
err = driver_create_file(sysfs, &driver_attr_version);
if (err)
goto err_attr_max_sg;
return 0;
err_attr_max_sg:
driver_remove_file(sysfs, &driver_attr_max_sg_segs);
err_attr_fixed_buf:
driver_remove_file(sysfs, &driver_attr_fixed_buffer_size);
err_try_direct_io:
driver_remove_file(sysfs, &driver_attr_try_direct_io);
return err;
}
static void do_remove_sysfs_files(void)
{
struct device_driver *sysfs = &st_template.gendrv;
driver_remove_file(sysfs, &driver_attr_version);
driver_remove_file(sysfs, &driver_attr_max_sg_segs);
driver_remove_file(sysfs, &driver_attr_fixed_buffer_size);
driver_remove_file(sysfs, &driver_attr_try_direct_io);
}
/* The sysfs simple class interface */
static ssize_t
st_defined_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct st_modedef *STm = dev_get_drvdata(dev);
ssize_t l = 0;
l = snprintf(buf, PAGE_SIZE, "%d\n", STm->defined);
return l;
}
DEVICE_ATTR(defined, S_IRUGO, st_defined_show, NULL);
static ssize_t
st_defblk_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct st_modedef *STm = dev_get_drvdata(dev);
ssize_t l = 0;
l = snprintf(buf, PAGE_SIZE, "%d\n", STm->default_blksize);
return l;
}
DEVICE_ATTR(default_blksize, S_IRUGO, st_defblk_show, NULL);
static ssize_t
st_defdensity_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct st_modedef *STm = dev_get_drvdata(dev);
ssize_t l = 0;
char *fmt;
fmt = STm->default_density >= 0 ? "0x%02x\n" : "%d\n";
l = snprintf(buf, PAGE_SIZE, fmt, STm->default_density);
return l;
}
DEVICE_ATTR(default_density, S_IRUGO, st_defdensity_show, NULL);
static ssize_t
st_defcompression_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct st_modedef *STm = dev_get_drvdata(dev);
ssize_t l = 0;
l = snprintf(buf, PAGE_SIZE, "%d\n", STm->default_compression - 1);
return l;
}
DEVICE_ATTR(default_compression, S_IRUGO, st_defcompression_show, NULL);
static ssize_t
st_options_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct st_modedef *STm = dev_get_drvdata(dev);
struct scsi_tape *STp;
int i, j, options;
ssize_t l = 0;
for (i=0; i < st_dev_max; i++) {
for (j=0; j < ST_NBR_MODES; j++)
if (&scsi_tapes[i]->modes[j] == STm)
break;
if (j < ST_NBR_MODES)
break;
}
if (i == st_dev_max)
return 0; /* should never happen */
STp = scsi_tapes[i];
options = STm->do_buffer_writes ? MT_ST_BUFFER_WRITES : 0;
options |= STm->do_async_writes ? MT_ST_ASYNC_WRITES : 0;
options |= STm->do_read_ahead ? MT_ST_READ_AHEAD : 0;
DEB( options |= debugging ? MT_ST_DEBUGGING : 0 );
options |= STp->two_fm ? MT_ST_TWO_FM : 0;
options |= STp->fast_mteom ? MT_ST_FAST_MTEOM : 0;
options |= STm->defaults_for_writes ? MT_ST_DEF_WRITES : 0;
options |= STp->can_bsr ? MT_ST_CAN_BSR : 0;
options |= STp->omit_blklims ? MT_ST_NO_BLKLIMS : 0;
options |= STp->can_partitions ? MT_ST_CAN_PARTITIONS : 0;
options |= STp->scsi2_logical ? MT_ST_SCSI2LOGICAL : 0;
options |= STm->sysv ? MT_ST_SYSV : 0;
options |= STp->immediate ? MT_ST_NOWAIT : 0;
options |= STp->sili ? MT_ST_SILI : 0;
l = snprintf(buf, PAGE_SIZE, "0x%08x\n", options);
return l;
}
DEVICE_ATTR(options, S_IRUGO, st_options_show, NULL);
static int do_create_class_files(struct scsi_tape *STp, int dev_num, int mode)
{
int i, rew, error;
char name[10];
struct device *st_class_member;
for (rew=0; rew < 2; rew++) {
/* Make sure that the minor numbers corresponding to the four
first modes always get the same names */
i = mode << (4 - ST_NBR_MODE_BITS);
snprintf(name, 10, "%s%s%s", rew ? "n" : "",
STp->disk->disk_name, st_formats[i]);
st_class_member =
device_create(st_sysfs_class, &STp->device->sdev_gendev,
MKDEV(SCSI_TAPE_MAJOR,
TAPE_MINOR(dev_num, mode, rew)),
&STp->modes[mode], "%s", name);
if (IS_ERR(st_class_member)) {
printk(KERN_WARNING "st%d: device_create failed\n",
dev_num);
error = PTR_ERR(st_class_member);
goto out;
}
error = device_create_file(st_class_member,
&dev_attr_defined);
if (error) goto out;
error = device_create_file(st_class_member,
&dev_attr_default_blksize);
if (error) goto out;
error = device_create_file(st_class_member,
&dev_attr_default_density);
if (error) goto out;
error = device_create_file(st_class_member,
&dev_attr_default_compression);
if (error) goto out;
error = device_create_file(st_class_member,
&dev_attr_options);
if (error) goto out;
if (mode == 0 && rew == 0) {
error = sysfs_create_link(&STp->device->sdev_gendev.kobj,
&st_class_member->kobj,
"tape");
if (error) {
printk(KERN_ERR
"st%d: Can't create sysfs link from SCSI device.\n",
dev_num);
goto out;
}
}
}
return 0;
out:
return error;
}
/* The following functions may be useful for a larger audience. */
static int sgl_map_user_pages(struct st_buffer *STbp,
const unsigned int max_pages, unsigned long uaddr,
size_t count, int rw)
{
unsigned long end = (uaddr + count + PAGE_SIZE - 1) >> PAGE_SHIFT;
unsigned long start = uaddr >> PAGE_SHIFT;
const int nr_pages = end - start;
int res, i, j;
struct page **pages;
struct rq_map_data *mdata = &STbp->map_data;
/* User attempted Overflow! */
if ((uaddr + count) < uaddr)
return -EINVAL;
/* Too big */
if (nr_pages > max_pages)
return -ENOMEM;
/* Hmm? */
if (count == 0)
return 0;
if ((pages = kmalloc(max_pages * sizeof(*pages), GFP_KERNEL)) == NULL)
return -ENOMEM;
/* Try to fault in all of the necessary pages */
down_read(¤t->mm->mmap_sem);
/* rw==READ means read from drive, write into memory area */
res = get_user_pages(
current,
current->mm,
uaddr,
nr_pages,
rw == READ,
0, /* don't force */
pages,
NULL);
up_read(¤t->mm->mmap_sem);
/* Errors and no page mapped should return here */
if (res < nr_pages)
goto out_unmap;
for (i=0; i < nr_pages; i++) {
/* FIXME: flush superflous for rw==READ,
* probably wrong function for rw==WRITE
*/
flush_dcache_page(pages[i]);
}
mdata->offset = uaddr & ~PAGE_MASK;
STbp->mapped_pages = pages;
return nr_pages;
out_unmap:
if (res > 0) {
for (j=0; j < res; j++)
page_cache_release(pages[j]);
res = 0;
}
kfree(pages);
return res;
}
/* And unmap them... */
static int sgl_unmap_user_pages(struct st_buffer *STbp,
const unsigned int nr_pages, int dirtied)
{
int i;
for (i=0; i < nr_pages; i++) {
struct page *page = STbp->mapped_pages[i];
if (dirtied)
SetPageDirty(page);
/* FIXME: cache flush missing for rw==READ
* FIXME: call the correct reference counting function
*/
page_cache_release(page);
}
kfree(STbp->mapped_pages);
STbp->mapped_pages = NULL;
return 0;
}
| gpl-2.0 |
skywave/caf-zte-blade | drivers/net/wan/pci200syn.c | 2694 | 11748 | /*
* Goramo PCI200SYN synchronous serial card driver for Linux
*
* Copyright (C) 2002-2008 Krzysztof Halasa <khc@pm.waw.pl>
*
* 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.
*
* For information see <http://www.kernel.org/pub/linux/utils/net/hdlc/>
*
* Sources of information:
* Hitachi HD64572 SCA-II User's Manual
* PLX Technology Inc. PCI9052 Data Book
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/capability.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/fcntl.h>
#include <linux/in.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/moduleparam.h>
#include <linux/netdevice.h>
#include <linux/hdlc.h>
#include <linux/pci.h>
#include <linux/delay.h>
#include <asm/io.h>
#include "hd64572.h"
#undef DEBUG_PKT
#define DEBUG_RINGS
#define PCI200SYN_PLX_SIZE 0x80 /* PLX control window size (128b) */
#define PCI200SYN_SCA_SIZE 0x400 /* SCA window size (1Kb) */
#define MAX_TX_BUFFERS 10
static int pci_clock_freq = 33000000;
#define CLOCK_BASE pci_clock_freq
/*
* PLX PCI9052 local configuration and shared runtime registers.
* This structure can be used to access 9052 registers (memory mapped).
*/
typedef struct {
u32 loc_addr_range[4]; /* 00-0Ch : Local Address Ranges */
u32 loc_rom_range; /* 10h : Local ROM Range */
u32 loc_addr_base[4]; /* 14-20h : Local Address Base Addrs */
u32 loc_rom_base; /* 24h : Local ROM Base */
u32 loc_bus_descr[4]; /* 28-34h : Local Bus Descriptors */
u32 rom_bus_descr; /* 38h : ROM Bus Descriptor */
u32 cs_base[4]; /* 3C-48h : Chip Select Base Addrs */
u32 intr_ctrl_stat; /* 4Ch : Interrupt Control/Status */
u32 init_ctrl; /* 50h : EEPROM ctrl, Init Ctrl, etc */
}plx9052;
typedef struct port_s {
struct napi_struct napi;
struct net_device *netdev;
struct card_s *card;
spinlock_t lock; /* TX lock */
sync_serial_settings settings;
int rxpart; /* partial frame received, next frame invalid*/
unsigned short encoding;
unsigned short parity;
u16 rxin; /* rx ring buffer 'in' pointer */
u16 txin; /* tx ring buffer 'in' and 'last' pointers */
u16 txlast;
u8 rxs, txs, tmc; /* SCA registers */
u8 chan; /* physical port # - 0 or 1 */
}port_t;
typedef struct card_s {
u8 __iomem *rambase; /* buffer memory base (virtual) */
u8 __iomem *scabase; /* SCA memory base (virtual) */
plx9052 __iomem *plxbase;/* PLX registers memory base (virtual) */
u16 rx_ring_buffers; /* number of buffers in a ring */
u16 tx_ring_buffers;
u16 buff_offset; /* offset of first buffer of first channel */
u8 irq; /* interrupt request level */
port_t ports[2];
}card_t;
#define get_port(card, port) (&card->ports[port])
#define sca_flush(card) (sca_in(IER0, card));
static inline void new_memcpy_toio(char __iomem *dest, char *src, int length)
{
int len;
do {
len = length > 256 ? 256 : length;
memcpy_toio(dest, src, len);
dest += len;
src += len;
length -= len;
readb(dest);
} while (len);
}
#undef memcpy_toio
#define memcpy_toio new_memcpy_toio
#include "hd64572.c"
static void pci200_set_iface(port_t *port)
{
card_t *card = port->card;
u16 msci = get_msci(port);
u8 rxs = port->rxs & CLK_BRG_MASK;
u8 txs = port->txs & CLK_BRG_MASK;
sca_out(EXS_TES1, (port->chan ? MSCI1_OFFSET : MSCI0_OFFSET) + EXS,
port->card);
switch(port->settings.clock_type) {
case CLOCK_INT:
rxs |= CLK_BRG; /* BRG output */
txs |= CLK_PIN_OUT | CLK_TX_RXCLK; /* RX clock */
break;
case CLOCK_TXINT:
rxs |= CLK_LINE; /* RXC input */
txs |= CLK_PIN_OUT | CLK_BRG; /* BRG output */
break;
case CLOCK_TXFROMRX:
rxs |= CLK_LINE; /* RXC input */
txs |= CLK_PIN_OUT | CLK_TX_RXCLK; /* RX clock */
break;
default: /* EXTernal clock */
rxs |= CLK_LINE; /* RXC input */
txs |= CLK_PIN_OUT | CLK_LINE; /* TXC input */
break;
}
port->rxs = rxs;
port->txs = txs;
sca_out(rxs, msci + RXS, card);
sca_out(txs, msci + TXS, card);
sca_set_port(port);
}
static int pci200_open(struct net_device *dev)
{
port_t *port = dev_to_port(dev);
int result = hdlc_open(dev);
if (result)
return result;
sca_open(dev);
pci200_set_iface(port);
sca_flush(port->card);
return 0;
}
static int pci200_close(struct net_device *dev)
{
sca_close(dev);
sca_flush(dev_to_port(dev)->card);
hdlc_close(dev);
return 0;
}
static int pci200_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
const size_t size = sizeof(sync_serial_settings);
sync_serial_settings new_line;
sync_serial_settings __user *line = ifr->ifr_settings.ifs_ifsu.sync;
port_t *port = dev_to_port(dev);
#ifdef DEBUG_RINGS
if (cmd == SIOCDEVPRIVATE) {
sca_dump_rings(dev);
return 0;
}
#endif
if (cmd != SIOCWANDEV)
return hdlc_ioctl(dev, ifr, cmd);
switch(ifr->ifr_settings.type) {
case IF_GET_IFACE:
ifr->ifr_settings.type = IF_IFACE_V35;
if (ifr->ifr_settings.size < size) {
ifr->ifr_settings.size = size; /* data size wanted */
return -ENOBUFS;
}
if (copy_to_user(line, &port->settings, size))
return -EFAULT;
return 0;
case IF_IFACE_V35:
case IF_IFACE_SYNC_SERIAL:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&new_line, line, size))
return -EFAULT;
if (new_line.clock_type != CLOCK_EXT &&
new_line.clock_type != CLOCK_TXFROMRX &&
new_line.clock_type != CLOCK_INT &&
new_line.clock_type != CLOCK_TXINT)
return -EINVAL; /* No such clock setting */
if (new_line.loopback != 0 && new_line.loopback != 1)
return -EINVAL;
memcpy(&port->settings, &new_line, size); /* Update settings */
pci200_set_iface(port);
sca_flush(port->card);
return 0;
default:
return hdlc_ioctl(dev, ifr, cmd);
}
}
static void pci200_pci_remove_one(struct pci_dev *pdev)
{
int i;
card_t *card = pci_get_drvdata(pdev);
for (i = 0; i < 2; i++)
if (card->ports[i].card)
unregister_hdlc_device(card->ports[i].netdev);
if (card->irq)
free_irq(card->irq, card);
if (card->rambase)
iounmap(card->rambase);
if (card->scabase)
iounmap(card->scabase);
if (card->plxbase)
iounmap(card->plxbase);
pci_release_regions(pdev);
pci_disable_device(pdev);
pci_set_drvdata(pdev, NULL);
if (card->ports[0].netdev)
free_netdev(card->ports[0].netdev);
if (card->ports[1].netdev)
free_netdev(card->ports[1].netdev);
kfree(card);
}
static const struct net_device_ops pci200_ops = {
.ndo_open = pci200_open,
.ndo_stop = pci200_close,
.ndo_change_mtu = hdlc_change_mtu,
.ndo_start_xmit = hdlc_start_xmit,
.ndo_do_ioctl = pci200_ioctl,
};
static int __devinit pci200_pci_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
card_t *card;
u32 __iomem *p;
int i;
u32 ramsize;
u32 ramphys; /* buffer memory base */
u32 scaphys; /* SCA memory base */
u32 plxphys; /* PLX registers memory base */
i = pci_enable_device(pdev);
if (i)
return i;
i = pci_request_regions(pdev, "PCI200SYN");
if (i) {
pci_disable_device(pdev);
return i;
}
card = kzalloc(sizeof(card_t), GFP_KERNEL);
if (card == NULL) {
printk(KERN_ERR "pci200syn: unable to allocate memory\n");
pci_release_regions(pdev);
pci_disable_device(pdev);
return -ENOBUFS;
}
pci_set_drvdata(pdev, card);
card->ports[0].netdev = alloc_hdlcdev(&card->ports[0]);
card->ports[1].netdev = alloc_hdlcdev(&card->ports[1]);
if (!card->ports[0].netdev || !card->ports[1].netdev) {
printk(KERN_ERR "pci200syn: unable to allocate memory\n");
pci200_pci_remove_one(pdev);
return -ENOMEM;
}
if (pci_resource_len(pdev, 0) != PCI200SYN_PLX_SIZE ||
pci_resource_len(pdev, 2) != PCI200SYN_SCA_SIZE ||
pci_resource_len(pdev, 3) < 16384) {
printk(KERN_ERR "pci200syn: invalid card EEPROM parameters\n");
pci200_pci_remove_one(pdev);
return -EFAULT;
}
plxphys = pci_resource_start(pdev,0) & PCI_BASE_ADDRESS_MEM_MASK;
card->plxbase = ioremap(plxphys, PCI200SYN_PLX_SIZE);
scaphys = pci_resource_start(pdev,2) & PCI_BASE_ADDRESS_MEM_MASK;
card->scabase = ioremap(scaphys, PCI200SYN_SCA_SIZE);
ramphys = pci_resource_start(pdev,3) & PCI_BASE_ADDRESS_MEM_MASK;
card->rambase = pci_ioremap_bar(pdev, 3);
if (card->plxbase == NULL ||
card->scabase == NULL ||
card->rambase == NULL) {
printk(KERN_ERR "pci200syn: ioremap() failed\n");
pci200_pci_remove_one(pdev);
return -EFAULT;
}
/* Reset PLX */
p = &card->plxbase->init_ctrl;
writel(readl(p) | 0x40000000, p);
readl(p); /* Flush the write - do not use sca_flush */
udelay(1);
writel(readl(p) & ~0x40000000, p);
readl(p); /* Flush the write - do not use sca_flush */
udelay(1);
ramsize = sca_detect_ram(card, card->rambase,
pci_resource_len(pdev, 3));
/* number of TX + RX buffers for one port - this is dual port card */
i = ramsize / (2 * (sizeof(pkt_desc) + HDLC_MAX_MRU));
card->tx_ring_buffers = min(i / 2, MAX_TX_BUFFERS);
card->rx_ring_buffers = i - card->tx_ring_buffers;
card->buff_offset = 2 * sizeof(pkt_desc) * (card->tx_ring_buffers +
card->rx_ring_buffers);
printk(KERN_INFO "pci200syn: %u KB RAM at 0x%x, IRQ%u, using %u TX +"
" %u RX packets rings\n", ramsize / 1024, ramphys,
pdev->irq, card->tx_ring_buffers, card->rx_ring_buffers);
if (card->tx_ring_buffers < 1) {
printk(KERN_ERR "pci200syn: RAM test failed\n");
pci200_pci_remove_one(pdev);
return -EFAULT;
}
/* Enable interrupts on the PCI bridge */
p = &card->plxbase->intr_ctrl_stat;
writew(readw(p) | 0x0040, p);
/* Allocate IRQ */
if (request_irq(pdev->irq, sca_intr, IRQF_SHARED, "pci200syn", card)) {
printk(KERN_WARNING "pci200syn: could not allocate IRQ%d.\n",
pdev->irq);
pci200_pci_remove_one(pdev);
return -EBUSY;
}
card->irq = pdev->irq;
sca_init(card, 0);
for (i = 0; i < 2; i++) {
port_t *port = &card->ports[i];
struct net_device *dev = port->netdev;
hdlc_device *hdlc = dev_to_hdlc(dev);
port->chan = i;
spin_lock_init(&port->lock);
dev->irq = card->irq;
dev->mem_start = ramphys;
dev->mem_end = ramphys + ramsize - 1;
dev->tx_queue_len = 50;
dev->netdev_ops = &pci200_ops;
hdlc->attach = sca_attach;
hdlc->xmit = sca_xmit;
port->settings.clock_type = CLOCK_EXT;
port->card = card;
sca_init_port(port);
if (register_hdlc_device(dev)) {
printk(KERN_ERR "pci200syn: unable to register hdlc "
"device\n");
port->card = NULL;
pci200_pci_remove_one(pdev);
return -ENOBUFS;
}
printk(KERN_INFO "%s: PCI200SYN channel %d\n",
dev->name, port->chan);
}
sca_flush(card);
return 0;
}
static DEFINE_PCI_DEVICE_TABLE(pci200_pci_tbl) = {
{ PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050, PCI_VENDOR_ID_PLX,
PCI_DEVICE_ID_PLX_PCI200SYN, 0, 0, 0 },
{ 0, }
};
static struct pci_driver pci200_pci_driver = {
.name = "PCI200SYN",
.id_table = pci200_pci_tbl,
.probe = pci200_pci_init_one,
.remove = pci200_pci_remove_one,
};
static int __init pci200_init_module(void)
{
if (pci_clock_freq < 1000000 || pci_clock_freq > 80000000) {
printk(KERN_ERR "pci200syn: Invalid PCI clock frequency\n");
return -EINVAL;
}
return pci_register_driver(&pci200_pci_driver);
}
static void __exit pci200_cleanup_module(void)
{
pci_unregister_driver(&pci200_pci_driver);
}
MODULE_AUTHOR("Krzysztof Halasa <khc@pm.waw.pl>");
MODULE_DESCRIPTION("Goramo PCI200SYN serial port driver");
MODULE_LICENSE("GPL v2");
MODULE_DEVICE_TABLE(pci, pci200_pci_tbl);
module_param(pci_clock_freq, int, 0444);
MODULE_PARM_DESC(pci_clock_freq, "System PCI clock frequency in Hz");
module_init(pci200_init_module);
module_exit(pci200_cleanup_module);
| gpl-2.0 |
ztemt/V5s_N918St_KitKat_kernel | arch/arm/mach-imx/devices/platform-imx-i2c.c | 2694 | 3671 | /*
* Copyright (C) 2009-2010 Pengutronix
* Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*/
#include "../hardware.h"
#include "devices-common.h"
#define imx_imx_i2c_data_entry_single(soc, _devid, _id, _hwid, _size) \
{ \
.devid = _devid, \
.id = _id, \
.iobase = soc ## _I2C ## _hwid ## _BASE_ADDR, \
.iosize = _size, \
.irq = soc ## _INT_I2C ## _hwid, \
}
#define imx_imx_i2c_data_entry(soc, _devid, _id, _hwid, _size) \
[_id] = imx_imx_i2c_data_entry_single(soc, _devid, _id, _hwid, _size)
#ifdef CONFIG_SOC_IMX1
const struct imx_imx_i2c_data imx1_imx_i2c_data __initconst =
imx_imx_i2c_data_entry_single(MX1, "imx1-i2c", 0, , SZ_4K);
#endif /* ifdef CONFIG_SOC_IMX1 */
#ifdef CONFIG_SOC_IMX21
const struct imx_imx_i2c_data imx21_imx_i2c_data __initconst =
imx_imx_i2c_data_entry_single(MX21, "imx21-i2c", 0, , SZ_4K);
#endif /* ifdef CONFIG_SOC_IMX21 */
#ifdef CONFIG_SOC_IMX25
const struct imx_imx_i2c_data imx25_imx_i2c_data[] __initconst = {
#define imx25_imx_i2c_data_entry(_id, _hwid) \
imx_imx_i2c_data_entry(MX25, "imx21-i2c", _id, _hwid, SZ_16K)
imx25_imx_i2c_data_entry(0, 1),
imx25_imx_i2c_data_entry(1, 2),
imx25_imx_i2c_data_entry(2, 3),
};
#endif /* ifdef CONFIG_SOC_IMX25 */
#ifdef CONFIG_SOC_IMX27
const struct imx_imx_i2c_data imx27_imx_i2c_data[] __initconst = {
#define imx27_imx_i2c_data_entry(_id, _hwid) \
imx_imx_i2c_data_entry(MX27, "imx21-i2c", _id, _hwid, SZ_4K)
imx27_imx_i2c_data_entry(0, 1),
imx27_imx_i2c_data_entry(1, 2),
};
#endif /* ifdef CONFIG_SOC_IMX27 */
#ifdef CONFIG_SOC_IMX31
const struct imx_imx_i2c_data imx31_imx_i2c_data[] __initconst = {
#define imx31_imx_i2c_data_entry(_id, _hwid) \
imx_imx_i2c_data_entry(MX31, "imx21-i2c", _id, _hwid, SZ_4K)
imx31_imx_i2c_data_entry(0, 1),
imx31_imx_i2c_data_entry(1, 2),
imx31_imx_i2c_data_entry(2, 3),
};
#endif /* ifdef CONFIG_SOC_IMX31 */
#ifdef CONFIG_SOC_IMX35
const struct imx_imx_i2c_data imx35_imx_i2c_data[] __initconst = {
#define imx35_imx_i2c_data_entry(_id, _hwid) \
imx_imx_i2c_data_entry(MX35, "imx21-i2c", _id, _hwid, SZ_4K)
imx35_imx_i2c_data_entry(0, 1),
imx35_imx_i2c_data_entry(1, 2),
imx35_imx_i2c_data_entry(2, 3),
};
#endif /* ifdef CONFIG_SOC_IMX35 */
#ifdef CONFIG_SOC_IMX51
const struct imx_imx_i2c_data imx51_imx_i2c_data[] __initconst = {
#define imx51_imx_i2c_data_entry(_id, _hwid) \
imx_imx_i2c_data_entry(MX51, "imx21-i2c", _id, _hwid, SZ_4K)
imx51_imx_i2c_data_entry(0, 1),
imx51_imx_i2c_data_entry(1, 2),
{
.devid = "imx21-i2c",
.id = 2,
.iobase = MX51_HSI2C_DMA_BASE_ADDR,
.iosize = SZ_16K,
.irq = MX51_INT_HS_I2C,
},
};
#endif /* ifdef CONFIG_SOC_IMX51 */
#ifdef CONFIG_SOC_IMX53
const struct imx_imx_i2c_data imx53_imx_i2c_data[] __initconst = {
#define imx53_imx_i2c_data_entry(_id, _hwid) \
imx_imx_i2c_data_entry(MX53, "imx21-i2c", _id, _hwid, SZ_4K)
imx53_imx_i2c_data_entry(0, 1),
imx53_imx_i2c_data_entry(1, 2),
imx53_imx_i2c_data_entry(2, 3),
};
#endif /* ifdef CONFIG_SOC_IMX53 */
struct platform_device *__init imx_add_imx_i2c(
const struct imx_imx_i2c_data *data,
const struct imxi2c_platform_data *pdata)
{
struct resource res[] = {
{
.start = data->iobase,
.end = data->iobase + data->iosize - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->irq,
.end = data->irq,
.flags = IORESOURCE_IRQ,
},
};
return imx_add_platform_device(data->devid, data->id,
res, ARRAY_SIZE(res),
pdata, sizeof(*pdata));
}
| gpl-2.0 |
Team-Hydra/android_kernel_htc_msm8660-caf | drivers/mmc/host/tifm_sd.c | 2950 | 29428 | /*
* tifm_sd.c - TI FlashMedia driver
*
* Copyright (C) 2006 Alex Dubov <oakad@yahoo.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.
*
* Special thanks to Brad Campbell for extensive testing of this driver.
*
*/
#include <linux/tifm.h>
#include <linux/mmc/host.h>
#include <linux/highmem.h>
#include <linux/scatterlist.h>
#include <asm/io.h>
#define DRIVER_NAME "tifm_sd"
#define DRIVER_VERSION "0.8"
static int no_dma = 0;
static int fixed_timeout = 0;
module_param(no_dma, bool, 0644);
module_param(fixed_timeout, bool, 0644);
/* Constants here are mostly from OMAP5912 datasheet */
#define TIFM_MMCSD_RESET 0x0002
#define TIFM_MMCSD_CLKMASK 0x03ff
#define TIFM_MMCSD_POWER 0x0800
#define TIFM_MMCSD_4BBUS 0x8000
#define TIFM_MMCSD_RXDE 0x8000 /* rx dma enable */
#define TIFM_MMCSD_TXDE 0x0080 /* tx dma enable */
#define TIFM_MMCSD_BUFINT 0x0c00 /* set bits: AE, AF */
#define TIFM_MMCSD_DPE 0x0020 /* data timeout counted in kilocycles */
#define TIFM_MMCSD_INAB 0x0080 /* abort / initialize command */
#define TIFM_MMCSD_READ 0x8000
#define TIFM_MMCSD_ERRMASK 0x01e0 /* set bits: CCRC, CTO, DCRC, DTO */
#define TIFM_MMCSD_EOC 0x0001 /* end of command phase */
#define TIFM_MMCSD_CD 0x0002 /* card detect */
#define TIFM_MMCSD_CB 0x0004 /* card enter busy state */
#define TIFM_MMCSD_BRS 0x0008 /* block received/sent */
#define TIFM_MMCSD_EOFB 0x0010 /* card exit busy state */
#define TIFM_MMCSD_DTO 0x0020 /* data time-out */
#define TIFM_MMCSD_DCRC 0x0040 /* data crc error */
#define TIFM_MMCSD_CTO 0x0080 /* command time-out */
#define TIFM_MMCSD_CCRC 0x0100 /* command crc error */
#define TIFM_MMCSD_AF 0x0400 /* fifo almost full */
#define TIFM_MMCSD_AE 0x0800 /* fifo almost empty */
#define TIFM_MMCSD_OCRB 0x1000 /* OCR busy */
#define TIFM_MMCSD_CIRQ 0x2000 /* card irq (cmd40/sdio) */
#define TIFM_MMCSD_CERR 0x4000 /* card status error */
#define TIFM_MMCSD_ODTO 0x0040 /* open drain / extended timeout */
#define TIFM_MMCSD_CARD_RO 0x0200 /* card is read-only */
#define TIFM_MMCSD_FIFO_SIZE 0x0020
#define TIFM_MMCSD_RSP_R0 0x0000
#define TIFM_MMCSD_RSP_R1 0x0100
#define TIFM_MMCSD_RSP_R2 0x0200
#define TIFM_MMCSD_RSP_R3 0x0300
#define TIFM_MMCSD_RSP_R4 0x0400
#define TIFM_MMCSD_RSP_R5 0x0500
#define TIFM_MMCSD_RSP_R6 0x0600
#define TIFM_MMCSD_RSP_BUSY 0x0800
#define TIFM_MMCSD_CMD_BC 0x0000
#define TIFM_MMCSD_CMD_BCR 0x1000
#define TIFM_MMCSD_CMD_AC 0x2000
#define TIFM_MMCSD_CMD_ADTC 0x3000
#define TIFM_MMCSD_MAX_BLOCK_SIZE 0x0800UL
enum {
CMD_READY = 0x0001,
FIFO_READY = 0x0002,
BRS_READY = 0x0004,
SCMD_ACTIVE = 0x0008,
SCMD_READY = 0x0010,
CARD_BUSY = 0x0020,
DATA_CARRY = 0x0040
};
struct tifm_sd {
struct tifm_dev *dev;
unsigned short eject:1,
open_drain:1,
no_dma:1;
unsigned short cmd_flags;
unsigned int clk_freq;
unsigned int clk_div;
unsigned long timeout_jiffies;
struct tasklet_struct finish_tasklet;
struct timer_list timer;
struct mmc_request *req;
int sg_len;
int sg_pos;
unsigned int block_pos;
struct scatterlist bounce_buf;
unsigned char bounce_buf_data[TIFM_MMCSD_MAX_BLOCK_SIZE];
};
/* for some reason, host won't respond correctly to readw/writew */
static void tifm_sd_read_fifo(struct tifm_sd *host, struct page *pg,
unsigned int off, unsigned int cnt)
{
struct tifm_dev *sock = host->dev;
unsigned char *buf;
unsigned int pos = 0, val;
buf = kmap_atomic(pg, KM_BIO_DST_IRQ) + off;
if (host->cmd_flags & DATA_CARRY) {
buf[pos++] = host->bounce_buf_data[0];
host->cmd_flags &= ~DATA_CARRY;
}
while (pos < cnt) {
val = readl(sock->addr + SOCK_MMCSD_DATA);
buf[pos++] = val & 0xff;
if (pos == cnt) {
host->bounce_buf_data[0] = (val >> 8) & 0xff;
host->cmd_flags |= DATA_CARRY;
break;
}
buf[pos++] = (val >> 8) & 0xff;
}
kunmap_atomic(buf - off, KM_BIO_DST_IRQ);
}
static void tifm_sd_write_fifo(struct tifm_sd *host, struct page *pg,
unsigned int off, unsigned int cnt)
{
struct tifm_dev *sock = host->dev;
unsigned char *buf;
unsigned int pos = 0, val;
buf = kmap_atomic(pg, KM_BIO_SRC_IRQ) + off;
if (host->cmd_flags & DATA_CARRY) {
val = host->bounce_buf_data[0] | ((buf[pos++] << 8) & 0xff00);
writel(val, sock->addr + SOCK_MMCSD_DATA);
host->cmd_flags &= ~DATA_CARRY;
}
while (pos < cnt) {
val = buf[pos++];
if (pos == cnt) {
host->bounce_buf_data[0] = val & 0xff;
host->cmd_flags |= DATA_CARRY;
break;
}
val |= (buf[pos++] << 8) & 0xff00;
writel(val, sock->addr + SOCK_MMCSD_DATA);
}
kunmap_atomic(buf - off, KM_BIO_SRC_IRQ);
}
static void tifm_sd_transfer_data(struct tifm_sd *host)
{
struct mmc_data *r_data = host->req->cmd->data;
struct scatterlist *sg = r_data->sg;
unsigned int off, cnt, t_size = TIFM_MMCSD_FIFO_SIZE * 2;
unsigned int p_off, p_cnt;
struct page *pg;
if (host->sg_pos == host->sg_len)
return;
while (t_size) {
cnt = sg[host->sg_pos].length - host->block_pos;
if (!cnt) {
host->block_pos = 0;
host->sg_pos++;
if (host->sg_pos == host->sg_len) {
if ((r_data->flags & MMC_DATA_WRITE)
&& (host->cmd_flags & DATA_CARRY))
writel(host->bounce_buf_data[0],
host->dev->addr
+ SOCK_MMCSD_DATA);
return;
}
cnt = sg[host->sg_pos].length;
}
off = sg[host->sg_pos].offset + host->block_pos;
pg = nth_page(sg_page(&sg[host->sg_pos]), off >> PAGE_SHIFT);
p_off = offset_in_page(off);
p_cnt = PAGE_SIZE - p_off;
p_cnt = min(p_cnt, cnt);
p_cnt = min(p_cnt, t_size);
if (r_data->flags & MMC_DATA_READ)
tifm_sd_read_fifo(host, pg, p_off, p_cnt);
else if (r_data->flags & MMC_DATA_WRITE)
tifm_sd_write_fifo(host, pg, p_off, p_cnt);
t_size -= p_cnt;
host->block_pos += p_cnt;
}
}
static void tifm_sd_copy_page(struct page *dst, unsigned int dst_off,
struct page *src, unsigned int src_off,
unsigned int count)
{
unsigned char *src_buf = kmap_atomic(src, KM_BIO_SRC_IRQ) + src_off;
unsigned char *dst_buf = kmap_atomic(dst, KM_BIO_DST_IRQ) + dst_off;
memcpy(dst_buf, src_buf, count);
kunmap_atomic(dst_buf - dst_off, KM_BIO_DST_IRQ);
kunmap_atomic(src_buf - src_off, KM_BIO_SRC_IRQ);
}
static void tifm_sd_bounce_block(struct tifm_sd *host, struct mmc_data *r_data)
{
struct scatterlist *sg = r_data->sg;
unsigned int t_size = r_data->blksz;
unsigned int off, cnt;
unsigned int p_off, p_cnt;
struct page *pg;
dev_dbg(&host->dev->dev, "bouncing block\n");
while (t_size) {
cnt = sg[host->sg_pos].length - host->block_pos;
if (!cnt) {
host->block_pos = 0;
host->sg_pos++;
if (host->sg_pos == host->sg_len)
return;
cnt = sg[host->sg_pos].length;
}
off = sg[host->sg_pos].offset + host->block_pos;
pg = nth_page(sg_page(&sg[host->sg_pos]), off >> PAGE_SHIFT);
p_off = offset_in_page(off);
p_cnt = PAGE_SIZE - p_off;
p_cnt = min(p_cnt, cnt);
p_cnt = min(p_cnt, t_size);
if (r_data->flags & MMC_DATA_WRITE)
tifm_sd_copy_page(sg_page(&host->bounce_buf),
r_data->blksz - t_size,
pg, p_off, p_cnt);
else if (r_data->flags & MMC_DATA_READ)
tifm_sd_copy_page(pg, p_off, sg_page(&host->bounce_buf),
r_data->blksz - t_size, p_cnt);
t_size -= p_cnt;
host->block_pos += p_cnt;
}
}
static int tifm_sd_set_dma_data(struct tifm_sd *host, struct mmc_data *r_data)
{
struct tifm_dev *sock = host->dev;
unsigned int t_size = TIFM_DMA_TSIZE * r_data->blksz;
unsigned int dma_len, dma_blk_cnt, dma_off;
struct scatterlist *sg = NULL;
unsigned long flags;
if (host->sg_pos == host->sg_len)
return 1;
if (host->cmd_flags & DATA_CARRY) {
host->cmd_flags &= ~DATA_CARRY;
local_irq_save(flags);
tifm_sd_bounce_block(host, r_data);
local_irq_restore(flags);
if (host->sg_pos == host->sg_len)
return 1;
}
dma_len = sg_dma_len(&r_data->sg[host->sg_pos]) - host->block_pos;
if (!dma_len) {
host->block_pos = 0;
host->sg_pos++;
if (host->sg_pos == host->sg_len)
return 1;
dma_len = sg_dma_len(&r_data->sg[host->sg_pos]);
}
if (dma_len < t_size) {
dma_blk_cnt = dma_len / r_data->blksz;
dma_off = host->block_pos;
host->block_pos += dma_blk_cnt * r_data->blksz;
} else {
dma_blk_cnt = TIFM_DMA_TSIZE;
dma_off = host->block_pos;
host->block_pos += t_size;
}
if (dma_blk_cnt)
sg = &r_data->sg[host->sg_pos];
else if (dma_len) {
if (r_data->flags & MMC_DATA_WRITE) {
local_irq_save(flags);
tifm_sd_bounce_block(host, r_data);
local_irq_restore(flags);
} else
host->cmd_flags |= DATA_CARRY;
sg = &host->bounce_buf;
dma_off = 0;
dma_blk_cnt = 1;
} else
return 1;
dev_dbg(&sock->dev, "setting dma for %d blocks\n", dma_blk_cnt);
writel(sg_dma_address(sg) + dma_off, sock->addr + SOCK_DMA_ADDRESS);
if (r_data->flags & MMC_DATA_WRITE)
writel((dma_blk_cnt << 8) | TIFM_DMA_TX | TIFM_DMA_EN,
sock->addr + SOCK_DMA_CONTROL);
else
writel((dma_blk_cnt << 8) | TIFM_DMA_EN,
sock->addr + SOCK_DMA_CONTROL);
return 0;
}
static unsigned int tifm_sd_op_flags(struct mmc_command *cmd)
{
unsigned int rc = 0;
switch (mmc_resp_type(cmd)) {
case MMC_RSP_NONE:
rc |= TIFM_MMCSD_RSP_R0;
break;
case MMC_RSP_R1B:
rc |= TIFM_MMCSD_RSP_BUSY; // deliberate fall-through
case MMC_RSP_R1:
rc |= TIFM_MMCSD_RSP_R1;
break;
case MMC_RSP_R2:
rc |= TIFM_MMCSD_RSP_R2;
break;
case MMC_RSP_R3:
rc |= TIFM_MMCSD_RSP_R3;
break;
default:
BUG();
}
switch (mmc_cmd_type(cmd)) {
case MMC_CMD_BC:
rc |= TIFM_MMCSD_CMD_BC;
break;
case MMC_CMD_BCR:
rc |= TIFM_MMCSD_CMD_BCR;
break;
case MMC_CMD_AC:
rc |= TIFM_MMCSD_CMD_AC;
break;
case MMC_CMD_ADTC:
rc |= TIFM_MMCSD_CMD_ADTC;
break;
default:
BUG();
}
return rc;
}
static void tifm_sd_exec(struct tifm_sd *host, struct mmc_command *cmd)
{
struct tifm_dev *sock = host->dev;
unsigned int cmd_mask = tifm_sd_op_flags(cmd);
if (host->open_drain)
cmd_mask |= TIFM_MMCSD_ODTO;
if (cmd->data && (cmd->data->flags & MMC_DATA_READ))
cmd_mask |= TIFM_MMCSD_READ;
dev_dbg(&sock->dev, "executing opcode 0x%x, arg: 0x%x, mask: 0x%x\n",
cmd->opcode, cmd->arg, cmd_mask);
writel((cmd->arg >> 16) & 0xffff, sock->addr + SOCK_MMCSD_ARG_HIGH);
writel(cmd->arg & 0xffff, sock->addr + SOCK_MMCSD_ARG_LOW);
writel(cmd->opcode | cmd_mask, sock->addr + SOCK_MMCSD_COMMAND);
}
static void tifm_sd_fetch_resp(struct mmc_command *cmd, struct tifm_dev *sock)
{
cmd->resp[0] = (readl(sock->addr + SOCK_MMCSD_RESPONSE + 0x1c) << 16)
| readl(sock->addr + SOCK_MMCSD_RESPONSE + 0x18);
cmd->resp[1] = (readl(sock->addr + SOCK_MMCSD_RESPONSE + 0x14) << 16)
| readl(sock->addr + SOCK_MMCSD_RESPONSE + 0x10);
cmd->resp[2] = (readl(sock->addr + SOCK_MMCSD_RESPONSE + 0x0c) << 16)
| readl(sock->addr + SOCK_MMCSD_RESPONSE + 0x08);
cmd->resp[3] = (readl(sock->addr + SOCK_MMCSD_RESPONSE + 0x04) << 16)
| readl(sock->addr + SOCK_MMCSD_RESPONSE + 0x00);
}
static void tifm_sd_check_status(struct tifm_sd *host)
{
struct tifm_dev *sock = host->dev;
struct mmc_command *cmd = host->req->cmd;
if (cmd->error)
goto finish_request;
if (!(host->cmd_flags & CMD_READY))
return;
if (cmd->data) {
if (cmd->data->error) {
if ((host->cmd_flags & SCMD_ACTIVE)
&& !(host->cmd_flags & SCMD_READY))
return;
goto finish_request;
}
if (!(host->cmd_flags & BRS_READY))
return;
if (!(host->no_dma || (host->cmd_flags & FIFO_READY)))
return;
if (cmd->data->flags & MMC_DATA_WRITE) {
if (host->req->stop) {
if (!(host->cmd_flags & SCMD_ACTIVE)) {
host->cmd_flags |= SCMD_ACTIVE;
writel(TIFM_MMCSD_EOFB
| readl(sock->addr
+ SOCK_MMCSD_INT_ENABLE),
sock->addr
+ SOCK_MMCSD_INT_ENABLE);
tifm_sd_exec(host, host->req->stop);
return;
} else {
if (!(host->cmd_flags & SCMD_READY)
|| (host->cmd_flags & CARD_BUSY))
return;
writel((~TIFM_MMCSD_EOFB)
& readl(sock->addr
+ SOCK_MMCSD_INT_ENABLE),
sock->addr
+ SOCK_MMCSD_INT_ENABLE);
}
} else {
if (host->cmd_flags & CARD_BUSY)
return;
writel((~TIFM_MMCSD_EOFB)
& readl(sock->addr
+ SOCK_MMCSD_INT_ENABLE),
sock->addr + SOCK_MMCSD_INT_ENABLE);
}
} else {
if (host->req->stop) {
if (!(host->cmd_flags & SCMD_ACTIVE)) {
host->cmd_flags |= SCMD_ACTIVE;
tifm_sd_exec(host, host->req->stop);
return;
} else {
if (!(host->cmd_flags & SCMD_READY))
return;
}
}
}
}
finish_request:
tasklet_schedule(&host->finish_tasklet);
}
/* Called from interrupt handler */
static void tifm_sd_data_event(struct tifm_dev *sock)
{
struct tifm_sd *host;
unsigned int fifo_status = 0;
struct mmc_data *r_data = NULL;
spin_lock(&sock->lock);
host = mmc_priv((struct mmc_host*)tifm_get_drvdata(sock));
fifo_status = readl(sock->addr + SOCK_DMA_FIFO_STATUS);
dev_dbg(&sock->dev, "data event: fifo_status %x, flags %x\n",
fifo_status, host->cmd_flags);
if (host->req) {
r_data = host->req->cmd->data;
if (r_data && (fifo_status & TIFM_FIFO_READY)) {
if (tifm_sd_set_dma_data(host, r_data)) {
host->cmd_flags |= FIFO_READY;
tifm_sd_check_status(host);
}
}
}
writel(fifo_status, sock->addr + SOCK_DMA_FIFO_STATUS);
spin_unlock(&sock->lock);
}
/* Called from interrupt handler */
static void tifm_sd_card_event(struct tifm_dev *sock)
{
struct tifm_sd *host;
unsigned int host_status = 0;
int cmd_error = 0;
struct mmc_command *cmd = NULL;
unsigned long flags;
spin_lock(&sock->lock);
host = mmc_priv((struct mmc_host*)tifm_get_drvdata(sock));
host_status = readl(sock->addr + SOCK_MMCSD_STATUS);
dev_dbg(&sock->dev, "host event: host_status %x, flags %x\n",
host_status, host->cmd_flags);
if (host->req) {
cmd = host->req->cmd;
if (host_status & TIFM_MMCSD_ERRMASK) {
writel(host_status & TIFM_MMCSD_ERRMASK,
sock->addr + SOCK_MMCSD_STATUS);
if (host_status & TIFM_MMCSD_CTO)
cmd_error = -ETIMEDOUT;
else if (host_status & TIFM_MMCSD_CCRC)
cmd_error = -EILSEQ;
if (cmd->data) {
if (host_status & TIFM_MMCSD_DTO)
cmd->data->error = -ETIMEDOUT;
else if (host_status & TIFM_MMCSD_DCRC)
cmd->data->error = -EILSEQ;
}
writel(TIFM_FIFO_INT_SETALL,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_CLEAR);
writel(TIFM_DMA_RESET, sock->addr + SOCK_DMA_CONTROL);
if (host->req->stop) {
if (host->cmd_flags & SCMD_ACTIVE) {
host->req->stop->error = cmd_error;
host->cmd_flags |= SCMD_READY;
} else {
cmd->error = cmd_error;
host->cmd_flags |= SCMD_ACTIVE;
tifm_sd_exec(host, host->req->stop);
goto done;
}
} else
cmd->error = cmd_error;
} else {
if (host_status & (TIFM_MMCSD_EOC | TIFM_MMCSD_CERR)) {
if (!(host->cmd_flags & CMD_READY)) {
host->cmd_flags |= CMD_READY;
tifm_sd_fetch_resp(cmd, sock);
} else if (host->cmd_flags & SCMD_ACTIVE) {
host->cmd_flags |= SCMD_READY;
tifm_sd_fetch_resp(host->req->stop,
sock);
}
}
if (host_status & TIFM_MMCSD_BRS)
host->cmd_flags |= BRS_READY;
}
if (host->no_dma && cmd->data) {
if (host_status & TIFM_MMCSD_AE)
writel(host_status & TIFM_MMCSD_AE,
sock->addr + SOCK_MMCSD_STATUS);
if (host_status & (TIFM_MMCSD_AE | TIFM_MMCSD_AF
| TIFM_MMCSD_BRS)) {
local_irq_save(flags);
tifm_sd_transfer_data(host);
local_irq_restore(flags);
host_status &= ~TIFM_MMCSD_AE;
}
}
if (host_status & TIFM_MMCSD_EOFB)
host->cmd_flags &= ~CARD_BUSY;
else if (host_status & TIFM_MMCSD_CB)
host->cmd_flags |= CARD_BUSY;
tifm_sd_check_status(host);
}
done:
writel(host_status, sock->addr + SOCK_MMCSD_STATUS);
spin_unlock(&sock->lock);
}
static void tifm_sd_set_data_timeout(struct tifm_sd *host,
struct mmc_data *data)
{
struct tifm_dev *sock = host->dev;
unsigned int data_timeout = data->timeout_clks;
if (fixed_timeout)
return;
data_timeout += data->timeout_ns /
((1000000000UL / host->clk_freq) * host->clk_div);
if (data_timeout < 0xffff) {
writel(data_timeout, sock->addr + SOCK_MMCSD_DATA_TO);
writel((~TIFM_MMCSD_DPE)
& readl(sock->addr + SOCK_MMCSD_SDIO_MODE_CONFIG),
sock->addr + SOCK_MMCSD_SDIO_MODE_CONFIG);
} else {
data_timeout = (data_timeout >> 10) + 1;
if (data_timeout > 0xffff)
data_timeout = 0; /* set to unlimited */
writel(data_timeout, sock->addr + SOCK_MMCSD_DATA_TO);
writel(TIFM_MMCSD_DPE
| readl(sock->addr + SOCK_MMCSD_SDIO_MODE_CONFIG),
sock->addr + SOCK_MMCSD_SDIO_MODE_CONFIG);
}
}
static void tifm_sd_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
struct tifm_sd *host = mmc_priv(mmc);
struct tifm_dev *sock = host->dev;
unsigned long flags;
struct mmc_data *r_data = mrq->cmd->data;
spin_lock_irqsave(&sock->lock, flags);
if (host->eject) {
mrq->cmd->error = -ENOMEDIUM;
goto err_out;
}
if (host->req) {
printk(KERN_ERR "%s : unfinished request detected\n",
dev_name(&sock->dev));
mrq->cmd->error = -ETIMEDOUT;
goto err_out;
}
host->cmd_flags = 0;
host->block_pos = 0;
host->sg_pos = 0;
if (mrq->data && !is_power_of_2(mrq->data->blksz))
host->no_dma = 1;
else
host->no_dma = no_dma ? 1 : 0;
if (r_data) {
tifm_sd_set_data_timeout(host, r_data);
if ((r_data->flags & MMC_DATA_WRITE) && !mrq->stop)
writel(TIFM_MMCSD_EOFB
| readl(sock->addr + SOCK_MMCSD_INT_ENABLE),
sock->addr + SOCK_MMCSD_INT_ENABLE);
if (host->no_dma) {
writel(TIFM_MMCSD_BUFINT
| readl(sock->addr + SOCK_MMCSD_INT_ENABLE),
sock->addr + SOCK_MMCSD_INT_ENABLE);
writel(((TIFM_MMCSD_FIFO_SIZE - 1) << 8)
| (TIFM_MMCSD_FIFO_SIZE - 1),
sock->addr + SOCK_MMCSD_BUFFER_CONFIG);
host->sg_len = r_data->sg_len;
} else {
sg_init_one(&host->bounce_buf, host->bounce_buf_data,
r_data->blksz);
if(1 != tifm_map_sg(sock, &host->bounce_buf, 1,
r_data->flags & MMC_DATA_WRITE
? PCI_DMA_TODEVICE
: PCI_DMA_FROMDEVICE)) {
printk(KERN_ERR "%s : scatterlist map failed\n",
dev_name(&sock->dev));
mrq->cmd->error = -ENOMEM;
goto err_out;
}
host->sg_len = tifm_map_sg(sock, r_data->sg,
r_data->sg_len,
r_data->flags
& MMC_DATA_WRITE
? PCI_DMA_TODEVICE
: PCI_DMA_FROMDEVICE);
if (host->sg_len < 1) {
printk(KERN_ERR "%s : scatterlist map failed\n",
dev_name(&sock->dev));
tifm_unmap_sg(sock, &host->bounce_buf, 1,
r_data->flags & MMC_DATA_WRITE
? PCI_DMA_TODEVICE
: PCI_DMA_FROMDEVICE);
mrq->cmd->error = -ENOMEM;
goto err_out;
}
writel(TIFM_FIFO_INT_SETALL,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_CLEAR);
writel(ilog2(r_data->blksz) - 2,
sock->addr + SOCK_FIFO_PAGE_SIZE);
writel(TIFM_FIFO_ENABLE,
sock->addr + SOCK_FIFO_CONTROL);
writel(TIFM_FIFO_INTMASK,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_SET);
if (r_data->flags & MMC_DATA_WRITE)
writel(TIFM_MMCSD_TXDE,
sock->addr + SOCK_MMCSD_BUFFER_CONFIG);
else
writel(TIFM_MMCSD_RXDE,
sock->addr + SOCK_MMCSD_BUFFER_CONFIG);
tifm_sd_set_dma_data(host, r_data);
}
writel(r_data->blocks - 1,
sock->addr + SOCK_MMCSD_NUM_BLOCKS);
writel(r_data->blksz - 1,
sock->addr + SOCK_MMCSD_BLOCK_LEN);
}
host->req = mrq;
mod_timer(&host->timer, jiffies + host->timeout_jiffies);
writel(TIFM_CTRL_LED | readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
tifm_sd_exec(host, mrq->cmd);
spin_unlock_irqrestore(&sock->lock, flags);
return;
err_out:
spin_unlock_irqrestore(&sock->lock, flags);
mmc_request_done(mmc, mrq);
}
static void tifm_sd_end_cmd(unsigned long data)
{
struct tifm_sd *host = (struct tifm_sd*)data;
struct tifm_dev *sock = host->dev;
struct mmc_host *mmc = tifm_get_drvdata(sock);
struct mmc_request *mrq;
struct mmc_data *r_data = NULL;
unsigned long flags;
spin_lock_irqsave(&sock->lock, flags);
del_timer(&host->timer);
mrq = host->req;
host->req = NULL;
if (!mrq) {
printk(KERN_ERR " %s : no request to complete?\n",
dev_name(&sock->dev));
spin_unlock_irqrestore(&sock->lock, flags);
return;
}
r_data = mrq->cmd->data;
if (r_data) {
if (host->no_dma) {
writel((~TIFM_MMCSD_BUFINT)
& readl(sock->addr + SOCK_MMCSD_INT_ENABLE),
sock->addr + SOCK_MMCSD_INT_ENABLE);
} else {
tifm_unmap_sg(sock, &host->bounce_buf, 1,
(r_data->flags & MMC_DATA_WRITE)
? PCI_DMA_TODEVICE : PCI_DMA_FROMDEVICE);
tifm_unmap_sg(sock, r_data->sg, r_data->sg_len,
(r_data->flags & MMC_DATA_WRITE)
? PCI_DMA_TODEVICE : PCI_DMA_FROMDEVICE);
}
r_data->bytes_xfered = r_data->blocks
- readl(sock->addr + SOCK_MMCSD_NUM_BLOCKS) - 1;
r_data->bytes_xfered *= r_data->blksz;
r_data->bytes_xfered += r_data->blksz
- readl(sock->addr + SOCK_MMCSD_BLOCK_LEN) + 1;
}
writel((~TIFM_CTRL_LED) & readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
spin_unlock_irqrestore(&sock->lock, flags);
mmc_request_done(mmc, mrq);
}
static void tifm_sd_abort(unsigned long data)
{
struct tifm_sd *host = (struct tifm_sd*)data;
printk(KERN_ERR
"%s : card failed to respond for a long period of time "
"(%x, %x)\n",
dev_name(&host->dev->dev), host->req->cmd->opcode, host->cmd_flags);
tifm_eject(host->dev);
}
static void tifm_sd_ios(struct mmc_host *mmc, struct mmc_ios *ios)
{
struct tifm_sd *host = mmc_priv(mmc);
struct tifm_dev *sock = host->dev;
unsigned int clk_div1, clk_div2;
unsigned long flags;
spin_lock_irqsave(&sock->lock, flags);
dev_dbg(&sock->dev, "ios: clock = %u, vdd = %x, bus_mode = %x, "
"chip_select = %x, power_mode = %x, bus_width = %x\n",
ios->clock, ios->vdd, ios->bus_mode, ios->chip_select,
ios->power_mode, ios->bus_width);
if (ios->bus_width == MMC_BUS_WIDTH_4) {
writel(TIFM_MMCSD_4BBUS | readl(sock->addr + SOCK_MMCSD_CONFIG),
sock->addr + SOCK_MMCSD_CONFIG);
} else {
writel((~TIFM_MMCSD_4BBUS)
& readl(sock->addr + SOCK_MMCSD_CONFIG),
sock->addr + SOCK_MMCSD_CONFIG);
}
if (ios->clock) {
clk_div1 = 20000000 / ios->clock;
if (!clk_div1)
clk_div1 = 1;
clk_div2 = 24000000 / ios->clock;
if (!clk_div2)
clk_div2 = 1;
if ((20000000 / clk_div1) > ios->clock)
clk_div1++;
if ((24000000 / clk_div2) > ios->clock)
clk_div2++;
if ((20000000 / clk_div1) > (24000000 / clk_div2)) {
host->clk_freq = 20000000;
host->clk_div = clk_div1;
writel((~TIFM_CTRL_FAST_CLK)
& readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
} else {
host->clk_freq = 24000000;
host->clk_div = clk_div2;
writel(TIFM_CTRL_FAST_CLK
| readl(sock->addr + SOCK_CONTROL),
sock->addr + SOCK_CONTROL);
}
} else {
host->clk_div = 0;
}
host->clk_div &= TIFM_MMCSD_CLKMASK;
writel(host->clk_div
| ((~TIFM_MMCSD_CLKMASK)
& readl(sock->addr + SOCK_MMCSD_CONFIG)),
sock->addr + SOCK_MMCSD_CONFIG);
host->open_drain = (ios->bus_mode == MMC_BUSMODE_OPENDRAIN);
/* chip_select : maybe later */
//vdd
//power is set before probe / after remove
spin_unlock_irqrestore(&sock->lock, flags);
}
static int tifm_sd_ro(struct mmc_host *mmc)
{
int rc = 0;
struct tifm_sd *host = mmc_priv(mmc);
struct tifm_dev *sock = host->dev;
unsigned long flags;
spin_lock_irqsave(&sock->lock, flags);
if (TIFM_MMCSD_CARD_RO & readl(sock->addr + SOCK_PRESENT_STATE))
rc = 1;
spin_unlock_irqrestore(&sock->lock, flags);
return rc;
}
static const struct mmc_host_ops tifm_sd_ops = {
.request = tifm_sd_request,
.set_ios = tifm_sd_ios,
.get_ro = tifm_sd_ro
};
static int tifm_sd_initialize_host(struct tifm_sd *host)
{
int rc;
unsigned int host_status = 0;
struct tifm_dev *sock = host->dev;
writel(0, sock->addr + SOCK_MMCSD_INT_ENABLE);
mmiowb();
host->clk_div = 61;
host->clk_freq = 20000000;
writel(TIFM_MMCSD_RESET, sock->addr + SOCK_MMCSD_SYSTEM_CONTROL);
writel(host->clk_div | TIFM_MMCSD_POWER,
sock->addr + SOCK_MMCSD_CONFIG);
/* wait up to 0.51 sec for reset */
for (rc = 32; rc <= 256; rc <<= 1) {
if (1 & readl(sock->addr + SOCK_MMCSD_SYSTEM_STATUS)) {
rc = 0;
break;
}
msleep(rc);
}
if (rc) {
printk(KERN_ERR "%s : controller failed to reset\n",
dev_name(&sock->dev));
return -ENODEV;
}
writel(0, sock->addr + SOCK_MMCSD_NUM_BLOCKS);
writel(host->clk_div | TIFM_MMCSD_POWER,
sock->addr + SOCK_MMCSD_CONFIG);
writel(TIFM_MMCSD_RXDE, sock->addr + SOCK_MMCSD_BUFFER_CONFIG);
// command timeout fixed to 64 clocks for now
writel(64, sock->addr + SOCK_MMCSD_COMMAND_TO);
writel(TIFM_MMCSD_INAB, sock->addr + SOCK_MMCSD_COMMAND);
for (rc = 16; rc <= 64; rc <<= 1) {
host_status = readl(sock->addr + SOCK_MMCSD_STATUS);
writel(host_status, sock->addr + SOCK_MMCSD_STATUS);
if (!(host_status & TIFM_MMCSD_ERRMASK)
&& (host_status & TIFM_MMCSD_EOC)) {
rc = 0;
break;
}
msleep(rc);
}
if (rc) {
printk(KERN_ERR
"%s : card not ready - probe failed on initialization\n",
dev_name(&sock->dev));
return -ENODEV;
}
writel(TIFM_MMCSD_CERR | TIFM_MMCSD_BRS | TIFM_MMCSD_EOC
| TIFM_MMCSD_ERRMASK,
sock->addr + SOCK_MMCSD_INT_ENABLE);
mmiowb();
return 0;
}
static int tifm_sd_probe(struct tifm_dev *sock)
{
struct mmc_host *mmc;
struct tifm_sd *host;
int rc = -EIO;
if (!(TIFM_SOCK_STATE_OCCUPIED
& readl(sock->addr + SOCK_PRESENT_STATE))) {
printk(KERN_WARNING "%s : card gone, unexpectedly\n",
dev_name(&sock->dev));
return rc;
}
mmc = mmc_alloc_host(sizeof(struct tifm_sd), &sock->dev);
if (!mmc)
return -ENOMEM;
host = mmc_priv(mmc);
tifm_set_drvdata(sock, mmc);
host->dev = sock;
host->timeout_jiffies = msecs_to_jiffies(1000);
tasklet_init(&host->finish_tasklet, tifm_sd_end_cmd,
(unsigned long)host);
setup_timer(&host->timer, tifm_sd_abort, (unsigned long)host);
mmc->ops = &tifm_sd_ops;
mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34;
mmc->caps = MMC_CAP_4_BIT_DATA;
mmc->f_min = 20000000 / 60;
mmc->f_max = 24000000;
mmc->max_blk_count = 2048;
mmc->max_segs = mmc->max_blk_count;
mmc->max_blk_size = min(TIFM_MMCSD_MAX_BLOCK_SIZE, PAGE_SIZE);
mmc->max_seg_size = mmc->max_blk_count * mmc->max_blk_size;
mmc->max_req_size = mmc->max_seg_size;
sock->card_event = tifm_sd_card_event;
sock->data_event = tifm_sd_data_event;
rc = tifm_sd_initialize_host(host);
if (!rc)
rc = mmc_add_host(mmc);
if (!rc)
return 0;
mmc_free_host(mmc);
return rc;
}
static void tifm_sd_remove(struct tifm_dev *sock)
{
struct mmc_host *mmc = tifm_get_drvdata(sock);
struct tifm_sd *host = mmc_priv(mmc);
unsigned long flags;
spin_lock_irqsave(&sock->lock, flags);
host->eject = 1;
writel(0, sock->addr + SOCK_MMCSD_INT_ENABLE);
mmiowb();
spin_unlock_irqrestore(&sock->lock, flags);
tasklet_kill(&host->finish_tasklet);
spin_lock_irqsave(&sock->lock, flags);
if (host->req) {
writel(TIFM_FIFO_INT_SETALL,
sock->addr + SOCK_DMA_FIFO_INT_ENABLE_CLEAR);
writel(0, sock->addr + SOCK_DMA_FIFO_INT_ENABLE_SET);
host->req->cmd->error = -ENOMEDIUM;
if (host->req->stop)
host->req->stop->error = -ENOMEDIUM;
tasklet_schedule(&host->finish_tasklet);
}
spin_unlock_irqrestore(&sock->lock, flags);
mmc_remove_host(mmc);
dev_dbg(&sock->dev, "after remove\n");
mmc_free_host(mmc);
}
#ifdef CONFIG_PM
static int tifm_sd_suspend(struct tifm_dev *sock, pm_message_t state)
{
return mmc_suspend_host(tifm_get_drvdata(sock));
}
static int tifm_sd_resume(struct tifm_dev *sock)
{
struct mmc_host *mmc = tifm_get_drvdata(sock);
struct tifm_sd *host = mmc_priv(mmc);
int rc;
rc = tifm_sd_initialize_host(host);
dev_dbg(&sock->dev, "resume initialize %d\n", rc);
if (rc)
host->eject = 1;
else
rc = mmc_resume_host(mmc);
return rc;
}
#else
#define tifm_sd_suspend NULL
#define tifm_sd_resume NULL
#endif /* CONFIG_PM */
static struct tifm_device_id tifm_sd_id_tbl[] = {
{ TIFM_TYPE_SD }, { }
};
static struct tifm_driver tifm_sd_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE
},
.id_table = tifm_sd_id_tbl,
.probe = tifm_sd_probe,
.remove = tifm_sd_remove,
.suspend = tifm_sd_suspend,
.resume = tifm_sd_resume
};
static int __init tifm_sd_init(void)
{
return tifm_register_driver(&tifm_sd_driver);
}
static void __exit tifm_sd_exit(void)
{
tifm_unregister_driver(&tifm_sd_driver);
}
MODULE_AUTHOR("Alex Dubov");
MODULE_DESCRIPTION("TI FlashMedia SD driver");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(tifm, tifm_sd_id_tbl);
MODULE_VERSION(DRIVER_VERSION);
module_init(tifm_sd_init);
module_exit(tifm_sd_exit);
| gpl-2.0 |
brymaster5000/BrYCS_kernel2 | arch/arm/mach-omap2/clkt2xxx_virt_prcm_set.c | 3206 | 6250 | /*
* OMAP2xxx DVFS virtual clock functions
*
* Copyright (C) 2005-2008 Texas Instruments, Inc.
* Copyright (C) 2004-2010 Nokia Corporation
*
* Contacts:
* Richard Woodruff <r-woodruff2@ti.com>
* Paul Walmsley
*
* Based on earlier work by Tuukka Tikkanen, Tony Lindgren,
* Gordon McNutt and RidgeRun, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* XXX Some of this code should be replaceable by the upcoming OPP layer
* code. However, some notion of "rate set" is probably still necessary
* for OMAP2xxx at least. Rate sets should be generalized so they can be
* used for any OMAP chip, not just OMAP2xxx. In particular, Richard Woodruff
* has in the past expressed a preference to use rate sets for OPP changes,
* rather than dynamically recalculating the clock tree, so if someone wants
* this badly enough to write the code to handle it, we should support it
* as an option.
*/
#undef DEBUG
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/cpufreq.h>
#include <linux/slab.h>
#include <plat/clock.h>
#include <plat/sram.h>
#include <plat/sdrc.h>
#include "clock.h"
#include "clock2xxx.h"
#include "opp2xxx.h"
#include "cm2xxx_3xxx.h"
#include "cm-regbits-24xx.h"
const struct prcm_config *curr_prcm_set;
const struct prcm_config *rate_table;
/**
* omap2_table_mpu_recalc - just return the MPU speed
* @clk: virt_prcm_set struct clk
*
* Set virt_prcm_set's rate to the mpu_speed field of the current PRCM set.
*/
unsigned long omap2_table_mpu_recalc(struct clk *clk)
{
return curr_prcm_set->mpu_speed;
}
/*
* Look for a rate equal or less than the target rate given a configuration set.
*
* What's not entirely clear is "which" field represents the key field.
* Some might argue L3-DDR, others ARM, others IVA. This code is simple and
* just uses the ARM rates.
*/
long omap2_round_to_table_rate(struct clk *clk, unsigned long rate)
{
const struct prcm_config *ptr;
long highest_rate;
highest_rate = -EINVAL;
for (ptr = rate_table; ptr->mpu_speed; ptr++) {
if (!(ptr->flags & cpu_mask))
continue;
if (ptr->xtal_speed != sclk->rate)
continue;
highest_rate = ptr->mpu_speed;
/* Can check only after xtal frequency check */
if (ptr->mpu_speed <= rate)
break;
}
return highest_rate;
}
/* Sets basic clocks based on the specified rate */
int omap2_select_table_rate(struct clk *clk, unsigned long rate)
{
u32 cur_rate, done_rate, bypass = 0, tmp;
const struct prcm_config *prcm;
unsigned long found_speed = 0;
unsigned long flags;
for (prcm = rate_table; prcm->mpu_speed; prcm++) {
if (!(prcm->flags & cpu_mask))
continue;
if (prcm->xtal_speed != sclk->rate)
continue;
if (prcm->mpu_speed <= rate) {
found_speed = prcm->mpu_speed;
break;
}
}
if (!found_speed) {
printk(KERN_INFO "Could not set MPU rate to %luMHz\n",
rate / 1000000);
return -EINVAL;
}
curr_prcm_set = prcm;
cur_rate = omap2xxx_clk_get_core_rate(dclk);
if (prcm->dpll_speed == cur_rate / 2) {
omap2xxx_sdrc_reprogram(CORE_CLK_SRC_DPLL, 1);
} else if (prcm->dpll_speed == cur_rate * 2) {
omap2xxx_sdrc_reprogram(CORE_CLK_SRC_DPLL_X2, 1);
} else if (prcm->dpll_speed != cur_rate) {
local_irq_save(flags);
if (prcm->dpll_speed == prcm->xtal_speed)
bypass = 1;
if ((prcm->cm_clksel2_pll & OMAP24XX_CORE_CLK_SRC_MASK) ==
CORE_CLK_SRC_DPLL_X2)
done_rate = CORE_CLK_SRC_DPLL_X2;
else
done_rate = CORE_CLK_SRC_DPLL;
/* MPU divider */
omap2_cm_write_mod_reg(prcm->cm_clksel_mpu, MPU_MOD, CM_CLKSEL);
/* dsp + iva1 div(2420), iva2.1(2430) */
omap2_cm_write_mod_reg(prcm->cm_clksel_dsp,
OMAP24XX_DSP_MOD, CM_CLKSEL);
omap2_cm_write_mod_reg(prcm->cm_clksel_gfx, GFX_MOD, CM_CLKSEL);
/* Major subsystem dividers */
tmp = omap2_cm_read_mod_reg(CORE_MOD, CM_CLKSEL1) & OMAP24XX_CLKSEL_DSS2_MASK;
omap2_cm_write_mod_reg(prcm->cm_clksel1_core | tmp, CORE_MOD,
CM_CLKSEL1);
if (cpu_is_omap2430())
omap2_cm_write_mod_reg(prcm->cm_clksel_mdm,
OMAP2430_MDM_MOD, CM_CLKSEL);
/* x2 to enter omap2xxx_sdrc_init_params() */
omap2xxx_sdrc_reprogram(CORE_CLK_SRC_DPLL_X2, 1);
omap2_set_prcm(prcm->cm_clksel1_pll, prcm->base_sdrc_rfr,
bypass);
omap2xxx_sdrc_init_params(omap2xxx_sdrc_dll_is_unlocked());
omap2xxx_sdrc_reprogram(done_rate, 0);
local_irq_restore(flags);
}
return 0;
}
#ifdef CONFIG_CPU_FREQ
/*
* Walk PRCM rate table and fillout cpufreq freq_table
* XXX This should be replaced by an OPP layer in the near future
*/
static struct cpufreq_frequency_table *freq_table;
void omap2_clk_init_cpufreq_table(struct cpufreq_frequency_table **table)
{
const struct prcm_config *prcm;
int i = 0;
int tbl_sz = 0;
if (!cpu_is_omap24xx())
return;
for (prcm = rate_table; prcm->mpu_speed; prcm++) {
if (!(prcm->flags & cpu_mask))
continue;
if (prcm->xtal_speed != sclk->rate)
continue;
/* don't put bypass rates in table */
if (prcm->dpll_speed == prcm->xtal_speed)
continue;
tbl_sz++;
}
/*
* XXX Ensure that we're doing what CPUFreq expects for this error
* case and the following one
*/
if (tbl_sz == 0) {
pr_warning("%s: no matching entries in rate_table\n",
__func__);
return;
}
/* Include the CPUFREQ_TABLE_END terminator entry */
tbl_sz++;
freq_table = kzalloc(sizeof(struct cpufreq_frequency_table) * tbl_sz,
GFP_ATOMIC);
if (!freq_table) {
pr_err("%s: could not kzalloc frequency table\n", __func__);
return;
}
for (prcm = rate_table; prcm->mpu_speed; prcm++) {
if (!(prcm->flags & cpu_mask))
continue;
if (prcm->xtal_speed != sclk->rate)
continue;
/* don't put bypass rates in table */
if (prcm->dpll_speed == prcm->xtal_speed)
continue;
freq_table[i].index = i;
freq_table[i].frequency = prcm->mpu_speed / 1000;
i++;
}
freq_table[i].index = i;
freq_table[i].frequency = CPUFREQ_TABLE_END;
*table = &freq_table[0];
}
void omap2_clk_exit_cpufreq_table(struct cpufreq_frequency_table **table)
{
if (!cpu_is_omap24xx())
return;
kfree(freq_table);
}
#endif
| gpl-2.0 |
imoseyon/leanKernel-d2usc-deprecated | drivers/usb/wusbcore/wa-hc.c | 3974 | 2592 | /*
* Wire Adapter Host Controller Driver
* Common items to HWA and DWA based HCDs
*
* Copyright (C) 2005-2006 Intel Corporation
* Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*
* FIXME: docs
*/
#include <linux/slab.h>
#include "wusbhc.h"
#include "wa-hc.h"
/**
* Assumes
*
* wa->usb_dev and wa->usb_iface initialized and refcounted,
* wa->wa_descr initialized.
*/
int wa_create(struct wahc *wa, struct usb_interface *iface)
{
int result;
struct device *dev = &iface->dev;
result = wa_rpipes_create(wa);
if (result < 0)
goto error_rpipes_create;
/* Fill up Data Transfer EP pointers */
wa->dti_epd = &iface->cur_altsetting->endpoint[1].desc;
wa->dto_epd = &iface->cur_altsetting->endpoint[2].desc;
wa->xfer_result_size = le16_to_cpu(wa->dti_epd->wMaxPacketSize);
wa->xfer_result = kmalloc(wa->xfer_result_size, GFP_KERNEL);
if (wa->xfer_result == NULL)
goto error_xfer_result_alloc;
result = wa_nep_create(wa, iface);
if (result < 0) {
dev_err(dev, "WA-CDS: can't initialize notif endpoint: %d\n",
result);
goto error_nep_create;
}
return 0;
error_nep_create:
kfree(wa->xfer_result);
error_xfer_result_alloc:
wa_rpipes_destroy(wa);
error_rpipes_create:
return result;
}
EXPORT_SYMBOL_GPL(wa_create);
void __wa_destroy(struct wahc *wa)
{
if (wa->dti_urb) {
usb_kill_urb(wa->dti_urb);
usb_put_urb(wa->dti_urb);
usb_kill_urb(wa->buf_in_urb);
usb_put_urb(wa->buf_in_urb);
}
kfree(wa->xfer_result);
wa_nep_destroy(wa);
wa_rpipes_destroy(wa);
}
EXPORT_SYMBOL_GPL(__wa_destroy);
/**
* wa_reset_all - reset the WA device
* @wa: the WA to be reset
*
* For HWAs the radio controller and all other PALs are also reset.
*/
void wa_reset_all(struct wahc *wa)
{
/* FIXME: assuming HWA. */
wusbhc_reset_all(wa->wusb);
}
MODULE_AUTHOR("Inaky Perez-Gonzalez <inaky.perez-gonzalez@intel.com>");
MODULE_DESCRIPTION("Wireless USB Wire Adapter core");
MODULE_LICENSE("GPL");
| gpl-2.0 |
widz4rd/WIDzard_Kernel_N900_KK | arch/x86/kvm/i8254.c | 4230 | 19447 | /*
* 8253/8254 interval timer emulation
*
* Copyright (c) 2003-2004 Fabrice Bellard
* Copyright (c) 2006 Intel Corporation
* Copyright (c) 2007 Keir Fraser, XenSource Inc
* Copyright (c) 2008 Intel Corporation
* Copyright 2009 Red Hat, Inc. and/or its affiliates.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* Authors:
* Sheng Yang <sheng.yang@intel.com>
* Based on QEMU and Xen.
*/
#define pr_fmt(fmt) "pit: " fmt
#include <linux/kvm_host.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include "irq.h"
#include "i8254.h"
#ifndef CONFIG_X86_64
#define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
#else
#define mod_64(x, y) ((x) % (y))
#endif
#define RW_STATE_LSB 1
#define RW_STATE_MSB 2
#define RW_STATE_WORD0 3
#define RW_STATE_WORD1 4
/* Compute with 96 bit intermediate result: (a*b)/c */
static u64 muldiv64(u64 a, u32 b, u32 c)
{
union {
u64 ll;
struct {
u32 low, high;
} l;
} u, res;
u64 rl, rh;
u.ll = a;
rl = (u64)u.l.low * (u64)b;
rh = (u64)u.l.high * (u64)b;
rh += (rl >> 32);
res.l.high = div64_u64(rh, c);
res.l.low = div64_u64(((mod_64(rh, c) << 32) + (rl & 0xffffffff)), c);
return res.ll;
}
static void pit_set_gate(struct kvm *kvm, int channel, u32 val)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
switch (c->mode) {
default:
case 0:
case 4:
/* XXX: just disable/enable counting */
break;
case 1:
case 2:
case 3:
case 5:
/* Restart counting on rising edge. */
if (c->gate < val)
c->count_load_time = ktime_get();
break;
}
c->gate = val;
}
static int pit_get_gate(struct kvm *kvm, int channel)
{
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
return kvm->arch.vpit->pit_state.channels[channel].gate;
}
static s64 __kpit_elapsed(struct kvm *kvm)
{
s64 elapsed;
ktime_t remaining;
struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state;
if (!ps->pit_timer.period)
return 0;
/*
* The Counter does not stop when it reaches zero. In
* Modes 0, 1, 4, and 5 the Counter ``wraps around'' to
* the highest count, either FFFF hex for binary counting
* or 9999 for BCD counting, and continues counting.
* Modes 2 and 3 are periodic; the Counter reloads
* itself with the initial count and continues counting
* from there.
*/
remaining = hrtimer_get_remaining(&ps->pit_timer.timer);
elapsed = ps->pit_timer.period - ktime_to_ns(remaining);
elapsed = mod_64(elapsed, ps->pit_timer.period);
return elapsed;
}
static s64 kpit_elapsed(struct kvm *kvm, struct kvm_kpit_channel_state *c,
int channel)
{
if (channel == 0)
return __kpit_elapsed(kvm);
return ktime_to_ns(ktime_sub(ktime_get(), c->count_load_time));
}
static int pit_get_count(struct kvm *kvm, int channel)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
s64 d, t;
int counter;
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
t = kpit_elapsed(kvm, c, channel);
d = muldiv64(t, KVM_PIT_FREQ, NSEC_PER_SEC);
switch (c->mode) {
case 0:
case 1:
case 4:
case 5:
counter = (c->count - d) & 0xffff;
break;
case 3:
/* XXX: may be incorrect for odd counts */
counter = c->count - (mod_64((2 * d), c->count));
break;
default:
counter = c->count - mod_64(d, c->count);
break;
}
return counter;
}
static int pit_get_out(struct kvm *kvm, int channel)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
s64 d, t;
int out;
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
t = kpit_elapsed(kvm, c, channel);
d = muldiv64(t, KVM_PIT_FREQ, NSEC_PER_SEC);
switch (c->mode) {
default:
case 0:
out = (d >= c->count);
break;
case 1:
out = (d < c->count);
break;
case 2:
out = ((mod_64(d, c->count) == 0) && (d != 0));
break;
case 3:
out = (mod_64(d, c->count) < ((c->count + 1) >> 1));
break;
case 4:
case 5:
out = (d == c->count);
break;
}
return out;
}
static void pit_latch_count(struct kvm *kvm, int channel)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
if (!c->count_latched) {
c->latched_count = pit_get_count(kvm, channel);
c->count_latched = c->rw_mode;
}
}
static void pit_latch_status(struct kvm *kvm, int channel)
{
struct kvm_kpit_channel_state *c =
&kvm->arch.vpit->pit_state.channels[channel];
WARN_ON(!mutex_is_locked(&kvm->arch.vpit->pit_state.lock));
if (!c->status_latched) {
/* TODO: Return NULL COUNT (bit 6). */
c->status = ((pit_get_out(kvm, channel) << 7) |
(c->rw_mode << 4) |
(c->mode << 1) |
c->bcd);
c->status_latched = 1;
}
}
static void kvm_pit_ack_irq(struct kvm_irq_ack_notifier *kian)
{
struct kvm_kpit_state *ps = container_of(kian, struct kvm_kpit_state,
irq_ack_notifier);
int value;
spin_lock(&ps->inject_lock);
value = atomic_dec_return(&ps->pit_timer.pending);
if (value < 0)
/* spurious acks can be generated if, for example, the
* PIC is being reset. Handle it gracefully here
*/
atomic_inc(&ps->pit_timer.pending);
else if (value > 0)
/* in this case, we had multiple outstanding pit interrupts
* that we needed to inject. Reinject
*/
queue_work(ps->pit->wq, &ps->pit->expired);
ps->irq_ack = 1;
spin_unlock(&ps->inject_lock);
}
void __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu)
{
struct kvm_pit *pit = vcpu->kvm->arch.vpit;
struct hrtimer *timer;
if (!kvm_vcpu_is_bsp(vcpu) || !pit)
return;
timer = &pit->pit_state.pit_timer.timer;
if (hrtimer_cancel(timer))
hrtimer_start_expires(timer, HRTIMER_MODE_ABS);
}
static void destroy_pit_timer(struct kvm_pit *pit)
{
hrtimer_cancel(&pit->pit_state.pit_timer.timer);
cancel_work_sync(&pit->expired);
}
static bool kpit_is_periodic(struct kvm_timer *ktimer)
{
struct kvm_kpit_state *ps = container_of(ktimer, struct kvm_kpit_state,
pit_timer);
return ps->is_periodic;
}
static struct kvm_timer_ops kpit_ops = {
.is_periodic = kpit_is_periodic,
};
static void pit_do_work(struct work_struct *work)
{
struct kvm_pit *pit = container_of(work, struct kvm_pit, expired);
struct kvm *kvm = pit->kvm;
struct kvm_vcpu *vcpu;
int i;
struct kvm_kpit_state *ps = &pit->pit_state;
int inject = 0;
/* Try to inject pending interrupts when
* last one has been acked.
*/
spin_lock(&ps->inject_lock);
if (ps->irq_ack) {
ps->irq_ack = 0;
inject = 1;
}
spin_unlock(&ps->inject_lock);
if (inject) {
kvm_set_irq(kvm, kvm->arch.vpit->irq_source_id, 0, 1);
kvm_set_irq(kvm, kvm->arch.vpit->irq_source_id, 0, 0);
/*
* Provides NMI watchdog support via Virtual Wire mode.
* The route is: PIT -> PIC -> LVT0 in NMI mode.
*
* Note: Our Virtual Wire implementation is simplified, only
* propagating PIT interrupts to all VCPUs when they have set
* LVT0 to NMI delivery. Other PIC interrupts are just sent to
* VCPU0, and only if its LVT0 is in EXTINT mode.
*/
if (kvm->arch.vapics_in_nmi_mode > 0)
kvm_for_each_vcpu(i, vcpu, kvm)
kvm_apic_nmi_wd_deliver(vcpu);
}
}
static enum hrtimer_restart pit_timer_fn(struct hrtimer *data)
{
struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
struct kvm_pit *pt = ktimer->kvm->arch.vpit;
if (ktimer->reinject || !atomic_read(&ktimer->pending)) {
atomic_inc(&ktimer->pending);
queue_work(pt->wq, &pt->expired);
}
if (ktimer->t_ops->is_periodic(ktimer)) {
hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
return HRTIMER_RESTART;
} else
return HRTIMER_NORESTART;
}
static void create_pit_timer(struct kvm *kvm, u32 val, int is_period)
{
struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state;
struct kvm_timer *pt = &ps->pit_timer;
s64 interval;
if (!irqchip_in_kernel(kvm) || ps->flags & KVM_PIT_FLAGS_HPET_LEGACY)
return;
interval = muldiv64(val, NSEC_PER_SEC, KVM_PIT_FREQ);
pr_debug("create pit timer, interval is %llu nsec\n", interval);
/* TODO The new value only affected after the retriggered */
hrtimer_cancel(&pt->timer);
cancel_work_sync(&ps->pit->expired);
pt->period = interval;
ps->is_periodic = is_period;
pt->timer.function = pit_timer_fn;
pt->t_ops = &kpit_ops;
pt->kvm = ps->pit->kvm;
atomic_set(&pt->pending, 0);
ps->irq_ack = 1;
hrtimer_start(&pt->timer, ktime_add_ns(ktime_get(), interval),
HRTIMER_MODE_ABS);
}
static void pit_load_count(struct kvm *kvm, int channel, u32 val)
{
struct kvm_kpit_state *ps = &kvm->arch.vpit->pit_state;
WARN_ON(!mutex_is_locked(&ps->lock));
pr_debug("load_count val is %d, channel is %d\n", val, channel);
/*
* The largest possible initial count is 0; this is equivalent
* to 216 for binary counting and 104 for BCD counting.
*/
if (val == 0)
val = 0x10000;
ps->channels[channel].count = val;
if (channel != 0) {
ps->channels[channel].count_load_time = ktime_get();
return;
}
/* Two types of timer
* mode 1 is one shot, mode 2 is period, otherwise del timer */
switch (ps->channels[0].mode) {
case 0:
case 1:
/* FIXME: enhance mode 4 precision */
case 4:
create_pit_timer(kvm, val, 0);
break;
case 2:
case 3:
create_pit_timer(kvm, val, 1);
break;
default:
destroy_pit_timer(kvm->arch.vpit);
}
}
void kvm_pit_load_count(struct kvm *kvm, int channel, u32 val, int hpet_legacy_start)
{
u8 saved_mode;
if (hpet_legacy_start) {
/* save existing mode for later reenablement */
saved_mode = kvm->arch.vpit->pit_state.channels[0].mode;
kvm->arch.vpit->pit_state.channels[0].mode = 0xff; /* disable timer */
pit_load_count(kvm, channel, val);
kvm->arch.vpit->pit_state.channels[0].mode = saved_mode;
} else {
pit_load_count(kvm, channel, val);
}
}
static inline struct kvm_pit *dev_to_pit(struct kvm_io_device *dev)
{
return container_of(dev, struct kvm_pit, dev);
}
static inline struct kvm_pit *speaker_to_pit(struct kvm_io_device *dev)
{
return container_of(dev, struct kvm_pit, speaker_dev);
}
static inline int pit_in_range(gpa_t addr)
{
return ((addr >= KVM_PIT_BASE_ADDRESS) &&
(addr < KVM_PIT_BASE_ADDRESS + KVM_PIT_MEM_LENGTH));
}
static int pit_ioport_write(struct kvm_io_device *this,
gpa_t addr, int len, const void *data)
{
struct kvm_pit *pit = dev_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
int channel, access;
struct kvm_kpit_channel_state *s;
u32 val = *(u32 *) data;
if (!pit_in_range(addr))
return -EOPNOTSUPP;
val &= 0xff;
addr &= KVM_PIT_CHANNEL_MASK;
mutex_lock(&pit_state->lock);
if (val != 0)
pr_debug("write addr is 0x%x, len is %d, val is 0x%x\n",
(unsigned int)addr, len, val);
if (addr == 3) {
channel = val >> 6;
if (channel == 3) {
/* Read-Back Command. */
for (channel = 0; channel < 3; channel++) {
s = &pit_state->channels[channel];
if (val & (2 << channel)) {
if (!(val & 0x20))
pit_latch_count(kvm, channel);
if (!(val & 0x10))
pit_latch_status(kvm, channel);
}
}
} else {
/* Select Counter <channel>. */
s = &pit_state->channels[channel];
access = (val >> 4) & KVM_PIT_CHANNEL_MASK;
if (access == 0) {
pit_latch_count(kvm, channel);
} else {
s->rw_mode = access;
s->read_state = access;
s->write_state = access;
s->mode = (val >> 1) & 7;
if (s->mode > 5)
s->mode -= 4;
s->bcd = val & 1;
}
}
} else {
/* Write Count. */
s = &pit_state->channels[addr];
switch (s->write_state) {
default:
case RW_STATE_LSB:
pit_load_count(kvm, addr, val);
break;
case RW_STATE_MSB:
pit_load_count(kvm, addr, val << 8);
break;
case RW_STATE_WORD0:
s->write_latch = val;
s->write_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
pit_load_count(kvm, addr, s->write_latch | (val << 8));
s->write_state = RW_STATE_WORD0;
break;
}
}
mutex_unlock(&pit_state->lock);
return 0;
}
static int pit_ioport_read(struct kvm_io_device *this,
gpa_t addr, int len, void *data)
{
struct kvm_pit *pit = dev_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
int ret, count;
struct kvm_kpit_channel_state *s;
if (!pit_in_range(addr))
return -EOPNOTSUPP;
addr &= KVM_PIT_CHANNEL_MASK;
if (addr == 3)
return 0;
s = &pit_state->channels[addr];
mutex_lock(&pit_state->lock);
if (s->status_latched) {
s->status_latched = 0;
ret = s->status;
} else if (s->count_latched) {
switch (s->count_latched) {
default:
case RW_STATE_LSB:
ret = s->latched_count & 0xff;
s->count_latched = 0;
break;
case RW_STATE_MSB:
ret = s->latched_count >> 8;
s->count_latched = 0;
break;
case RW_STATE_WORD0:
ret = s->latched_count & 0xff;
s->count_latched = RW_STATE_MSB;
break;
}
} else {
switch (s->read_state) {
default:
case RW_STATE_LSB:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
break;
case RW_STATE_MSB:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
break;
case RW_STATE_WORD0:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
s->read_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
s->read_state = RW_STATE_WORD0;
break;
}
}
if (len > sizeof(ret))
len = sizeof(ret);
memcpy(data, (char *)&ret, len);
mutex_unlock(&pit_state->lock);
return 0;
}
static int speaker_ioport_write(struct kvm_io_device *this,
gpa_t addr, int len, const void *data)
{
struct kvm_pit *pit = speaker_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
u32 val = *(u32 *) data;
if (addr != KVM_SPEAKER_BASE_ADDRESS)
return -EOPNOTSUPP;
mutex_lock(&pit_state->lock);
pit_state->speaker_data_on = (val >> 1) & 1;
pit_set_gate(kvm, 2, val & 1);
mutex_unlock(&pit_state->lock);
return 0;
}
static int speaker_ioport_read(struct kvm_io_device *this,
gpa_t addr, int len, void *data)
{
struct kvm_pit *pit = speaker_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
unsigned int refresh_clock;
int ret;
if (addr != KVM_SPEAKER_BASE_ADDRESS)
return -EOPNOTSUPP;
/* Refresh clock toggles at about 15us. We approximate as 2^14ns. */
refresh_clock = ((unsigned int)ktime_to_ns(ktime_get()) >> 14) & 1;
mutex_lock(&pit_state->lock);
ret = ((pit_state->speaker_data_on << 1) | pit_get_gate(kvm, 2) |
(pit_get_out(kvm, 2) << 5) | (refresh_clock << 4));
if (len > sizeof(ret))
len = sizeof(ret);
memcpy(data, (char *)&ret, len);
mutex_unlock(&pit_state->lock);
return 0;
}
void kvm_pit_reset(struct kvm_pit *pit)
{
int i;
struct kvm_kpit_channel_state *c;
mutex_lock(&pit->pit_state.lock);
pit->pit_state.flags = 0;
for (i = 0; i < 3; i++) {
c = &pit->pit_state.channels[i];
c->mode = 0xff;
c->gate = (i != 2);
pit_load_count(pit->kvm, i, 0);
}
mutex_unlock(&pit->pit_state.lock);
atomic_set(&pit->pit_state.pit_timer.pending, 0);
pit->pit_state.irq_ack = 1;
}
static void pit_mask_notifer(struct kvm_irq_mask_notifier *kimn, bool mask)
{
struct kvm_pit *pit = container_of(kimn, struct kvm_pit, mask_notifier);
if (!mask) {
atomic_set(&pit->pit_state.pit_timer.pending, 0);
pit->pit_state.irq_ack = 1;
}
}
static const struct kvm_io_device_ops pit_dev_ops = {
.read = pit_ioport_read,
.write = pit_ioport_write,
};
static const struct kvm_io_device_ops speaker_dev_ops = {
.read = speaker_ioport_read,
.write = speaker_ioport_write,
};
/* Caller must hold slots_lock */
struct kvm_pit *kvm_create_pit(struct kvm *kvm, u32 flags)
{
struct kvm_pit *pit;
struct kvm_kpit_state *pit_state;
int ret;
pit = kzalloc(sizeof(struct kvm_pit), GFP_KERNEL);
if (!pit)
return NULL;
pit->irq_source_id = kvm_request_irq_source_id(kvm);
if (pit->irq_source_id < 0) {
kfree(pit);
return NULL;
}
mutex_init(&pit->pit_state.lock);
mutex_lock(&pit->pit_state.lock);
spin_lock_init(&pit->pit_state.inject_lock);
pit->wq = create_singlethread_workqueue("kvm-pit-wq");
if (!pit->wq) {
mutex_unlock(&pit->pit_state.lock);
kvm_free_irq_source_id(kvm, pit->irq_source_id);
kfree(pit);
return NULL;
}
INIT_WORK(&pit->expired, pit_do_work);
kvm->arch.vpit = pit;
pit->kvm = kvm;
pit_state = &pit->pit_state;
pit_state->pit = pit;
hrtimer_init(&pit_state->pit_timer.timer,
CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
pit_state->irq_ack_notifier.gsi = 0;
pit_state->irq_ack_notifier.irq_acked = kvm_pit_ack_irq;
kvm_register_irq_ack_notifier(kvm, &pit_state->irq_ack_notifier);
pit_state->pit_timer.reinject = true;
mutex_unlock(&pit->pit_state.lock);
kvm_pit_reset(pit);
pit->mask_notifier.func = pit_mask_notifer;
kvm_register_irq_mask_notifier(kvm, 0, &pit->mask_notifier);
kvm_iodevice_init(&pit->dev, &pit_dev_ops);
ret = kvm_io_bus_register_dev(kvm, KVM_PIO_BUS, KVM_PIT_BASE_ADDRESS,
KVM_PIT_MEM_LENGTH, &pit->dev);
if (ret < 0)
goto fail;
if (flags & KVM_PIT_SPEAKER_DUMMY) {
kvm_iodevice_init(&pit->speaker_dev, &speaker_dev_ops);
ret = kvm_io_bus_register_dev(kvm, KVM_PIO_BUS,
KVM_SPEAKER_BASE_ADDRESS, 4,
&pit->speaker_dev);
if (ret < 0)
goto fail_unregister;
}
return pit;
fail_unregister:
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &pit->dev);
fail:
kvm_unregister_irq_mask_notifier(kvm, 0, &pit->mask_notifier);
kvm_unregister_irq_ack_notifier(kvm, &pit_state->irq_ack_notifier);
kvm_free_irq_source_id(kvm, pit->irq_source_id);
destroy_workqueue(pit->wq);
kfree(pit);
return NULL;
}
void kvm_free_pit(struct kvm *kvm)
{
struct hrtimer *timer;
if (kvm->arch.vpit) {
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS, &kvm->arch.vpit->dev);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&kvm->arch.vpit->speaker_dev);
kvm_unregister_irq_mask_notifier(kvm, 0,
&kvm->arch.vpit->mask_notifier);
kvm_unregister_irq_ack_notifier(kvm,
&kvm->arch.vpit->pit_state.irq_ack_notifier);
mutex_lock(&kvm->arch.vpit->pit_state.lock);
timer = &kvm->arch.vpit->pit_state.pit_timer.timer;
hrtimer_cancel(timer);
cancel_work_sync(&kvm->arch.vpit->expired);
kvm_free_irq_source_id(kvm, kvm->arch.vpit->irq_source_id);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
destroy_workqueue(kvm->arch.vpit->wq);
kfree(kvm->arch.vpit);
}
}
| gpl-2.0 |
Lime1iME/Testing | drivers/leds/leds-wrap.c | 4742 | 3300 | /*
* LEDs driver for PCEngines WRAP
*
* Copyright (C) 2006 Kristian Kielhofner <kris@krisk.org>
*
* Based on leds-net48xx.c
*
* 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 <asm/io.h>
#include <linux/scx200_gpio.h>
#define DRVNAME "wrap-led"
#define WRAP_POWER_LED_GPIO 2
#define WRAP_ERROR_LED_GPIO 3
#define WRAP_EXTRA_LED_GPIO 18
static struct platform_device *pdev;
static void wrap_power_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value)
scx200_gpio_set_low(WRAP_POWER_LED_GPIO);
else
scx200_gpio_set_high(WRAP_POWER_LED_GPIO);
}
static void wrap_error_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value)
scx200_gpio_set_low(WRAP_ERROR_LED_GPIO);
else
scx200_gpio_set_high(WRAP_ERROR_LED_GPIO);
}
static void wrap_extra_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
if (value)
scx200_gpio_set_low(WRAP_EXTRA_LED_GPIO);
else
scx200_gpio_set_high(WRAP_EXTRA_LED_GPIO);
}
static struct led_classdev wrap_power_led = {
.name = "wrap::power",
.brightness_set = wrap_power_led_set,
.default_trigger = "default-on",
.flags = LED_CORE_SUSPENDRESUME,
};
static struct led_classdev wrap_error_led = {
.name = "wrap::error",
.brightness_set = wrap_error_led_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static struct led_classdev wrap_extra_led = {
.name = "wrap::extra",
.brightness_set = wrap_extra_led_set,
.flags = LED_CORE_SUSPENDRESUME,
};
static int wrap_led_probe(struct platform_device *pdev)
{
int ret;
ret = led_classdev_register(&pdev->dev, &wrap_power_led);
if (ret < 0)
return ret;
ret = led_classdev_register(&pdev->dev, &wrap_error_led);
if (ret < 0)
goto err1;
ret = led_classdev_register(&pdev->dev, &wrap_extra_led);
if (ret < 0)
goto err2;
return ret;
err2:
led_classdev_unregister(&wrap_error_led);
err1:
led_classdev_unregister(&wrap_power_led);
return ret;
}
static int wrap_led_remove(struct platform_device *pdev)
{
led_classdev_unregister(&wrap_power_led);
led_classdev_unregister(&wrap_error_led);
led_classdev_unregister(&wrap_extra_led);
return 0;
}
static struct platform_driver wrap_led_driver = {
.probe = wrap_led_probe,
.remove = wrap_led_remove,
.driver = {
.name = DRVNAME,
.owner = THIS_MODULE,
},
};
static int __init wrap_led_init(void)
{
int ret;
if (!scx200_gpio_present()) {
ret = -ENODEV;
goto out;
}
ret = platform_driver_register(&wrap_led_driver);
if (ret < 0)
goto out;
pdev = platform_device_register_simple(DRVNAME, -1, NULL, 0);
if (IS_ERR(pdev)) {
ret = PTR_ERR(pdev);
platform_driver_unregister(&wrap_led_driver);
goto out;
}
out:
return ret;
}
static void __exit wrap_led_exit(void)
{
platform_device_unregister(pdev);
platform_driver_unregister(&wrap_led_driver);
}
module_init(wrap_led_init);
module_exit(wrap_led_exit);
MODULE_AUTHOR("Kristian Kielhofner <kris@krisk.org>");
MODULE_DESCRIPTION("PCEngines WRAP LED driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Christopher83/samsung-kernel-msm7x30 | arch/powerpc/sysdev/rtc_cmos_setup.c | 4998 | 1616 | /*
* Setup code for PC-style Real-Time Clock.
*
* Author: Wade Farnsworth <wfarnsworth@mvista.com>
*
* 2007 (c) MontaVista Software, Inc. This file is licensed under
* the terms of the GNU General Public License version 2. This program
* is licensed "as is" without any warranty of any kind, whether express
* or implied.
*/
#include <linux/platform_device.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/mc146818rtc.h>
#include <asm/prom.h>
static int __init add_rtc(void)
{
struct device_node *np;
struct platform_device *pd;
struct resource res[2];
unsigned int num_res = 1;
int ret;
memset(&res, 0, sizeof(res));
np = of_find_compatible_node(NULL, NULL, "pnpPNP,b00");
if (!np)
return -ENODEV;
ret = of_address_to_resource(np, 0, &res[0]);
of_node_put(np);
if (ret)
return ret;
/*
* RTC_PORT(x) is hardcoded in asm/mc146818rtc.h. Verify that the
* address provided by the device node matches.
*/
if (res[0].start != RTC_PORT(0))
return -EINVAL;
np = of_find_compatible_node(NULL, NULL, "chrp,iic");
if (!np)
np = of_find_compatible_node(NULL, NULL, "pnpPNP,000");
if (np) {
of_node_put(np);
/*
* Use a fixed interrupt value of 8 since on PPC if we are
* using this its off an i8259 which we ensure has interrupt
* numbers 0..15.
*/
res[1].start = 8;
res[1].end = 8;
res[1].flags = IORESOURCE_IRQ;
num_res++;
}
pd = platform_device_register_simple("rtc_cmos", -1,
&res[0], num_res);
if (IS_ERR(pd))
return PTR_ERR(pd);
return 0;
}
fs_initcall(add_rtc);
MODULE_LICENSE("GPL");
| gpl-2.0 |
showp1984/bricked-flo | drivers/video/fbcmap.c | 6278 | 8660 | /*
* linux/drivers/video/fbcmap.c -- Colormap handling for frame buffer devices
*
* Created 15 Jun 1997 by Geert Uytterhoeven
*
* 2001 - Documented with DocBook
* - Brad Douglas <brad@neruo.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/string.h>
#include <linux/module.h>
#include <linux/fb.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
static u16 red2[] __read_mostly = {
0x0000, 0xaaaa
};
static u16 green2[] __read_mostly = {
0x0000, 0xaaaa
};
static u16 blue2[] __read_mostly = {
0x0000, 0xaaaa
};
static u16 red4[] __read_mostly = {
0x0000, 0xaaaa, 0x5555, 0xffff
};
static u16 green4[] __read_mostly = {
0x0000, 0xaaaa, 0x5555, 0xffff
};
static u16 blue4[] __read_mostly = {
0x0000, 0xaaaa, 0x5555, 0xffff
};
static u16 red8[] __read_mostly = {
0x0000, 0x0000, 0x0000, 0x0000, 0xaaaa, 0xaaaa, 0xaaaa, 0xaaaa
};
static u16 green8[] __read_mostly = {
0x0000, 0x0000, 0xaaaa, 0xaaaa, 0x0000, 0x0000, 0x5555, 0xaaaa
};
static u16 blue8[] __read_mostly = {
0x0000, 0xaaaa, 0x0000, 0xaaaa, 0x0000, 0xaaaa, 0x0000, 0xaaaa
};
static u16 red16[] __read_mostly = {
0x0000, 0x0000, 0x0000, 0x0000, 0xaaaa, 0xaaaa, 0xaaaa, 0xaaaa,
0x5555, 0x5555, 0x5555, 0x5555, 0xffff, 0xffff, 0xffff, 0xffff
};
static u16 green16[] __read_mostly = {
0x0000, 0x0000, 0xaaaa, 0xaaaa, 0x0000, 0x0000, 0x5555, 0xaaaa,
0x5555, 0x5555, 0xffff, 0xffff, 0x5555, 0x5555, 0xffff, 0xffff
};
static u16 blue16[] __read_mostly = {
0x0000, 0xaaaa, 0x0000, 0xaaaa, 0x0000, 0xaaaa, 0x0000, 0xaaaa,
0x5555, 0xffff, 0x5555, 0xffff, 0x5555, 0xffff, 0x5555, 0xffff
};
static const struct fb_cmap default_2_colors = {
.len=2, .red=red2, .green=green2, .blue=blue2
};
static const struct fb_cmap default_8_colors = {
.len=8, .red=red8, .green=green8, .blue=blue8
};
static const struct fb_cmap default_4_colors = {
.len=4, .red=red4, .green=green4, .blue=blue4
};
static const struct fb_cmap default_16_colors = {
.len=16, .red=red16, .green=green16, .blue=blue16
};
/**
* fb_alloc_cmap - allocate a colormap
* @cmap: frame buffer colormap structure
* @len: length of @cmap
* @transp: boolean, 1 if there is transparency, 0 otherwise
* @flags: flags for kmalloc memory allocation
*
* Allocates memory for a colormap @cmap. @len is the
* number of entries in the palette.
*
* Returns negative errno on error, or zero on success.
*
*/
int fb_alloc_cmap_gfp(struct fb_cmap *cmap, int len, int transp, gfp_t flags)
{
int size = len * sizeof(u16);
int ret = -ENOMEM;
if (cmap->len != len) {
fb_dealloc_cmap(cmap);
if (!len)
return 0;
cmap->red = kmalloc(size, flags);
if (!cmap->red)
goto fail;
cmap->green = kmalloc(size, flags);
if (!cmap->green)
goto fail;
cmap->blue = kmalloc(size, flags);
if (!cmap->blue)
goto fail;
if (transp) {
cmap->transp = kmalloc(size, flags);
if (!cmap->transp)
goto fail;
} else {
cmap->transp = NULL;
}
}
cmap->start = 0;
cmap->len = len;
ret = fb_copy_cmap(fb_default_cmap(len), cmap);
if (ret)
goto fail;
return 0;
fail:
fb_dealloc_cmap(cmap);
return ret;
}
int fb_alloc_cmap(struct fb_cmap *cmap, int len, int transp)
{
return fb_alloc_cmap_gfp(cmap, len, transp, GFP_ATOMIC);
}
/**
* fb_dealloc_cmap - deallocate a colormap
* @cmap: frame buffer colormap structure
*
* Deallocates a colormap that was previously allocated with
* fb_alloc_cmap().
*
*/
void fb_dealloc_cmap(struct fb_cmap *cmap)
{
kfree(cmap->red);
kfree(cmap->green);
kfree(cmap->blue);
kfree(cmap->transp);
cmap->red = cmap->green = cmap->blue = cmap->transp = NULL;
cmap->len = 0;
}
/**
* fb_copy_cmap - copy a colormap
* @from: frame buffer colormap structure
* @to: frame buffer colormap structure
*
* Copy contents of colormap from @from to @to.
*/
int fb_copy_cmap(const struct fb_cmap *from, struct fb_cmap *to)
{
int tooff = 0, fromoff = 0;
int size;
if (to->start > from->start)
fromoff = to->start - from->start;
else
tooff = from->start - to->start;
size = to->len - tooff;
if (size > (int) (from->len - fromoff))
size = from->len - fromoff;
if (size <= 0)
return -EINVAL;
size *= sizeof(u16);
memcpy(to->red+tooff, from->red+fromoff, size);
memcpy(to->green+tooff, from->green+fromoff, size);
memcpy(to->blue+tooff, from->blue+fromoff, size);
if (from->transp && to->transp)
memcpy(to->transp+tooff, from->transp+fromoff, size);
return 0;
}
int fb_cmap_to_user(const struct fb_cmap *from, struct fb_cmap_user *to)
{
int tooff = 0, fromoff = 0;
int size;
if (to->start > from->start)
fromoff = to->start - from->start;
else
tooff = from->start - to->start;
size = to->len - tooff;
if (size > (int) (from->len - fromoff))
size = from->len - fromoff;
if (size <= 0)
return -EINVAL;
size *= sizeof(u16);
if (copy_to_user(to->red+tooff, from->red+fromoff, size))
return -EFAULT;
if (copy_to_user(to->green+tooff, from->green+fromoff, size))
return -EFAULT;
if (copy_to_user(to->blue+tooff, from->blue+fromoff, size))
return -EFAULT;
if (from->transp && to->transp)
if (copy_to_user(to->transp+tooff, from->transp+fromoff, size))
return -EFAULT;
return 0;
}
/**
* fb_set_cmap - set the colormap
* @cmap: frame buffer colormap structure
* @info: frame buffer info structure
*
* Sets the colormap @cmap for a screen of device @info.
*
* Returns negative errno on error, or zero on success.
*
*/
int fb_set_cmap(struct fb_cmap *cmap, struct fb_info *info)
{
int i, start, rc = 0;
u16 *red, *green, *blue, *transp;
u_int hred, hgreen, hblue, htransp = 0xffff;
red = cmap->red;
green = cmap->green;
blue = cmap->blue;
transp = cmap->transp;
start = cmap->start;
if (start < 0 || (!info->fbops->fb_setcolreg &&
!info->fbops->fb_setcmap))
return -EINVAL;
if (info->fbops->fb_setcmap) {
rc = info->fbops->fb_setcmap(cmap, info);
} else {
for (i = 0; i < cmap->len; i++) {
hred = *red++;
hgreen = *green++;
hblue = *blue++;
if (transp)
htransp = *transp++;
if (info->fbops->fb_setcolreg(start++,
hred, hgreen, hblue,
htransp, info))
break;
}
}
if (rc == 0)
fb_copy_cmap(cmap, &info->cmap);
return rc;
}
int fb_set_user_cmap(struct fb_cmap_user *cmap, struct fb_info *info)
{
int rc, size = cmap->len * sizeof(u16);
struct fb_cmap umap;
if (size < 0 || size < cmap->len)
return -E2BIG;
memset(&umap, 0, sizeof(struct fb_cmap));
rc = fb_alloc_cmap_gfp(&umap, cmap->len, cmap->transp != NULL,
GFP_KERNEL);
if (rc)
return rc;
if (copy_from_user(umap.red, cmap->red, size) ||
copy_from_user(umap.green, cmap->green, size) ||
copy_from_user(umap.blue, cmap->blue, size) ||
(cmap->transp && copy_from_user(umap.transp, cmap->transp, size))) {
rc = -EFAULT;
goto out;
}
umap.start = cmap->start;
if (!lock_fb_info(info)) {
rc = -ENODEV;
goto out;
}
if (cmap->start < 0 || (!info->fbops->fb_setcolreg &&
!info->fbops->fb_setcmap)) {
rc = -EINVAL;
goto out1;
}
rc = fb_set_cmap(&umap, info);
out1:
unlock_fb_info(info);
out:
fb_dealloc_cmap(&umap);
return rc;
}
/**
* fb_default_cmap - get default colormap
* @len: size of palette for a depth
*
* Gets the default colormap for a specific screen depth. @len
* is the size of the palette for a particular screen depth.
*
* Returns pointer to a frame buffer colormap structure.
*
*/
const struct fb_cmap *fb_default_cmap(int len)
{
if (len <= 2)
return &default_2_colors;
if (len <= 4)
return &default_4_colors;
if (len <= 8)
return &default_8_colors;
return &default_16_colors;
}
/**
* fb_invert_cmaps - invert all defaults colormaps
*
* Invert all default colormaps.
*
*/
void fb_invert_cmaps(void)
{
u_int i;
for (i = 0; i < ARRAY_SIZE(red2); i++) {
red2[i] = ~red2[i];
green2[i] = ~green2[i];
blue2[i] = ~blue2[i];
}
for (i = 0; i < ARRAY_SIZE(red4); i++) {
red4[i] = ~red4[i];
green4[i] = ~green4[i];
blue4[i] = ~blue4[i];
}
for (i = 0; i < ARRAY_SIZE(red8); i++) {
red8[i] = ~red8[i];
green8[i] = ~green8[i];
blue8[i] = ~blue8[i];
}
for (i = 0; i < ARRAY_SIZE(red16); i++) {
red16[i] = ~red16[i];
green16[i] = ~green16[i];
blue16[i] = ~blue16[i];
}
}
/*
* Visible symbols for modules
*/
EXPORT_SYMBOL(fb_alloc_cmap);
EXPORT_SYMBOL(fb_dealloc_cmap);
EXPORT_SYMBOL(fb_copy_cmap);
EXPORT_SYMBOL(fb_set_cmap);
EXPORT_SYMBOL(fb_default_cmap);
EXPORT_SYMBOL(fb_invert_cmaps);
| gpl-2.0 |
DirtyDevs/android_kernel_motorola_ghost | drivers/isdn/hisax/netjet.c | 7302 | 26106 | /* $Id: netjet.c,v 1.29.2.4 2004/02/11 13:21:34 keil Exp $
*
* low level stuff for Traverse Technologie NETJet ISDN cards
*
* Author Karsten Keil
* Copyright by Karsten Keil <keil@isdn4linux.de>
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* Thanks to Traverse Technologies Australia for documents and information
*
* 16-Apr-2002 - led code added - Guy Ellis (guy@traverse.com.au)
*
*/
#include <linux/init.h>
#include "hisax.h"
#include "isac.h"
#include "hscx.h"
#include "isdnl1.h"
#include <linux/interrupt.h>
#include <linux/ppp_defs.h>
#include <linux/slab.h>
#include <asm/io.h>
#include "netjet.h"
/* Interface functions */
u_char
NETjet_ReadIC(struct IsdnCardState *cs, u_char offset)
{
u_char ret;
cs->hw.njet.auxd &= 0xfc;
cs->hw.njet.auxd |= (offset >> 4) & 3;
byteout(cs->hw.njet.auxa, cs->hw.njet.auxd);
ret = bytein(cs->hw.njet.isac + ((offset & 0xf) << 2));
return (ret);
}
void
NETjet_WriteIC(struct IsdnCardState *cs, u_char offset, u_char value)
{
cs->hw.njet.auxd &= 0xfc;
cs->hw.njet.auxd |= (offset >> 4) & 3;
byteout(cs->hw.njet.auxa, cs->hw.njet.auxd);
byteout(cs->hw.njet.isac + ((offset & 0xf) << 2), value);
}
void
NETjet_ReadICfifo(struct IsdnCardState *cs, u_char *data, int size)
{
cs->hw.njet.auxd &= 0xfc;
byteout(cs->hw.njet.auxa, cs->hw.njet.auxd);
insb(cs->hw.njet.isac, data, size);
}
void
NETjet_WriteICfifo(struct IsdnCardState *cs, u_char *data, int size)
{
cs->hw.njet.auxd &= 0xfc;
byteout(cs->hw.njet.auxa, cs->hw.njet.auxd);
outsb(cs->hw.njet.isac, data, size);
}
static void fill_mem(struct BCState *bcs, u_int *pos, u_int cnt, int chan, u_char fill)
{
u_int mask = 0x000000ff, val = 0, *p = pos;
u_int i;
val |= fill;
if (chan) {
val <<= 8;
mask <<= 8;
}
mask ^= 0xffffffff;
for (i = 0; i < cnt; i++) {
*p &= mask;
*p++ |= val;
if (p > bcs->hw.tiger.s_end)
p = bcs->hw.tiger.send;
}
}
static void
mode_tiger(struct BCState *bcs, int mode, int bc)
{
struct IsdnCardState *cs = bcs->cs;
u_char led;
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "Tiger mode %d bchan %d/%d",
mode, bc, bcs->channel);
bcs->mode = mode;
bcs->channel = bc;
switch (mode) {
case (L1_MODE_NULL):
fill_mem(bcs, bcs->hw.tiger.send,
NETJET_DMA_TXSIZE, bc, 0xff);
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "Tiger stat rec %d/%d send %d",
bcs->hw.tiger.r_tot, bcs->hw.tiger.r_err,
bcs->hw.tiger.s_tot);
if ((cs->bcs[0].mode == L1_MODE_NULL) &&
(cs->bcs[1].mode == L1_MODE_NULL)) {
cs->hw.njet.dmactrl = 0;
byteout(cs->hw.njet.base + NETJET_DMACTRL,
cs->hw.njet.dmactrl);
byteout(cs->hw.njet.base + NETJET_IRQMASK0, 0);
}
if (cs->typ == ISDN_CTYPE_NETJET_S)
{
// led off
led = bc & 0x01;
led = 0x01 << (6 + led); // convert to mask
led = ~led;
cs->hw.njet.auxd &= led;
byteout(cs->hw.njet.auxa, cs->hw.njet.auxd);
}
break;
case (L1_MODE_TRANS):
break;
case (L1_MODE_HDLC_56K):
case (L1_MODE_HDLC):
fill_mem(bcs, bcs->hw.tiger.send,
NETJET_DMA_TXSIZE, bc, 0xff);
bcs->hw.tiger.r_state = HDLC_ZERO_SEARCH;
bcs->hw.tiger.r_tot = 0;
bcs->hw.tiger.r_bitcnt = 0;
bcs->hw.tiger.r_one = 0;
bcs->hw.tiger.r_err = 0;
bcs->hw.tiger.s_tot = 0;
if (!cs->hw.njet.dmactrl) {
fill_mem(bcs, bcs->hw.tiger.send,
NETJET_DMA_TXSIZE, !bc, 0xff);
cs->hw.njet.dmactrl = 1;
byteout(cs->hw.njet.base + NETJET_DMACTRL,
cs->hw.njet.dmactrl);
byteout(cs->hw.njet.base + NETJET_IRQMASK0, 0x0f);
/* was 0x3f now 0x0f for TJ300 and TJ320 GE 13/07/00 */
}
bcs->hw.tiger.sendp = bcs->hw.tiger.send;
bcs->hw.tiger.free = NETJET_DMA_TXSIZE;
test_and_set_bit(BC_FLG_EMPTY, &bcs->Flag);
if (cs->typ == ISDN_CTYPE_NETJET_S)
{
// led on
led = bc & 0x01;
led = 0x01 << (6 + led); // convert to mask
cs->hw.njet.auxd |= led;
byteout(cs->hw.njet.auxa, cs->hw.njet.auxd);
}
break;
}
if (cs->debug & L1_DEB_HSCX)
debugl1(cs, "tiger: set %x %x %x %x/%x pulse=%d",
bytein(cs->hw.njet.base + NETJET_DMACTRL),
bytein(cs->hw.njet.base + NETJET_IRQMASK0),
bytein(cs->hw.njet.base + NETJET_IRQSTAT0),
inl(cs->hw.njet.base + NETJET_DMA_READ_ADR),
inl(cs->hw.njet.base + NETJET_DMA_WRITE_ADR),
bytein(cs->hw.njet.base + NETJET_PULSE_CNT));
}
static void printframe(struct IsdnCardState *cs, u_char *buf, int count, char *s) {
char tmp[128];
char *t = tmp;
int i = count, j;
u_char *p = buf;
t += sprintf(t, "tiger %s(%4d)", s, count);
while (i > 0) {
if (i > 16)
j = 16;
else
j = i;
QuickHex(t, p, j);
debugl1(cs, tmp);
p += j;
i -= j;
t = tmp;
t += sprintf(t, "tiger %s ", s);
}
}
// macro for 64k
#define MAKE_RAW_BYTE for (j = 0; j < 8; j++) { \
bitcnt++; \
s_val >>= 1; \
if (val & 1) { \
s_one++; \
s_val |= 0x80; \
} else { \
s_one = 0; \
s_val &= 0x7f; \
} \
if (bitcnt == 8) { \
bcs->hw.tiger.sendbuf[s_cnt++] = s_val; \
bitcnt = 0; \
} \
if (s_one == 5) { \
s_val >>= 1; \
s_val &= 0x7f; \
bitcnt++; \
s_one = 0; \
} \
if (bitcnt == 8) { \
bcs->hw.tiger.sendbuf[s_cnt++] = s_val; \
bitcnt = 0; \
} \
val >>= 1; \
}
static int make_raw_data(struct BCState *bcs) {
// this make_raw is for 64k
register u_int i, s_cnt = 0;
register u_char j;
register u_char val;
register u_char s_one = 0;
register u_char s_val = 0;
register u_char bitcnt = 0;
u_int fcs;
if (!bcs->tx_skb) {
debugl1(bcs->cs, "tiger make_raw: NULL skb");
return (1);
}
bcs->hw.tiger.sendbuf[s_cnt++] = HDLC_FLAG_VALUE;
fcs = PPP_INITFCS;
for (i = 0; i < bcs->tx_skb->len; i++) {
val = bcs->tx_skb->data[i];
fcs = PPP_FCS(fcs, val);
MAKE_RAW_BYTE;
}
fcs ^= 0xffff;
val = fcs & 0xff;
MAKE_RAW_BYTE;
val = (fcs >> 8) & 0xff;
MAKE_RAW_BYTE;
val = HDLC_FLAG_VALUE;
for (j = 0; j < 8; j++) {
bitcnt++;
s_val >>= 1;
if (val & 1)
s_val |= 0x80;
else
s_val &= 0x7f;
if (bitcnt == 8) {
bcs->hw.tiger.sendbuf[s_cnt++] = s_val;
bitcnt = 0;
}
val >>= 1;
}
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger make_raw: in %u out %d.%d",
bcs->tx_skb->len, s_cnt, bitcnt);
if (bitcnt) {
while (8 > bitcnt++) {
s_val >>= 1;
s_val |= 0x80;
}
bcs->hw.tiger.sendbuf[s_cnt++] = s_val;
bcs->hw.tiger.sendbuf[s_cnt++] = 0xff; // NJ<->NJ thoughput bug fix
}
bcs->hw.tiger.sendcnt = s_cnt;
bcs->tx_cnt -= bcs->tx_skb->len;
bcs->hw.tiger.sp = bcs->hw.tiger.sendbuf;
return (0);
}
// macro for 56k
#define MAKE_RAW_BYTE_56K for (j = 0; j < 8; j++) { \
bitcnt++; \
s_val >>= 1; \
if (val & 1) { \
s_one++; \
s_val |= 0x80; \
} else { \
s_one = 0; \
s_val &= 0x7f; \
} \
if (bitcnt == 7) { \
s_val >>= 1; \
s_val |= 0x80; \
bcs->hw.tiger.sendbuf[s_cnt++] = s_val; \
bitcnt = 0; \
} \
if (s_one == 5) { \
s_val >>= 1; \
s_val &= 0x7f; \
bitcnt++; \
s_one = 0; \
} \
if (bitcnt == 7) { \
s_val >>= 1; \
s_val |= 0x80; \
bcs->hw.tiger.sendbuf[s_cnt++] = s_val; \
bitcnt = 0; \
} \
val >>= 1; \
}
static int make_raw_data_56k(struct BCState *bcs) {
// this make_raw is for 56k
register u_int i, s_cnt = 0;
register u_char j;
register u_char val;
register u_char s_one = 0;
register u_char s_val = 0;
register u_char bitcnt = 0;
u_int fcs;
if (!bcs->tx_skb) {
debugl1(bcs->cs, "tiger make_raw_56k: NULL skb");
return (1);
}
val = HDLC_FLAG_VALUE;
for (j = 0; j < 8; j++) {
bitcnt++;
s_val >>= 1;
if (val & 1)
s_val |= 0x80;
else
s_val &= 0x7f;
if (bitcnt == 7) {
s_val >>= 1;
s_val |= 0x80;
bcs->hw.tiger.sendbuf[s_cnt++] = s_val;
bitcnt = 0;
}
val >>= 1;
};
fcs = PPP_INITFCS;
for (i = 0; i < bcs->tx_skb->len; i++) {
val = bcs->tx_skb->data[i];
fcs = PPP_FCS(fcs, val);
MAKE_RAW_BYTE_56K;
}
fcs ^= 0xffff;
val = fcs & 0xff;
MAKE_RAW_BYTE_56K;
val = (fcs >> 8) & 0xff;
MAKE_RAW_BYTE_56K;
val = HDLC_FLAG_VALUE;
for (j = 0; j < 8; j++) {
bitcnt++;
s_val >>= 1;
if (val & 1)
s_val |= 0x80;
else
s_val &= 0x7f;
if (bitcnt == 7) {
s_val >>= 1;
s_val |= 0x80;
bcs->hw.tiger.sendbuf[s_cnt++] = s_val;
bitcnt = 0;
}
val >>= 1;
}
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger make_raw_56k: in %u out %d.%d",
bcs->tx_skb->len, s_cnt, bitcnt);
if (bitcnt) {
while (8 > bitcnt++) {
s_val >>= 1;
s_val |= 0x80;
}
bcs->hw.tiger.sendbuf[s_cnt++] = s_val;
bcs->hw.tiger.sendbuf[s_cnt++] = 0xff; // NJ<->NJ thoughput bug fix
}
bcs->hw.tiger.sendcnt = s_cnt;
bcs->tx_cnt -= bcs->tx_skb->len;
bcs->hw.tiger.sp = bcs->hw.tiger.sendbuf;
return (0);
}
static void got_frame(struct BCState *bcs, int count) {
struct sk_buff *skb;
if (!(skb = dev_alloc_skb(count)))
printk(KERN_WARNING "TIGER: receive out of memory\n");
else {
memcpy(skb_put(skb, count), bcs->hw.tiger.rcvbuf, count);
skb_queue_tail(&bcs->rqueue, skb);
}
test_and_set_bit(B_RCVBUFREADY, &bcs->event);
schedule_work(&bcs->tqueue);
if (bcs->cs->debug & L1_DEB_RECEIVE_FRAME)
printframe(bcs->cs, bcs->hw.tiger.rcvbuf, count, "rec");
}
static void read_raw(struct BCState *bcs, u_int *buf, int cnt) {
int i;
register u_char j;
register u_char val;
u_int *pend = bcs->hw.tiger.rec + NETJET_DMA_RXSIZE - 1;
register u_char state = bcs->hw.tiger.r_state;
register u_char r_one = bcs->hw.tiger.r_one;
register u_char r_val = bcs->hw.tiger.r_val;
register u_int bitcnt = bcs->hw.tiger.r_bitcnt;
u_int *p = buf;
int bits;
u_char mask;
if (bcs->mode == L1_MODE_HDLC) { // it's 64k
mask = 0xff;
bits = 8;
}
else { // it's 56K
mask = 0x7f;
bits = 7;
};
for (i = 0; i < cnt; i++) {
val = bcs->channel ? ((*p >> 8) & 0xff) : (*p & 0xff);
p++;
if (p > pend)
p = bcs->hw.tiger.rec;
if ((val & mask) == mask) {
state = HDLC_ZERO_SEARCH;
bcs->hw.tiger.r_tot++;
bitcnt = 0;
r_one = 0;
continue;
}
for (j = 0; j < bits; j++) {
if (state == HDLC_ZERO_SEARCH) {
if (val & 1) {
r_one++;
} else {
r_one = 0;
state = HDLC_FLAG_SEARCH;
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger read_raw: zBit(%d,%d,%d) %x",
bcs->hw.tiger.r_tot, i, j, val);
}
} else if (state == HDLC_FLAG_SEARCH) {
if (val & 1) {
r_one++;
if (r_one > 6) {
state = HDLC_ZERO_SEARCH;
}
} else {
if (r_one == 6) {
bitcnt = 0;
r_val = 0;
state = HDLC_FLAG_FOUND;
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger read_raw: flag(%d,%d,%d) %x",
bcs->hw.tiger.r_tot, i, j, val);
}
r_one = 0;
}
} else if (state == HDLC_FLAG_FOUND) {
if (val & 1) {
r_one++;
if (r_one > 6) {
state = HDLC_ZERO_SEARCH;
} else {
r_val >>= 1;
r_val |= 0x80;
bitcnt++;
}
} else {
if (r_one == 6) {
bitcnt = 0;
r_val = 0;
r_one = 0;
val >>= 1;
continue;
} else if (r_one != 5) {
r_val >>= 1;
r_val &= 0x7f;
bitcnt++;
}
r_one = 0;
}
if ((state != HDLC_ZERO_SEARCH) &&
!(bitcnt & 7)) {
state = HDLC_FRAME_FOUND;
bcs->hw.tiger.r_fcs = PPP_INITFCS;
bcs->hw.tiger.rcvbuf[0] = r_val;
bcs->hw.tiger.r_fcs = PPP_FCS(bcs->hw.tiger.r_fcs, r_val);
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger read_raw: byte1(%d,%d,%d) rval %x val %x i %x",
bcs->hw.tiger.r_tot, i, j, r_val, val,
bcs->cs->hw.njet.irqstat0);
}
} else if (state == HDLC_FRAME_FOUND) {
if (val & 1) {
r_one++;
if (r_one > 6) {
state = HDLC_ZERO_SEARCH;
bitcnt = 0;
} else {
r_val >>= 1;
r_val |= 0x80;
bitcnt++;
}
} else {
if (r_one == 6) {
r_val = 0;
r_one = 0;
bitcnt++;
if (bitcnt & 7) {
debugl1(bcs->cs, "tiger: frame not byte aligned");
state = HDLC_FLAG_SEARCH;
bcs->hw.tiger.r_err++;
#ifdef ERROR_STATISTIC
bcs->err_inv++;
#endif
} else {
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger frame end(%d,%d): fcs(%x) i %x",
i, j, bcs->hw.tiger.r_fcs, bcs->cs->hw.njet.irqstat0);
if (bcs->hw.tiger.r_fcs == PPP_GOODFCS) {
got_frame(bcs, (bitcnt >> 3) - 3);
} else {
if (bcs->cs->debug) {
debugl1(bcs->cs, "tiger FCS error");
printframe(bcs->cs, bcs->hw.tiger.rcvbuf,
(bitcnt >> 3) - 1, "rec");
bcs->hw.tiger.r_err++;
}
#ifdef ERROR_STATISTIC
bcs->err_crc++;
#endif
}
state = HDLC_FLAG_FOUND;
}
bitcnt = 0;
} else if (r_one == 5) {
val >>= 1;
r_one = 0;
continue;
} else {
r_val >>= 1;
r_val &= 0x7f;
bitcnt++;
}
r_one = 0;
}
if ((state == HDLC_FRAME_FOUND) &&
!(bitcnt & 7)) {
if ((bitcnt >> 3) >= HSCX_BUFMAX) {
debugl1(bcs->cs, "tiger: frame too big");
r_val = 0;
state = HDLC_FLAG_SEARCH;
bcs->hw.tiger.r_err++;
#ifdef ERROR_STATISTIC
bcs->err_inv++;
#endif
} else {
bcs->hw.tiger.rcvbuf[(bitcnt >> 3) - 1] = r_val;
bcs->hw.tiger.r_fcs =
PPP_FCS(bcs->hw.tiger.r_fcs, r_val);
}
}
}
val >>= 1;
}
bcs->hw.tiger.r_tot++;
}
bcs->hw.tiger.r_state = state;
bcs->hw.tiger.r_one = r_one;
bcs->hw.tiger.r_val = r_val;
bcs->hw.tiger.r_bitcnt = bitcnt;
}
void read_tiger(struct IsdnCardState *cs) {
u_int *p;
int cnt = NETJET_DMA_RXSIZE / 2;
if ((cs->hw.njet.irqstat0 & cs->hw.njet.last_is0) & NETJET_IRQM0_READ) {
debugl1(cs, "tiger warn read double dma %x/%x",
cs->hw.njet.irqstat0, cs->hw.njet.last_is0);
#ifdef ERROR_STATISTIC
if (cs->bcs[0].mode)
cs->bcs[0].err_rdo++;
if (cs->bcs[1].mode)
cs->bcs[1].err_rdo++;
#endif
return;
} else {
cs->hw.njet.last_is0 &= ~NETJET_IRQM0_READ;
cs->hw.njet.last_is0 |= (cs->hw.njet.irqstat0 & NETJET_IRQM0_READ);
}
if (cs->hw.njet.irqstat0 & NETJET_IRQM0_READ_1)
p = cs->bcs[0].hw.tiger.rec + NETJET_DMA_RXSIZE - 1;
else
p = cs->bcs[0].hw.tiger.rec + cnt - 1;
if ((cs->bcs[0].mode == L1_MODE_HDLC) || (cs->bcs[0].mode == L1_MODE_HDLC_56K))
read_raw(cs->bcs, p, cnt);
if ((cs->bcs[1].mode == L1_MODE_HDLC) || (cs->bcs[1].mode == L1_MODE_HDLC_56K))
read_raw(cs->bcs + 1, p, cnt);
cs->hw.njet.irqstat0 &= ~NETJET_IRQM0_READ;
}
static void write_raw(struct BCState *bcs, u_int *buf, int cnt);
void netjet_fill_dma(struct BCState *bcs)
{
register u_int *p, *sp;
register int cnt;
if (!bcs->tx_skb)
return;
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger fill_dma1: c%d %4lx", bcs->channel,
bcs->Flag);
if (test_and_set_bit(BC_FLG_BUSY, &bcs->Flag))
return;
if (bcs->mode == L1_MODE_HDLC) { // it's 64k
if (make_raw_data(bcs))
return;
}
else { // it's 56k
if (make_raw_data_56k(bcs))
return;
};
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger fill_dma2: c%d %4lx", bcs->channel,
bcs->Flag);
if (test_and_clear_bit(BC_FLG_NOFRAME, &bcs->Flag)) {
write_raw(bcs, bcs->hw.tiger.sendp, bcs->hw.tiger.free);
} else if (test_and_clear_bit(BC_FLG_HALF, &bcs->Flag)) {
p = bus_to_virt(inl(bcs->cs->hw.njet.base + NETJET_DMA_READ_ADR));
sp = bcs->hw.tiger.sendp;
if (p == bcs->hw.tiger.s_end)
p = bcs->hw.tiger.send - 1;
if (sp == bcs->hw.tiger.s_end)
sp = bcs->hw.tiger.send - 1;
cnt = p - sp;
if (cnt < 0) {
write_raw(bcs, bcs->hw.tiger.sendp, bcs->hw.tiger.free);
} else {
p++;
cnt++;
if (p > bcs->hw.tiger.s_end)
p = bcs->hw.tiger.send;
p++;
cnt++;
if (p > bcs->hw.tiger.s_end)
p = bcs->hw.tiger.send;
write_raw(bcs, p, bcs->hw.tiger.free - cnt);
}
} else if (test_and_clear_bit(BC_FLG_EMPTY, &bcs->Flag)) {
p = bus_to_virt(inl(bcs->cs->hw.njet.base + NETJET_DMA_READ_ADR));
cnt = bcs->hw.tiger.s_end - p;
if (cnt < 2) {
p = bcs->hw.tiger.send + 1;
cnt = NETJET_DMA_TXSIZE / 2 - 2;
} else {
p++;
p++;
if (cnt <= (NETJET_DMA_TXSIZE / 2))
cnt += NETJET_DMA_TXSIZE / 2;
cnt--;
cnt--;
}
write_raw(bcs, p, cnt);
}
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger fill_dma3: c%d %4lx", bcs->channel,
bcs->Flag);
}
static void write_raw(struct BCState *bcs, u_int *buf, int cnt) {
u_int mask, val, *p = buf;
u_int i, s_cnt;
if (cnt <= 0)
return;
if (test_bit(BC_FLG_BUSY, &bcs->Flag)) {
if (bcs->hw.tiger.sendcnt > cnt) {
s_cnt = cnt;
bcs->hw.tiger.sendcnt -= cnt;
} else {
s_cnt = bcs->hw.tiger.sendcnt;
bcs->hw.tiger.sendcnt = 0;
}
if (bcs->channel)
mask = 0xffff00ff;
else
mask = 0xffffff00;
for (i = 0; i < s_cnt; i++) {
val = bcs->channel ? ((bcs->hw.tiger.sp[i] << 8) & 0xff00) :
(bcs->hw.tiger.sp[i]);
*p &= mask;
*p++ |= val;
if (p > bcs->hw.tiger.s_end)
p = bcs->hw.tiger.send;
}
bcs->hw.tiger.s_tot += s_cnt;
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger write_raw: c%d %p-%p %d/%d %d %x", bcs->channel,
buf, p, s_cnt, cnt,
bcs->hw.tiger.sendcnt, bcs->cs->hw.njet.irqstat0);
if (bcs->cs->debug & L1_DEB_HSCX_FIFO)
printframe(bcs->cs, bcs->hw.tiger.sp, s_cnt, "snd");
bcs->hw.tiger.sp += s_cnt;
bcs->hw.tiger.sendp = p;
if (!bcs->hw.tiger.sendcnt) {
if (!bcs->tx_skb) {
debugl1(bcs->cs, "tiger write_raw: NULL skb s_cnt %d", s_cnt);
} else {
if (test_bit(FLG_LLI_L1WAKEUP, &bcs->st->lli.flag) &&
(PACKET_NOACK != bcs->tx_skb->pkt_type)) {
u_long flags;
spin_lock_irqsave(&bcs->aclock, flags);
bcs->ackcnt += bcs->tx_skb->len;
spin_unlock_irqrestore(&bcs->aclock, flags);
schedule_event(bcs, B_ACKPENDING);
}
dev_kfree_skb_any(bcs->tx_skb);
bcs->tx_skb = NULL;
}
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->hw.tiger.free = cnt - s_cnt;
if (bcs->hw.tiger.free > (NETJET_DMA_TXSIZE / 2))
test_and_set_bit(BC_FLG_HALF, &bcs->Flag);
else {
test_and_clear_bit(BC_FLG_HALF, &bcs->Flag);
test_and_set_bit(BC_FLG_NOFRAME, &bcs->Flag);
}
if ((bcs->tx_skb = skb_dequeue(&bcs->squeue))) {
netjet_fill_dma(bcs);
} else {
mask ^= 0xffffffff;
if (s_cnt < cnt) {
for (i = s_cnt; i < cnt; i++) {
*p++ |= mask;
if (p > bcs->hw.tiger.s_end)
p = bcs->hw.tiger.send;
}
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger write_raw: fill rest %d",
cnt - s_cnt);
}
test_and_set_bit(B_XMTBUFREADY, &bcs->event);
schedule_work(&bcs->tqueue);
}
}
} else if (test_and_clear_bit(BC_FLG_NOFRAME, &bcs->Flag)) {
test_and_set_bit(BC_FLG_HALF, &bcs->Flag);
fill_mem(bcs, buf, cnt, bcs->channel, 0xff);
bcs->hw.tiger.free += cnt;
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger write_raw: fill half");
} else if (test_and_clear_bit(BC_FLG_HALF, &bcs->Flag)) {
test_and_set_bit(BC_FLG_EMPTY, &bcs->Flag);
fill_mem(bcs, buf, cnt, bcs->channel, 0xff);
if (bcs->cs->debug & L1_DEB_HSCX)
debugl1(bcs->cs, "tiger write_raw: fill full");
}
}
void write_tiger(struct IsdnCardState *cs) {
u_int *p, cnt = NETJET_DMA_TXSIZE / 2;
if ((cs->hw.njet.irqstat0 & cs->hw.njet.last_is0) & NETJET_IRQM0_WRITE) {
debugl1(cs, "tiger warn write double dma %x/%x",
cs->hw.njet.irqstat0, cs->hw.njet.last_is0);
#ifdef ERROR_STATISTIC
if (cs->bcs[0].mode)
cs->bcs[0].err_tx++;
if (cs->bcs[1].mode)
cs->bcs[1].err_tx++;
#endif
return;
} else {
cs->hw.njet.last_is0 &= ~NETJET_IRQM0_WRITE;
cs->hw.njet.last_is0 |= (cs->hw.njet.irqstat0 & NETJET_IRQM0_WRITE);
}
if (cs->hw.njet.irqstat0 & NETJET_IRQM0_WRITE_1)
p = cs->bcs[0].hw.tiger.send + NETJET_DMA_TXSIZE - 1;
else
p = cs->bcs[0].hw.tiger.send + cnt - 1;
if ((cs->bcs[0].mode == L1_MODE_HDLC) || (cs->bcs[0].mode == L1_MODE_HDLC_56K))
write_raw(cs->bcs, p, cnt);
if ((cs->bcs[1].mode == L1_MODE_HDLC) || (cs->bcs[1].mode == L1_MODE_HDLC_56K))
write_raw(cs->bcs + 1, p, cnt);
cs->hw.njet.irqstat0 &= ~NETJET_IRQM0_WRITE;
}
static void
tiger_l2l1(struct PStack *st, int pr, void *arg)
{
struct BCState *bcs = st->l1.bcs;
struct sk_buff *skb = arg;
u_long flags;
switch (pr) {
case (PH_DATA | REQUEST):
spin_lock_irqsave(&bcs->cs->lock, flags);
if (bcs->tx_skb) {
skb_queue_tail(&bcs->squeue, skb);
} else {
bcs->tx_skb = skb;
bcs->cs->BC_Send_Data(bcs);
}
spin_unlock_irqrestore(&bcs->cs->lock, flags);
break;
case (PH_PULL | INDICATION):
spin_lock_irqsave(&bcs->cs->lock, flags);
if (bcs->tx_skb) {
printk(KERN_WARNING "tiger_l2l1: this shouldn't happen\n");
} else {
bcs->tx_skb = skb;
bcs->cs->BC_Send_Data(bcs);
}
spin_unlock_irqrestore(&bcs->cs->lock, flags);
break;
case (PH_PULL | REQUEST):
if (!bcs->tx_skb) {
test_and_clear_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
st->l1.l1l2(st, PH_PULL | CONFIRM, NULL);
} else
test_and_set_bit(FLG_L1_PULL_REQ, &st->l1.Flags);
break;
case (PH_ACTIVATE | REQUEST):
spin_lock_irqsave(&bcs->cs->lock, flags);
test_and_set_bit(BC_FLG_ACTIV, &bcs->Flag);
mode_tiger(bcs, st->l1.mode, st->l1.bc);
/* 2001/10/04 Christoph Ersfeld, Formula-n Europe AG */
spin_unlock_irqrestore(&bcs->cs->lock, flags);
bcs->cs->cardmsg(bcs->cs, MDL_BC_ASSIGN, (void *)(&st->l1.bc));
l1_msg_b(st, pr, arg);
break;
case (PH_DEACTIVATE | REQUEST):
/* 2001/10/04 Christoph Ersfeld, Formula-n Europe AG */
bcs->cs->cardmsg(bcs->cs, MDL_BC_RELEASE, (void *)(&st->l1.bc));
l1_msg_b(st, pr, arg);
break;
case (PH_DEACTIVATE | CONFIRM):
spin_lock_irqsave(&bcs->cs->lock, flags);
test_and_clear_bit(BC_FLG_ACTIV, &bcs->Flag);
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
mode_tiger(bcs, 0, st->l1.bc);
spin_unlock_irqrestore(&bcs->cs->lock, flags);
st->l1.l1l2(st, PH_DEACTIVATE | CONFIRM, NULL);
break;
}
}
static void
close_tigerstate(struct BCState *bcs)
{
mode_tiger(bcs, 0, bcs->channel);
if (test_and_clear_bit(BC_FLG_INIT, &bcs->Flag)) {
kfree(bcs->hw.tiger.rcvbuf);
bcs->hw.tiger.rcvbuf = NULL;
kfree(bcs->hw.tiger.sendbuf);
bcs->hw.tiger.sendbuf = NULL;
skb_queue_purge(&bcs->rqueue);
skb_queue_purge(&bcs->squeue);
if (bcs->tx_skb) {
dev_kfree_skb_any(bcs->tx_skb);
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
}
}
}
static int
open_tigerstate(struct IsdnCardState *cs, struct BCState *bcs)
{
if (!test_and_set_bit(BC_FLG_INIT, &bcs->Flag)) {
if (!(bcs->hw.tiger.rcvbuf = kmalloc(HSCX_BUFMAX, GFP_ATOMIC))) {
printk(KERN_WARNING
"HiSax: No memory for tiger.rcvbuf\n");
return (1);
}
if (!(bcs->hw.tiger.sendbuf = kmalloc(RAW_BUFMAX, GFP_ATOMIC))) {
printk(KERN_WARNING
"HiSax: No memory for tiger.sendbuf\n");
return (1);
}
skb_queue_head_init(&bcs->rqueue);
skb_queue_head_init(&bcs->squeue);
}
bcs->tx_skb = NULL;
bcs->hw.tiger.sendcnt = 0;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->event = 0;
bcs->tx_cnt = 0;
return (0);
}
static int
setstack_tiger(struct PStack *st, struct BCState *bcs)
{
bcs->channel = st->l1.bc;
if (open_tigerstate(st->l1.hardware, bcs))
return (-1);
st->l1.bcs = bcs;
st->l2.l2l1 = tiger_l2l1;
setstack_manager(st);
bcs->st = st;
setstack_l1_B(st);
return (0);
}
void
inittiger(struct IsdnCardState *cs)
{
if (!(cs->bcs[0].hw.tiger.send = kmalloc(NETJET_DMA_TXSIZE * sizeof(unsigned int),
GFP_KERNEL | GFP_DMA))) {
printk(KERN_WARNING
"HiSax: No memory for tiger.send\n");
return;
}
cs->bcs[0].hw.tiger.s_irq = cs->bcs[0].hw.tiger.send + NETJET_DMA_TXSIZE / 2 - 1;
cs->bcs[0].hw.tiger.s_end = cs->bcs[0].hw.tiger.send + NETJET_DMA_TXSIZE - 1;
cs->bcs[1].hw.tiger.send = cs->bcs[0].hw.tiger.send;
cs->bcs[1].hw.tiger.s_irq = cs->bcs[0].hw.tiger.s_irq;
cs->bcs[1].hw.tiger.s_end = cs->bcs[0].hw.tiger.s_end;
memset(cs->bcs[0].hw.tiger.send, 0xff, NETJET_DMA_TXSIZE * sizeof(unsigned int));
debugl1(cs, "tiger: send buf %p - %p", cs->bcs[0].hw.tiger.send,
cs->bcs[0].hw.tiger.send + NETJET_DMA_TXSIZE - 1);
outl(virt_to_bus(cs->bcs[0].hw.tiger.send),
cs->hw.njet.base + NETJET_DMA_READ_START);
outl(virt_to_bus(cs->bcs[0].hw.tiger.s_irq),
cs->hw.njet.base + NETJET_DMA_READ_IRQ);
outl(virt_to_bus(cs->bcs[0].hw.tiger.s_end),
cs->hw.njet.base + NETJET_DMA_READ_END);
if (!(cs->bcs[0].hw.tiger.rec = kmalloc(NETJET_DMA_RXSIZE * sizeof(unsigned int),
GFP_KERNEL | GFP_DMA))) {
printk(KERN_WARNING
"HiSax: No memory for tiger.rec\n");
return;
}
debugl1(cs, "tiger: rec buf %p - %p", cs->bcs[0].hw.tiger.rec,
cs->bcs[0].hw.tiger.rec + NETJET_DMA_RXSIZE - 1);
cs->bcs[1].hw.tiger.rec = cs->bcs[0].hw.tiger.rec;
memset(cs->bcs[0].hw.tiger.rec, 0xff, NETJET_DMA_RXSIZE * sizeof(unsigned int));
outl(virt_to_bus(cs->bcs[0].hw.tiger.rec),
cs->hw.njet.base + NETJET_DMA_WRITE_START);
outl(virt_to_bus(cs->bcs[0].hw.tiger.rec + NETJET_DMA_RXSIZE / 2 - 1),
cs->hw.njet.base + NETJET_DMA_WRITE_IRQ);
outl(virt_to_bus(cs->bcs[0].hw.tiger.rec + NETJET_DMA_RXSIZE - 1),
cs->hw.njet.base + NETJET_DMA_WRITE_END);
debugl1(cs, "tiger: dmacfg %x/%x pulse=%d",
inl(cs->hw.njet.base + NETJET_DMA_WRITE_ADR),
inl(cs->hw.njet.base + NETJET_DMA_READ_ADR),
bytein(cs->hw.njet.base + NETJET_PULSE_CNT));
cs->hw.njet.last_is0 = 0;
cs->bcs[0].BC_SetStack = setstack_tiger;
cs->bcs[1].BC_SetStack = setstack_tiger;
cs->bcs[0].BC_Close = close_tigerstate;
cs->bcs[1].BC_Close = close_tigerstate;
}
static void
releasetiger(struct IsdnCardState *cs)
{
kfree(cs->bcs[0].hw.tiger.send);
cs->bcs[0].hw.tiger.send = NULL;
cs->bcs[1].hw.tiger.send = NULL;
kfree(cs->bcs[0].hw.tiger.rec);
cs->bcs[0].hw.tiger.rec = NULL;
cs->bcs[1].hw.tiger.rec = NULL;
}
void
release_io_netjet(struct IsdnCardState *cs)
{
byteout(cs->hw.njet.base + NETJET_IRQMASK0, 0);
byteout(cs->hw.njet.base + NETJET_IRQMASK1, 0);
releasetiger(cs);
release_region(cs->hw.njet.base, 256);
}
| gpl-2.0 |
TeamEpsilon/linux-3.8-test_context | drivers/isdn/hisax/elsa_ser.c | 7302 | 17053 | /* $Id: elsa_ser.c,v 2.14.2.3 2004/02/11 13:21:33 keil Exp $
*
* stuff for the serial modem on ELSA cards
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
*/
#include <linux/serial.h>
#include <linux/serial_reg.h>
#include <linux/slab.h>
#define MAX_MODEM_BUF 256
#define WAKEUP_CHARS (MAX_MODEM_BUF / 2)
#define RS_ISR_PASS_LIMIT 256
#define BASE_BAUD (1843200 / 16)
//#define SERIAL_DEBUG_OPEN 1
//#define SERIAL_DEBUG_INTR 1
//#define SERIAL_DEBUG_FLOW 1
#undef SERIAL_DEBUG_OPEN
#undef SERIAL_DEBUG_INTR
#undef SERIAL_DEBUG_FLOW
#undef SERIAL_DEBUG_REG
//#define SERIAL_DEBUG_REG 1
#ifdef SERIAL_DEBUG_REG
static u_char deb[32];
const char *ModemIn[] = {"RBR", "IER", "IIR", "LCR", "MCR", "LSR", "MSR", "SCR"};
const char *ModemOut[] = {"THR", "IER", "FCR", "LCR", "MCR", "LSR", "MSR", "SCR"};
#endif
static char *MInit_1 = "AT&F&C1E0&D2\r\0";
static char *MInit_2 = "ATL2M1S64=13\r\0";
static char *MInit_3 = "AT+FCLASS=0\r\0";
static char *MInit_4 = "ATV1S2=128X1\r\0";
static char *MInit_5 = "AT\\V8\\N3\r\0";
static char *MInit_6 = "ATL0M0&G0%E1\r\0";
static char *MInit_7 = "AT%L1%M0%C3\r\0";
static char *MInit_speed28800 = "AT%G0%B28800\r\0";
static char *MInit_dialout = "ATs7=60 x1 d\r\0";
static char *MInit_dialin = "ATs7=60 x1 a\r\0";
static inline unsigned int serial_in(struct IsdnCardState *cs, int offset)
{
#ifdef SERIAL_DEBUG_REG
u_int val = inb(cs->hw.elsa.base + 8 + offset);
debugl1(cs, "in %s %02x", ModemIn[offset], val);
return (val);
#else
return inb(cs->hw.elsa.base + 8 + offset);
#endif
}
static inline unsigned int serial_inp(struct IsdnCardState *cs, int offset)
{
#ifdef SERIAL_DEBUG_REG
#ifdef ELSA_SERIAL_NOPAUSE_IO
u_int val = inb(cs->hw.elsa.base + 8 + offset);
debugl1(cs, "inp %s %02x", ModemIn[offset], val);
#else
u_int val = inb_p(cs->hw.elsa.base + 8 + offset);
debugl1(cs, "inP %s %02x", ModemIn[offset], val);
#endif
return (val);
#else
#ifdef ELSA_SERIAL_NOPAUSE_IO
return inb(cs->hw.elsa.base + 8 + offset);
#else
return inb_p(cs->hw.elsa.base + 8 + offset);
#endif
#endif
}
static inline void serial_out(struct IsdnCardState *cs, int offset, int value)
{
#ifdef SERIAL_DEBUG_REG
debugl1(cs, "out %s %02x", ModemOut[offset], value);
#endif
outb(value, cs->hw.elsa.base + 8 + offset);
}
static inline void serial_outp(struct IsdnCardState *cs, int offset,
int value)
{
#ifdef SERIAL_DEBUG_REG
#ifdef ELSA_SERIAL_NOPAUSE_IO
debugl1(cs, "outp %s %02x", ModemOut[offset], value);
#else
debugl1(cs, "outP %s %02x", ModemOut[offset], value);
#endif
#endif
#ifdef ELSA_SERIAL_NOPAUSE_IO
outb(value, cs->hw.elsa.base + 8 + offset);
#else
outb_p(value, cs->hw.elsa.base + 8 + offset);
#endif
}
/*
* This routine is called to set the UART divisor registers to match
* the specified baud rate for a serial port.
*/
static void change_speed(struct IsdnCardState *cs, int baud)
{
int quot = 0, baud_base;
unsigned cval, fcr = 0;
/* byte size and parity */
cval = 0x03;
/* Determine divisor based on baud rate */
baud_base = BASE_BAUD;
quot = baud_base / baud;
/* If the quotient is ever zero, default to 9600 bps */
if (!quot)
quot = baud_base / 9600;
/* Set up FIFO's */
if ((baud_base / quot) < 2400)
fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_1;
else
fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_8;
serial_outp(cs, UART_FCR, fcr);
/* CTS flow control flag and modem status interrupts */
cs->hw.elsa.IER &= ~UART_IER_MSI;
cs->hw.elsa.IER |= UART_IER_MSI;
serial_outp(cs, UART_IER, cs->hw.elsa.IER);
debugl1(cs, "modem quot=0x%x", quot);
serial_outp(cs, UART_LCR, cval | UART_LCR_DLAB);/* set DLAB */
serial_outp(cs, UART_DLL, quot & 0xff); /* LS of divisor */
serial_outp(cs, UART_DLM, quot >> 8); /* MS of divisor */
serial_outp(cs, UART_LCR, cval); /* reset DLAB */
serial_inp(cs, UART_RX);
}
static int mstartup(struct IsdnCardState *cs)
{
int retval = 0;
/*
* Clear the FIFO buffers and disable them
* (they will be reenabled in change_speed())
*/
serial_outp(cs, UART_FCR, (UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT));
/*
* At this point there's no way the LSR could still be 0xFF;
* if it is, then bail out, because there's likely no UART
* here.
*/
if (serial_inp(cs, UART_LSR) == 0xff) {
retval = -ENODEV;
goto errout;
}
/*
* Clear the interrupt registers.
*/
(void) serial_inp(cs, UART_RX);
(void) serial_inp(cs, UART_IIR);
(void) serial_inp(cs, UART_MSR);
/*
* Now, initialize the UART
*/
serial_outp(cs, UART_LCR, UART_LCR_WLEN8); /* reset DLAB */
cs->hw.elsa.MCR = 0;
cs->hw.elsa.MCR = UART_MCR_DTR | UART_MCR_RTS | UART_MCR_OUT2;
serial_outp(cs, UART_MCR, cs->hw.elsa.MCR);
/*
* Finally, enable interrupts
*/
cs->hw.elsa.IER = UART_IER_MSI | UART_IER_RLSI | UART_IER_RDI;
serial_outp(cs, UART_IER, cs->hw.elsa.IER); /* enable interrupts */
/*
* And clear the interrupt registers again for luck.
*/
(void)serial_inp(cs, UART_LSR);
(void)serial_inp(cs, UART_RX);
(void)serial_inp(cs, UART_IIR);
(void)serial_inp(cs, UART_MSR);
cs->hw.elsa.transcnt = cs->hw.elsa.transp = 0;
cs->hw.elsa.rcvcnt = cs->hw.elsa.rcvp = 0;
/*
* and set the speed of the serial port
*/
change_speed(cs, BASE_BAUD);
cs->hw.elsa.MFlag = 1;
errout:
return retval;
}
/*
* This routine will shutdown a serial port; interrupts are disabled, and
* DTR is dropped if the hangup on close termio flag is on.
*/
static void mshutdown(struct IsdnCardState *cs)
{
#ifdef SERIAL_DEBUG_OPEN
printk(KERN_DEBUG"Shutting down serial ....");
#endif
/*
* clear delta_msr_wait queue to avoid mem leaks: we may free the irq
* here so the queue might never be waken up
*/
cs->hw.elsa.IER = 0;
serial_outp(cs, UART_IER, 0x00); /* disable all intrs */
cs->hw.elsa.MCR &= ~UART_MCR_OUT2;
/* disable break condition */
serial_outp(cs, UART_LCR, serial_inp(cs, UART_LCR) & ~UART_LCR_SBC);
cs->hw.elsa.MCR &= ~(UART_MCR_DTR | UART_MCR_RTS);
serial_outp(cs, UART_MCR, cs->hw.elsa.MCR);
/* disable FIFO's */
serial_outp(cs, UART_FCR, (UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT));
serial_inp(cs, UART_RX); /* read data port to reset things */
#ifdef SERIAL_DEBUG_OPEN
printk(" done\n");
#endif
}
static inline int
write_modem(struct BCState *bcs) {
int ret = 0;
struct IsdnCardState *cs = bcs->cs;
int count, len, fp;
if (!bcs->tx_skb)
return 0;
if (bcs->tx_skb->len <= 0)
return 0;
len = bcs->tx_skb->len;
if (len > MAX_MODEM_BUF - cs->hw.elsa.transcnt)
len = MAX_MODEM_BUF - cs->hw.elsa.transcnt;
fp = cs->hw.elsa.transcnt + cs->hw.elsa.transp;
fp &= (MAX_MODEM_BUF - 1);
count = len;
if (count > MAX_MODEM_BUF - fp) {
count = MAX_MODEM_BUF - fp;
skb_copy_from_linear_data(bcs->tx_skb,
cs->hw.elsa.transbuf + fp, count);
skb_pull(bcs->tx_skb, count);
cs->hw.elsa.transcnt += count;
ret = count;
count = len - count;
fp = 0;
}
skb_copy_from_linear_data(bcs->tx_skb,
cs->hw.elsa.transbuf + fp, count);
skb_pull(bcs->tx_skb, count);
cs->hw.elsa.transcnt += count;
ret += count;
if (cs->hw.elsa.transcnt &&
!(cs->hw.elsa.IER & UART_IER_THRI)) {
cs->hw.elsa.IER |= UART_IER_THRI;
serial_outp(cs, UART_IER, cs->hw.elsa.IER);
}
return (ret);
}
static inline void
modem_fill(struct BCState *bcs) {
if (bcs->tx_skb) {
if (bcs->tx_skb->len) {
write_modem(bcs);
return;
} else {
if (test_bit(FLG_LLI_L1WAKEUP, &bcs->st->lli.flag) &&
(PACKET_NOACK != bcs->tx_skb->pkt_type)) {
u_long flags;
spin_lock_irqsave(&bcs->aclock, flags);
bcs->ackcnt += bcs->hw.hscx.count;
spin_unlock_irqrestore(&bcs->aclock, flags);
schedule_event(bcs, B_ACKPENDING);
}
dev_kfree_skb_any(bcs->tx_skb);
bcs->tx_skb = NULL;
}
}
if ((bcs->tx_skb = skb_dequeue(&bcs->squeue))) {
bcs->hw.hscx.count = 0;
test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
write_modem(bcs);
} else {
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
schedule_event(bcs, B_XMTBUFREADY);
}
}
static inline void receive_chars(struct IsdnCardState *cs,
int *status)
{
unsigned char ch;
struct sk_buff *skb;
do {
ch = serial_in(cs, UART_RX);
if (cs->hw.elsa.rcvcnt >= MAX_MODEM_BUF)
break;
cs->hw.elsa.rcvbuf[cs->hw.elsa.rcvcnt++] = ch;
#ifdef SERIAL_DEBUG_INTR
printk("DR%02x:%02x...", ch, *status);
#endif
if (*status & (UART_LSR_BI | UART_LSR_PE |
UART_LSR_FE | UART_LSR_OE)) {
#ifdef SERIAL_DEBUG_INTR
printk("handling exept....");
#endif
}
*status = serial_inp(cs, UART_LSR);
} while (*status & UART_LSR_DR);
if (cs->hw.elsa.MFlag == 2) {
if (!(skb = dev_alloc_skb(cs->hw.elsa.rcvcnt)))
printk(KERN_WARNING "ElsaSER: receive out of memory\n");
else {
memcpy(skb_put(skb, cs->hw.elsa.rcvcnt), cs->hw.elsa.rcvbuf,
cs->hw.elsa.rcvcnt);
skb_queue_tail(&cs->hw.elsa.bcs->rqueue, skb);
}
schedule_event(cs->hw.elsa.bcs, B_RCVBUFREADY);
} else {
char tmp[128];
char *t = tmp;
t += sprintf(t, "modem read cnt %d", cs->hw.elsa.rcvcnt);
QuickHex(t, cs->hw.elsa.rcvbuf, cs->hw.elsa.rcvcnt);
debugl1(cs, tmp);
}
cs->hw.elsa.rcvcnt = 0;
}
static inline void transmit_chars(struct IsdnCardState *cs, int *intr_done)
{
int count;
debugl1(cs, "transmit_chars: p(%x) cnt(%x)", cs->hw.elsa.transp,
cs->hw.elsa.transcnt);
if (cs->hw.elsa.transcnt <= 0) {
cs->hw.elsa.IER &= ~UART_IER_THRI;
serial_out(cs, UART_IER, cs->hw.elsa.IER);
return;
}
count = 16;
do {
serial_outp(cs, UART_TX, cs->hw.elsa.transbuf[cs->hw.elsa.transp++]);
if (cs->hw.elsa.transp >= MAX_MODEM_BUF)
cs->hw.elsa.transp = 0;
if (--cs->hw.elsa.transcnt <= 0)
break;
} while (--count > 0);
if ((cs->hw.elsa.transcnt < WAKEUP_CHARS) && (cs->hw.elsa.MFlag == 2))
modem_fill(cs->hw.elsa.bcs);
#ifdef SERIAL_DEBUG_INTR
printk("THRE...");
#endif
if (intr_done)
*intr_done = 0;
if (cs->hw.elsa.transcnt <= 0) {
cs->hw.elsa.IER &= ~UART_IER_THRI;
serial_outp(cs, UART_IER, cs->hw.elsa.IER);
}
}
static void rs_interrupt_elsa(struct IsdnCardState *cs)
{
int status, iir, msr;
int pass_counter = 0;
#ifdef SERIAL_DEBUG_INTR
printk(KERN_DEBUG "rs_interrupt_single(%d)...", cs->irq);
#endif
do {
status = serial_inp(cs, UART_LSR);
debugl1(cs, "rs LSR %02x", status);
#ifdef SERIAL_DEBUG_INTR
printk("status = %x...", status);
#endif
if (status & UART_LSR_DR)
receive_chars(cs, &status);
if (status & UART_LSR_THRE)
transmit_chars(cs, NULL);
if (pass_counter++ > RS_ISR_PASS_LIMIT) {
printk("rs_single loop break.\n");
break;
}
iir = serial_inp(cs, UART_IIR);
debugl1(cs, "rs IIR %02x", iir);
if ((iir & 0xf) == 0) {
msr = serial_inp(cs, UART_MSR);
debugl1(cs, "rs MSR %02x", msr);
}
} while (!(iir & UART_IIR_NO_INT));
#ifdef SERIAL_DEBUG_INTR
printk("end.\n");
#endif
}
extern int open_hscxstate(struct IsdnCardState *cs, struct BCState *bcs);
extern void modehscx(struct BCState *bcs, int mode, int bc);
extern void hscx_l2l1(struct PStack *st, int pr, void *arg);
static void
close_elsastate(struct BCState *bcs)
{
modehscx(bcs, 0, bcs->channel);
if (test_and_clear_bit(BC_FLG_INIT, &bcs->Flag)) {
if (bcs->hw.hscx.rcvbuf) {
if (bcs->mode != L1_MODE_MODEM)
kfree(bcs->hw.hscx.rcvbuf);
bcs->hw.hscx.rcvbuf = NULL;
}
skb_queue_purge(&bcs->rqueue);
skb_queue_purge(&bcs->squeue);
if (bcs->tx_skb) {
dev_kfree_skb_any(bcs->tx_skb);
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
}
}
}
static void
modem_write_cmd(struct IsdnCardState *cs, u_char *buf, int len) {
int count, fp;
u_char *msg = buf;
if (!len)
return;
if (len > (MAX_MODEM_BUF - cs->hw.elsa.transcnt)) {
return;
}
fp = cs->hw.elsa.transcnt + cs->hw.elsa.transp;
fp &= (MAX_MODEM_BUF - 1);
count = len;
if (count > MAX_MODEM_BUF - fp) {
count = MAX_MODEM_BUF - fp;
memcpy(cs->hw.elsa.transbuf + fp, msg, count);
cs->hw.elsa.transcnt += count;
msg += count;
count = len - count;
fp = 0;
}
memcpy(cs->hw.elsa.transbuf + fp, msg, count);
cs->hw.elsa.transcnt += count;
if (cs->hw.elsa.transcnt &&
!(cs->hw.elsa.IER & UART_IER_THRI)) {
cs->hw.elsa.IER |= UART_IER_THRI;
serial_outp(cs, UART_IER, cs->hw.elsa.IER);
}
}
static void
modem_set_init(struct IsdnCardState *cs) {
int timeout;
#define RCV_DELAY 20
modem_write_cmd(cs, MInit_1, strlen(MInit_1));
timeout = 1000;
while (timeout-- && cs->hw.elsa.transcnt)
udelay(1000);
debugl1(cs, "msi tout=%d", timeout);
mdelay(RCV_DELAY);
modem_write_cmd(cs, MInit_2, strlen(MInit_2));
timeout = 1000;
while (timeout-- && cs->hw.elsa.transcnt)
udelay(1000);
debugl1(cs, "msi tout=%d", timeout);
mdelay(RCV_DELAY);
modem_write_cmd(cs, MInit_3, strlen(MInit_3));
timeout = 1000;
while (timeout-- && cs->hw.elsa.transcnt)
udelay(1000);
debugl1(cs, "msi tout=%d", timeout);
mdelay(RCV_DELAY);
modem_write_cmd(cs, MInit_4, strlen(MInit_4));
timeout = 1000;
while (timeout-- && cs->hw.elsa.transcnt)
udelay(1000);
debugl1(cs, "msi tout=%d", timeout);
mdelay(RCV_DELAY);
modem_write_cmd(cs, MInit_5, strlen(MInit_5));
timeout = 1000;
while (timeout-- && cs->hw.elsa.transcnt)
udelay(1000);
debugl1(cs, "msi tout=%d", timeout);
mdelay(RCV_DELAY);
modem_write_cmd(cs, MInit_6, strlen(MInit_6));
timeout = 1000;
while (timeout-- && cs->hw.elsa.transcnt)
udelay(1000);
debugl1(cs, "msi tout=%d", timeout);
mdelay(RCV_DELAY);
modem_write_cmd(cs, MInit_7, strlen(MInit_7));
timeout = 1000;
while (timeout-- && cs->hw.elsa.transcnt)
udelay(1000);
debugl1(cs, "msi tout=%d", timeout);
mdelay(RCV_DELAY);
}
static void
modem_set_dial(struct IsdnCardState *cs, int outgoing) {
int timeout;
#define RCV_DELAY 20
modem_write_cmd(cs, MInit_speed28800, strlen(MInit_speed28800));
timeout = 1000;
while (timeout-- && cs->hw.elsa.transcnt)
udelay(1000);
debugl1(cs, "msi tout=%d", timeout);
mdelay(RCV_DELAY);
if (outgoing)
modem_write_cmd(cs, MInit_dialout, strlen(MInit_dialout));
else
modem_write_cmd(cs, MInit_dialin, strlen(MInit_dialin));
timeout = 1000;
while (timeout-- && cs->hw.elsa.transcnt)
udelay(1000);
debugl1(cs, "msi tout=%d", timeout);
mdelay(RCV_DELAY);
}
static void
modem_l2l1(struct PStack *st, int pr, void *arg)
{
struct BCState *bcs = st->l1.bcs;
struct sk_buff *skb = arg;
u_long flags;
if (pr == (PH_DATA | REQUEST)) {
spin_lock_irqsave(&bcs->cs->lock, flags);
if (bcs->tx_skb) {
skb_queue_tail(&bcs->squeue, skb);
} else {
bcs->tx_skb = skb;
test_and_set_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->hw.hscx.count = 0;
write_modem(bcs);
}
spin_unlock_irqrestore(&bcs->cs->lock, flags);
} else if (pr == (PH_ACTIVATE | REQUEST)) {
test_and_set_bit(BC_FLG_ACTIV, &bcs->Flag);
st->l1.l1l2(st, PH_ACTIVATE | CONFIRM, NULL);
set_arcofi(bcs->cs, st->l1.bc);
mstartup(bcs->cs);
modem_set_dial(bcs->cs, test_bit(FLG_ORIG, &st->l2.flag));
bcs->cs->hw.elsa.MFlag = 2;
} else if (pr == (PH_DEACTIVATE | REQUEST)) {
test_and_clear_bit(BC_FLG_ACTIV, &bcs->Flag);
bcs->cs->dc.isac.arcofi_bc = st->l1.bc;
arcofi_fsm(bcs->cs, ARCOFI_START, &ARCOFI_XOP_0);
interruptible_sleep_on(&bcs->cs->dc.isac.arcofi_wait);
bcs->cs->hw.elsa.MFlag = 1;
} else {
printk(KERN_WARNING "ElsaSer: unknown pr %x\n", pr);
}
}
static int
setstack_elsa(struct PStack *st, struct BCState *bcs)
{
bcs->channel = st->l1.bc;
switch (st->l1.mode) {
case L1_MODE_HDLC:
case L1_MODE_TRANS:
if (open_hscxstate(st->l1.hardware, bcs))
return (-1);
st->l2.l2l1 = hscx_l2l1;
break;
case L1_MODE_MODEM:
bcs->mode = L1_MODE_MODEM;
if (!test_and_set_bit(BC_FLG_INIT, &bcs->Flag)) {
bcs->hw.hscx.rcvbuf = bcs->cs->hw.elsa.rcvbuf;
skb_queue_head_init(&bcs->rqueue);
skb_queue_head_init(&bcs->squeue);
}
bcs->tx_skb = NULL;
test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag);
bcs->event = 0;
bcs->hw.hscx.rcvidx = 0;
bcs->tx_cnt = 0;
bcs->cs->hw.elsa.bcs = bcs;
st->l2.l2l1 = modem_l2l1;
break;
}
st->l1.bcs = bcs;
setstack_manager(st);
bcs->st = st;
setstack_l1_B(st);
return (0);
}
static void
init_modem(struct IsdnCardState *cs) {
cs->bcs[0].BC_SetStack = setstack_elsa;
cs->bcs[1].BC_SetStack = setstack_elsa;
cs->bcs[0].BC_Close = close_elsastate;
cs->bcs[1].BC_Close = close_elsastate;
if (!(cs->hw.elsa.rcvbuf = kmalloc(MAX_MODEM_BUF,
GFP_ATOMIC))) {
printk(KERN_WARNING
"Elsa: No modem mem hw.elsa.rcvbuf\n");
return;
}
if (!(cs->hw.elsa.transbuf = kmalloc(MAX_MODEM_BUF,
GFP_ATOMIC))) {
printk(KERN_WARNING
"Elsa: No modem mem hw.elsa.transbuf\n");
kfree(cs->hw.elsa.rcvbuf);
cs->hw.elsa.rcvbuf = NULL;
return;
}
if (mstartup(cs)) {
printk(KERN_WARNING "Elsa: problem startup modem\n");
}
modem_set_init(cs);
}
static void
release_modem(struct IsdnCardState *cs) {
cs->hw.elsa.MFlag = 0;
if (cs->hw.elsa.transbuf) {
if (cs->hw.elsa.rcvbuf) {
mshutdown(cs);
kfree(cs->hw.elsa.rcvbuf);
cs->hw.elsa.rcvbuf = NULL;
}
kfree(cs->hw.elsa.transbuf);
cs->hw.elsa.transbuf = NULL;
}
}
| gpl-2.0 |
deadman96385/android_kernel_nextbit_msm8992 | net/netlabel/netlabel_addrlist.c | 7558 | 10564 | /*
* NetLabel Network Address Lists
*
* This file contains network address list functions used to manage ordered
* lists of network addresses for use by the NetLabel subsystem. The NetLabel
* system manages static and dynamic label mappings for network protocols such
* as CIPSO and RIPSO.
*
* Author: Paul Moore <paul@paul-moore.com>
*
*/
/*
* (c) Copyright Hewlett-Packard Development Company, L.P., 2008
*
* 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/rcupdate.h>
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <linux/audit.h>
#include "netlabel_addrlist.h"
/*
* Address List Functions
*/
/**
* netlbl_af4list_search - Search for a matching IPv4 address entry
* @addr: IPv4 address
* @head: the list head
*
* Description:
* Searches the IPv4 address list given by @head. If a matching address entry
* is found it is returned, otherwise NULL is returned. The caller is
* responsible for calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af4list *netlbl_af4list_search(__be32 addr,
struct list_head *head)
{
struct netlbl_af4list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid && (addr & iter->mask) == iter->addr)
return iter;
return NULL;
}
/**
* netlbl_af4list_search_exact - Search for an exact IPv4 address entry
* @addr: IPv4 address
* @mask: IPv4 address mask
* @head: the list head
*
* Description:
* Searches the IPv4 address list given by @head. If an exact match if found
* it is returned, otherwise NULL is returned. The caller is responsible for
* calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af4list *netlbl_af4list_search_exact(__be32 addr,
__be32 mask,
struct list_head *head)
{
struct netlbl_af4list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid && iter->addr == addr && iter->mask == mask)
return iter;
return NULL;
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_search - Search for a matching IPv6 address entry
* @addr: IPv6 address
* @head: the list head
*
* Description:
* Searches the IPv6 address list given by @head. If a matching address entry
* is found it is returned, otherwise NULL is returned. The caller is
* responsible for calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af6list *netlbl_af6list_search(const struct in6_addr *addr,
struct list_head *head)
{
struct netlbl_af6list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ipv6_masked_addr_cmp(&iter->addr, &iter->mask, addr) == 0)
return iter;
return NULL;
}
/**
* netlbl_af6list_search_exact - Search for an exact IPv6 address entry
* @addr: IPv6 address
* @mask: IPv6 address mask
* @head: the list head
*
* Description:
* Searches the IPv6 address list given by @head. If an exact match if found
* it is returned, otherwise NULL is returned. The caller is responsible for
* calling the rcu_read_[un]lock() functions.
*
*/
struct netlbl_af6list *netlbl_af6list_search_exact(const struct in6_addr *addr,
const struct in6_addr *mask,
struct list_head *head)
{
struct netlbl_af6list *iter;
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ipv6_addr_equal(&iter->addr, addr) &&
ipv6_addr_equal(&iter->mask, mask))
return iter;
return NULL;
}
#endif /* IPv6 */
/**
* netlbl_af4list_add - Add a new IPv4 address entry to a list
* @entry: address entry
* @head: the list head
*
* Description:
* Add a new address entry to the list pointed to by @head. On success zero is
* returned, otherwise a negative value is returned. The caller is responsible
* for calling the necessary locking functions.
*
*/
int netlbl_af4list_add(struct netlbl_af4list *entry, struct list_head *head)
{
struct netlbl_af4list *iter;
iter = netlbl_af4list_search(entry->addr, head);
if (iter != NULL &&
iter->addr == entry->addr && iter->mask == entry->mask)
return -EEXIST;
/* in order to speed up address searches through the list (the common
* case) we need to keep the list in order based on the size of the
* address mask such that the entry with the widest mask (smallest
* numerical value) appears first in the list */
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ntohl(entry->mask) > ntohl(iter->mask)) {
__list_add_rcu(&entry->list,
iter->list.prev,
&iter->list);
return 0;
}
list_add_tail_rcu(&entry->list, head);
return 0;
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_add - Add a new IPv6 address entry to a list
* @entry: address entry
* @head: the list head
*
* Description:
* Add a new address entry to the list pointed to by @head. On success zero is
* returned, otherwise a negative value is returned. The caller is responsible
* for calling the necessary locking functions.
*
*/
int netlbl_af6list_add(struct netlbl_af6list *entry, struct list_head *head)
{
struct netlbl_af6list *iter;
iter = netlbl_af6list_search(&entry->addr, head);
if (iter != NULL &&
ipv6_addr_equal(&iter->addr, &entry->addr) &&
ipv6_addr_equal(&iter->mask, &entry->mask))
return -EEXIST;
/* in order to speed up address searches through the list (the common
* case) we need to keep the list in order based on the size of the
* address mask such that the entry with the widest mask (smallest
* numerical value) appears first in the list */
list_for_each_entry_rcu(iter, head, list)
if (iter->valid &&
ipv6_addr_cmp(&entry->mask, &iter->mask) > 0) {
__list_add_rcu(&entry->list,
iter->list.prev,
&iter->list);
return 0;
}
list_add_tail_rcu(&entry->list, head);
return 0;
}
#endif /* IPv6 */
/**
* netlbl_af4list_remove_entry - Remove an IPv4 address entry
* @entry: address entry
*
* Description:
* Remove the specified IP address entry. The caller is responsible for
* calling the necessary locking functions.
*
*/
void netlbl_af4list_remove_entry(struct netlbl_af4list *entry)
{
entry->valid = 0;
list_del_rcu(&entry->list);
}
/**
* netlbl_af4list_remove - Remove an IPv4 address entry
* @addr: IP address
* @mask: IP address mask
* @head: the list head
*
* Description:
* Remove an IP address entry from the list pointed to by @head. Returns the
* entry on success, NULL on failure. The caller is responsible for calling
* the necessary locking functions.
*
*/
struct netlbl_af4list *netlbl_af4list_remove(__be32 addr, __be32 mask,
struct list_head *head)
{
struct netlbl_af4list *entry;
entry = netlbl_af4list_search_exact(addr, mask, head);
if (entry == NULL)
return NULL;
netlbl_af4list_remove_entry(entry);
return entry;
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_remove_entry - Remove an IPv6 address entry
* @entry: address entry
*
* Description:
* Remove the specified IP address entry. The caller is responsible for
* calling the necessary locking functions.
*
*/
void netlbl_af6list_remove_entry(struct netlbl_af6list *entry)
{
entry->valid = 0;
list_del_rcu(&entry->list);
}
/**
* netlbl_af6list_remove - Remove an IPv6 address entry
* @addr: IP address
* @mask: IP address mask
* @head: the list head
*
* Description:
* Remove an IP address entry from the list pointed to by @head. Returns the
* entry on success, NULL on failure. The caller is responsible for calling
* the necessary locking functions.
*
*/
struct netlbl_af6list *netlbl_af6list_remove(const struct in6_addr *addr,
const struct in6_addr *mask,
struct list_head *head)
{
struct netlbl_af6list *entry;
entry = netlbl_af6list_search_exact(addr, mask, head);
if (entry == NULL)
return NULL;
netlbl_af6list_remove_entry(entry);
return entry;
}
#endif /* IPv6 */
/*
* Audit Helper Functions
*/
#ifdef CONFIG_AUDIT
/**
* netlbl_af4list_audit_addr - Audit an IPv4 address
* @audit_buf: audit buffer
* @src: true if source address, false if destination
* @dev: network interface
* @addr: IP address
* @mask: IP address mask
*
* Description:
* Write the IPv4 address and address mask, if necessary, to @audit_buf.
*
*/
void netlbl_af4list_audit_addr(struct audit_buffer *audit_buf,
int src, const char *dev,
__be32 addr, __be32 mask)
{
u32 mask_val = ntohl(mask);
char *dir = (src ? "src" : "dst");
if (dev != NULL)
audit_log_format(audit_buf, " netif=%s", dev);
audit_log_format(audit_buf, " %s=%pI4", dir, &addr);
if (mask_val != 0xffffffff) {
u32 mask_len = 0;
while (mask_val > 0) {
mask_val <<= 1;
mask_len++;
}
audit_log_format(audit_buf, " %s_prefixlen=%d", dir, mask_len);
}
}
#if IS_ENABLED(CONFIG_IPV6)
/**
* netlbl_af6list_audit_addr - Audit an IPv6 address
* @audit_buf: audit buffer
* @src: true if source address, false if destination
* @dev: network interface
* @addr: IP address
* @mask: IP address mask
*
* Description:
* Write the IPv6 address and address mask, if necessary, to @audit_buf.
*
*/
void netlbl_af6list_audit_addr(struct audit_buffer *audit_buf,
int src,
const char *dev,
const struct in6_addr *addr,
const struct in6_addr *mask)
{
char *dir = (src ? "src" : "dst");
if (dev != NULL)
audit_log_format(audit_buf, " netif=%s", dev);
audit_log_format(audit_buf, " %s=%pI6", dir, addr);
if (ntohl(mask->s6_addr32[3]) != 0xffffffff) {
u32 mask_len = 0;
u32 mask_val;
int iter = -1;
while (ntohl(mask->s6_addr32[++iter]) == 0xffffffff)
mask_len += 32;
mask_val = ntohl(mask->s6_addr32[iter]);
while (mask_val > 0) {
mask_val <<= 1;
mask_len++;
}
audit_log_format(audit_buf, " %s_prefixlen=%d", dir, mask_len);
}
}
#endif /* IPv6 */
#endif /* CONFIG_AUDIT */
| gpl-2.0 |
zipperX/android_kernel_oneplus_msm8974 | drivers/infiniband/hw/qib/qib_qsfp.c | 8582 | 14259 | /*
* Copyright (c) 2006, 2007, 2008, 2009 QLogic Corporation. All rights reserved.
* Copyright (c) 2003, 2004, 2005, 2006 PathScale, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include "qib.h"
#include "qib_qsfp.h"
/*
* QSFP support for ib_qib driver, using "Two Wire Serial Interface" driver
* in qib_twsi.c
*/
#define QSFP_MAX_RETRY 4
static int qsfp_read(struct qib_pportdata *ppd, int addr, void *bp, int len)
{
struct qib_devdata *dd = ppd->dd;
u32 out, mask;
int ret, cnt, pass = 0;
int stuck = 0;
u8 *buff = bp;
ret = mutex_lock_interruptible(&dd->eep_lock);
if (ret)
goto no_unlock;
if (dd->twsi_eeprom_dev == QIB_TWSI_NO_DEV) {
ret = -ENXIO;
goto bail;
}
/*
* We presume, if we are called at all, that this board has
* QSFP. This is on the same i2c chain as the legacy parts,
* but only responds if the module is selected via GPIO pins.
* Further, there are very long setup and hold requirements
* on MODSEL.
*/
mask = QSFP_GPIO_MOD_SEL_N | QSFP_GPIO_MOD_RST_N | QSFP_GPIO_LP_MODE;
out = QSFP_GPIO_MOD_RST_N | QSFP_GPIO_LP_MODE;
if (ppd->hw_pidx) {
mask <<= QSFP_GPIO_PORT2_SHIFT;
out <<= QSFP_GPIO_PORT2_SHIFT;
}
dd->f_gpio_mod(dd, out, mask, mask);
/*
* Module could take up to 2 Msec to respond to MOD_SEL, and there
* is no way to tell if it is ready, so we must wait.
*/
msleep(2);
/* Make sure TWSI bus is in sane state. */
ret = qib_twsi_reset(dd);
if (ret) {
qib_dev_porterr(dd, ppd->port,
"QSFP interface Reset for read failed\n");
ret = -EIO;
stuck = 1;
goto deselect;
}
/* All QSFP modules are at A0 */
cnt = 0;
while (cnt < len) {
unsigned in_page;
int wlen = len - cnt;
in_page = addr % QSFP_PAGESIZE;
if ((in_page + wlen) > QSFP_PAGESIZE)
wlen = QSFP_PAGESIZE - in_page;
ret = qib_twsi_blk_rd(dd, QSFP_DEV, addr, buff + cnt, wlen);
/* Some QSFP's fail first try. Retry as experiment */
if (ret && cnt == 0 && ++pass < QSFP_MAX_RETRY)
continue;
if (ret) {
/* qib_twsi_blk_rd() 1 for error, else 0 */
ret = -EIO;
goto deselect;
}
addr += wlen;
cnt += wlen;
}
ret = cnt;
deselect:
/*
* Module could take up to 10 uSec after transfer before
* ready to respond to MOD_SEL negation, and there is no way
* to tell if it is ready, so we must wait.
*/
udelay(10);
/* set QSFP MODSEL, RST. LP all high */
dd->f_gpio_mod(dd, mask, mask, mask);
/*
* Module could take up to 2 Msec to respond to MOD_SEL
* going away, and there is no way to tell if it is ready.
* so we must wait.
*/
if (stuck)
qib_dev_err(dd, "QSFP interface bus stuck non-idle\n");
if (pass >= QSFP_MAX_RETRY && ret)
qib_dev_porterr(dd, ppd->port, "QSFP failed even retrying\n");
else if (pass)
qib_dev_porterr(dd, ppd->port, "QSFP retries: %d\n", pass);
msleep(2);
bail:
mutex_unlock(&dd->eep_lock);
no_unlock:
return ret;
}
/*
* qsfp_write
* We do not ordinarily write the QSFP, but this is needed to select
* the page on non-flat QSFPs, and possibly later unusual cases
*/
static int qib_qsfp_write(struct qib_pportdata *ppd, int addr, void *bp,
int len)
{
struct qib_devdata *dd = ppd->dd;
u32 out, mask;
int ret, cnt;
u8 *buff = bp;
ret = mutex_lock_interruptible(&dd->eep_lock);
if (ret)
goto no_unlock;
if (dd->twsi_eeprom_dev == QIB_TWSI_NO_DEV) {
ret = -ENXIO;
goto bail;
}
/*
* We presume, if we are called at all, that this board has
* QSFP. This is on the same i2c chain as the legacy parts,
* but only responds if the module is selected via GPIO pins.
* Further, there are very long setup and hold requirements
* on MODSEL.
*/
mask = QSFP_GPIO_MOD_SEL_N | QSFP_GPIO_MOD_RST_N | QSFP_GPIO_LP_MODE;
out = QSFP_GPIO_MOD_RST_N | QSFP_GPIO_LP_MODE;
if (ppd->hw_pidx) {
mask <<= QSFP_GPIO_PORT2_SHIFT;
out <<= QSFP_GPIO_PORT2_SHIFT;
}
dd->f_gpio_mod(dd, out, mask, mask);
/*
* Module could take up to 2 Msec to respond to MOD_SEL,
* and there is no way to tell if it is ready, so we must wait.
*/
msleep(2);
/* Make sure TWSI bus is in sane state. */
ret = qib_twsi_reset(dd);
if (ret) {
qib_dev_porterr(dd, ppd->port,
"QSFP interface Reset for write failed\n");
ret = -EIO;
goto deselect;
}
/* All QSFP modules are at A0 */
cnt = 0;
while (cnt < len) {
unsigned in_page;
int wlen = len - cnt;
in_page = addr % QSFP_PAGESIZE;
if ((in_page + wlen) > QSFP_PAGESIZE)
wlen = QSFP_PAGESIZE - in_page;
ret = qib_twsi_blk_wr(dd, QSFP_DEV, addr, buff + cnt, wlen);
if (ret) {
/* qib_twsi_blk_wr() 1 for error, else 0 */
ret = -EIO;
goto deselect;
}
addr += wlen;
cnt += wlen;
}
ret = cnt;
deselect:
/*
* Module could take up to 10 uSec after transfer before
* ready to respond to MOD_SEL negation, and there is no way
* to tell if it is ready, so we must wait.
*/
udelay(10);
/* set QSFP MODSEL, RST, LP high */
dd->f_gpio_mod(dd, mask, mask, mask);
/*
* Module could take up to 2 Msec to respond to MOD_SEL
* going away, and there is no way to tell if it is ready.
* so we must wait.
*/
msleep(2);
bail:
mutex_unlock(&dd->eep_lock);
no_unlock:
return ret;
}
/*
* For validation, we want to check the checksums, even of the
* fields we do not otherwise use. This function reads the bytes from
* <first> to <next-1> and returns the 8lsbs of the sum, or <0 for errors
*/
static int qsfp_cks(struct qib_pportdata *ppd, int first, int next)
{
int ret;
u16 cks;
u8 bval;
cks = 0;
while (first < next) {
ret = qsfp_read(ppd, first, &bval, 1);
if (ret < 0)
goto bail;
cks += bval;
++first;
}
ret = cks & 0xFF;
bail:
return ret;
}
int qib_refresh_qsfp_cache(struct qib_pportdata *ppd, struct qib_qsfp_cache *cp)
{
int ret;
int idx;
u16 cks;
u8 peek[4];
/* ensure sane contents on invalid reads, for cable swaps */
memset(cp, 0, sizeof(*cp));
if (!qib_qsfp_mod_present(ppd)) {
ret = -ENODEV;
goto bail;
}
ret = qsfp_read(ppd, 0, peek, 3);
if (ret < 0)
goto bail;
if ((peek[0] & 0xFE) != 0x0C)
qib_dev_porterr(ppd->dd, ppd->port,
"QSFP byte0 is 0x%02X, S/B 0x0C/D\n", peek[0]);
if ((peek[2] & 2) == 0) {
/*
* If cable is paged, rather than "flat memory", we need to
* set the page to zero, Even if it already appears to be zero.
*/
u8 poke = 0;
ret = qib_qsfp_write(ppd, 127, &poke, 1);
udelay(50);
if (ret != 1) {
qib_dev_porterr(ppd->dd, ppd->port,
"Failed QSFP Page set\n");
goto bail;
}
}
ret = qsfp_read(ppd, QSFP_MOD_ID_OFFS, &cp->id, 1);
if (ret < 0)
goto bail;
if ((cp->id & 0xFE) != 0x0C)
qib_dev_porterr(ppd->dd, ppd->port,
"QSFP ID byte is 0x%02X, S/B 0x0C/D\n", cp->id);
cks = cp->id;
ret = qsfp_read(ppd, QSFP_MOD_PWR_OFFS, &cp->pwr, 1);
if (ret < 0)
goto bail;
cks += cp->pwr;
ret = qsfp_cks(ppd, QSFP_MOD_PWR_OFFS + 1, QSFP_MOD_LEN_OFFS);
if (ret < 0)
goto bail;
cks += ret;
ret = qsfp_read(ppd, QSFP_MOD_LEN_OFFS, &cp->len, 1);
if (ret < 0)
goto bail;
cks += cp->len;
ret = qsfp_read(ppd, QSFP_MOD_TECH_OFFS, &cp->tech, 1);
if (ret < 0)
goto bail;
cks += cp->tech;
ret = qsfp_read(ppd, QSFP_VEND_OFFS, &cp->vendor, QSFP_VEND_LEN);
if (ret < 0)
goto bail;
for (idx = 0; idx < QSFP_VEND_LEN; ++idx)
cks += cp->vendor[idx];
ret = qsfp_read(ppd, QSFP_IBXCV_OFFS, &cp->xt_xcv, 1);
if (ret < 0)
goto bail;
cks += cp->xt_xcv;
ret = qsfp_read(ppd, QSFP_VOUI_OFFS, &cp->oui, QSFP_VOUI_LEN);
if (ret < 0)
goto bail;
for (idx = 0; idx < QSFP_VOUI_LEN; ++idx)
cks += cp->oui[idx];
ret = qsfp_read(ppd, QSFP_PN_OFFS, &cp->partnum, QSFP_PN_LEN);
if (ret < 0)
goto bail;
for (idx = 0; idx < QSFP_PN_LEN; ++idx)
cks += cp->partnum[idx];
ret = qsfp_read(ppd, QSFP_REV_OFFS, &cp->rev, QSFP_REV_LEN);
if (ret < 0)
goto bail;
for (idx = 0; idx < QSFP_REV_LEN; ++idx)
cks += cp->rev[idx];
ret = qsfp_read(ppd, QSFP_ATTEN_OFFS, &cp->atten, QSFP_ATTEN_LEN);
if (ret < 0)
goto bail;
for (idx = 0; idx < QSFP_ATTEN_LEN; ++idx)
cks += cp->atten[idx];
ret = qsfp_cks(ppd, QSFP_ATTEN_OFFS + QSFP_ATTEN_LEN, QSFP_CC_OFFS);
if (ret < 0)
goto bail;
cks += ret;
cks &= 0xFF;
ret = qsfp_read(ppd, QSFP_CC_OFFS, &cp->cks1, 1);
if (ret < 0)
goto bail;
if (cks != cp->cks1)
qib_dev_porterr(ppd->dd, ppd->port,
"QSFP cks1 is %02X, computed %02X\n", cp->cks1,
cks);
/* Second checksum covers 192 to (serial, date, lot) */
ret = qsfp_cks(ppd, QSFP_CC_OFFS + 1, QSFP_SN_OFFS);
if (ret < 0)
goto bail;
cks = ret;
ret = qsfp_read(ppd, QSFP_SN_OFFS, &cp->serial, QSFP_SN_LEN);
if (ret < 0)
goto bail;
for (idx = 0; idx < QSFP_SN_LEN; ++idx)
cks += cp->serial[idx];
ret = qsfp_read(ppd, QSFP_DATE_OFFS, &cp->date, QSFP_DATE_LEN);
if (ret < 0)
goto bail;
for (idx = 0; idx < QSFP_DATE_LEN; ++idx)
cks += cp->date[idx];
ret = qsfp_read(ppd, QSFP_LOT_OFFS, &cp->lot, QSFP_LOT_LEN);
if (ret < 0)
goto bail;
for (idx = 0; idx < QSFP_LOT_LEN; ++idx)
cks += cp->lot[idx];
ret = qsfp_cks(ppd, QSFP_LOT_OFFS + QSFP_LOT_LEN, QSFP_CC_EXT_OFFS);
if (ret < 0)
goto bail;
cks += ret;
ret = qsfp_read(ppd, QSFP_CC_EXT_OFFS, &cp->cks2, 1);
if (ret < 0)
goto bail;
cks &= 0xFF;
if (cks != cp->cks2)
qib_dev_porterr(ppd->dd, ppd->port,
"QSFP cks2 is %02X, computed %02X\n", cp->cks2,
cks);
return 0;
bail:
cp->id = 0;
return ret;
}
const char * const qib_qsfp_devtech[16] = {
"850nm VCSEL", "1310nm VCSEL", "1550nm VCSEL", "1310nm FP",
"1310nm DFB", "1550nm DFB", "1310nm EML", "1550nm EML",
"Cu Misc", "1490nm DFB", "Cu NoEq", "Cu Eq",
"Undef", "Cu Active BothEq", "Cu FarEq", "Cu NearEq"
};
#define QSFP_DUMP_CHUNK 16 /* Holds longest string */
#define QSFP_DEFAULT_HDR_CNT 224
static const char *pwr_codes = "1.5W2.0W2.5W3.5W";
int qib_qsfp_mod_present(struct qib_pportdata *ppd)
{
u32 mask;
int ret;
mask = QSFP_GPIO_MOD_PRS_N <<
(ppd->hw_pidx * QSFP_GPIO_PORT2_SHIFT);
ret = ppd->dd->f_gpio_mod(ppd->dd, 0, 0, 0);
return !((ret & mask) >>
((ppd->hw_pidx * QSFP_GPIO_PORT2_SHIFT) + 3));
}
/*
* Initialize structures that control access to QSFP. Called once per port
* on cards that support QSFP.
*/
void qib_qsfp_init(struct qib_qsfp_data *qd,
void (*fevent)(struct work_struct *))
{
u32 mask, highs;
struct qib_devdata *dd = qd->ppd->dd;
/* Initialize work struct for later QSFP events */
INIT_WORK(&qd->work, fevent);
/*
* Later, we may want more validation. For now, just set up pins and
* blip reset. If module is present, call qib_refresh_qsfp_cache(),
* to do further init.
*/
mask = QSFP_GPIO_MOD_SEL_N | QSFP_GPIO_MOD_RST_N | QSFP_GPIO_LP_MODE;
highs = mask - QSFP_GPIO_MOD_RST_N;
if (qd->ppd->hw_pidx) {
mask <<= QSFP_GPIO_PORT2_SHIFT;
highs <<= QSFP_GPIO_PORT2_SHIFT;
}
dd->f_gpio_mod(dd, highs, mask, mask);
udelay(20); /* Generous RST dwell */
dd->f_gpio_mod(dd, mask, mask, mask);
return;
}
void qib_qsfp_deinit(struct qib_qsfp_data *qd)
{
/*
* There is nothing to do here for now. our work is scheduled
* with queue_work(), and flush_workqueue() from remove_one
* will block until all work setup with queue_work()
* completes.
*/
}
int qib_qsfp_dump(struct qib_pportdata *ppd, char *buf, int len)
{
struct qib_qsfp_cache cd;
u8 bin_buff[QSFP_DUMP_CHUNK];
char lenstr[6];
int sofar, ret;
int bidx = 0;
sofar = 0;
ret = qib_refresh_qsfp_cache(ppd, &cd);
if (ret < 0)
goto bail;
lenstr[0] = ' ';
lenstr[1] = '\0';
if (QSFP_IS_CU(cd.tech))
sprintf(lenstr, "%dM ", cd.len);
sofar += scnprintf(buf + sofar, len - sofar, "PWR:%.3sW\n", pwr_codes +
(QSFP_PWR(cd.pwr) * 4));
sofar += scnprintf(buf + sofar, len - sofar, "TECH:%s%s\n", lenstr,
qib_qsfp_devtech[cd.tech >> 4]);
sofar += scnprintf(buf + sofar, len - sofar, "Vendor:%.*s\n",
QSFP_VEND_LEN, cd.vendor);
sofar += scnprintf(buf + sofar, len - sofar, "OUI:%06X\n",
QSFP_OUI(cd.oui));
sofar += scnprintf(buf + sofar, len - sofar, "Part#:%.*s\n",
QSFP_PN_LEN, cd.partnum);
sofar += scnprintf(buf + sofar, len - sofar, "Rev:%.*s\n",
QSFP_REV_LEN, cd.rev);
if (QSFP_IS_CU(cd.tech))
sofar += scnprintf(buf + sofar, len - sofar, "Atten:%d, %d\n",
QSFP_ATTEN_SDR(cd.atten),
QSFP_ATTEN_DDR(cd.atten));
sofar += scnprintf(buf + sofar, len - sofar, "Serial:%.*s\n",
QSFP_SN_LEN, cd.serial);
sofar += scnprintf(buf + sofar, len - sofar, "Date:%.*s\n",
QSFP_DATE_LEN, cd.date);
sofar += scnprintf(buf + sofar, len - sofar, "Lot:%.*s\n",
QSFP_LOT_LEN, cd.date);
while (bidx < QSFP_DEFAULT_HDR_CNT) {
int iidx;
ret = qsfp_read(ppd, bidx, bin_buff, QSFP_DUMP_CHUNK);
if (ret < 0)
goto bail;
for (iidx = 0; iidx < ret; ++iidx) {
sofar += scnprintf(buf + sofar, len-sofar, " %02X",
bin_buff[iidx]);
}
sofar += scnprintf(buf + sofar, len - sofar, "\n");
bidx += QSFP_DUMP_CHUNK;
}
ret = sofar;
bail:
return ret;
}
| gpl-2.0 |
ziqifan16/selective-cache | arch/frv/mb93090-mb00/pci-irq.c | 8582 | 1729 | /* pci-irq.c: PCI IRQ routing on the FRV motherboard
*
* Copyright (C) 2003 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
* derived from: arch/i386/kernel/pci-irq.c: (c) 1999--2000 Martin Mares <mj@suse.cz>
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <asm/io.h>
#include <asm/smp.h>
#include "pci-frv.h"
/*
* DEVICE DEVNO INT#A INT#B INT#C INT#D
* ======= ======= ======= ======= ======= =======
* MB86943 0 fpga.10 - - -
* RTL8029 16 fpga.12 - - -
* SLOT 1 19 fpga.6 fpga.5 fpga.4 fpga.3
* SLOT 2 18 fpga.5 fpga.4 fpga.3 fpga.6
* SLOT 3 17 fpga.4 fpga.3 fpga.6 fpga.5
*
*/
static const uint8_t __initdata pci_bus0_irq_routing[32][4] = {
[0 ] = { IRQ_FPGA_MB86943_PCI_INTA },
[16] = { IRQ_FPGA_RTL8029_INTA },
[17] = { IRQ_FPGA_PCI_INTC, IRQ_FPGA_PCI_INTD, IRQ_FPGA_PCI_INTA, IRQ_FPGA_PCI_INTB },
[18] = { IRQ_FPGA_PCI_INTB, IRQ_FPGA_PCI_INTC, IRQ_FPGA_PCI_INTD, IRQ_FPGA_PCI_INTA },
[19] = { IRQ_FPGA_PCI_INTA, IRQ_FPGA_PCI_INTB, IRQ_FPGA_PCI_INTC, IRQ_FPGA_PCI_INTD },
};
void __init pcibios_irq_init(void)
{
}
void __init pcibios_fixup_irqs(void)
{
struct pci_dev *dev = NULL;
uint8_t line, pin;
for_each_pci_dev(dev) {
pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &pin);
if (pin) {
dev->irq = pci_bus0_irq_routing[PCI_SLOT(dev->devfn)][pin - 1];
pci_write_config_byte(dev, PCI_INTERRUPT_LINE, dev->irq);
}
pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &line);
}
}
void __init pcibios_penalize_isa_irq(int irq)
{
}
void pcibios_enable_irq(struct pci_dev *dev)
{
pci_write_config_byte(dev, PCI_INTERRUPT_LINE, dev->irq);
}
| gpl-2.0 |
martyj/LGP999_V10c_Kernel | arch/powerpc/platforms/pseries/hvcserver.c | 9606 | 7926 | /*
* hvcserver.c
* Copyright (C) 2004 Ryan S Arnold, IBM Corporation
*
* PPC64 virtual I/O console server support.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <asm/hvcall.h>
#include <asm/hvcserver.h>
#include <asm/io.h>
#define HVCS_ARCH_VERSION "1.0.0"
MODULE_AUTHOR("Ryan S. Arnold <rsa@us.ibm.com>");
MODULE_DESCRIPTION("IBM hvcs ppc64 API");
MODULE_LICENSE("GPL");
MODULE_VERSION(HVCS_ARCH_VERSION);
/*
* Convert arch specific return codes into relevant errnos. The hvcs
* functions aren't performance sensitive, so this conversion isn't an
* issue.
*/
static int hvcs_convert(long to_convert)
{
switch (to_convert) {
case H_SUCCESS:
return 0;
case H_PARAMETER:
return -EINVAL;
case H_HARDWARE:
return -EIO;
case H_BUSY:
case H_LONG_BUSY_ORDER_1_MSEC:
case H_LONG_BUSY_ORDER_10_MSEC:
case H_LONG_BUSY_ORDER_100_MSEC:
case H_LONG_BUSY_ORDER_1_SEC:
case H_LONG_BUSY_ORDER_10_SEC:
case H_LONG_BUSY_ORDER_100_SEC:
return -EBUSY;
case H_FUNCTION: /* fall through */
default:
return -EPERM;
}
}
/**
* hvcs_free_partner_info - free pi allocated by hvcs_get_partner_info
* @head: list_head pointer for an allocated list of partner info structs to
* free.
*
* This function is used to free the partner info list that was returned by
* calling hvcs_get_partner_info().
*/
int hvcs_free_partner_info(struct list_head *head)
{
struct hvcs_partner_info *pi;
struct list_head *element;
if (!head)
return -EINVAL;
while (!list_empty(head)) {
element = head->next;
pi = list_entry(element, struct hvcs_partner_info, node);
list_del(element);
kfree(pi);
}
return 0;
}
EXPORT_SYMBOL(hvcs_free_partner_info);
/* Helper function for hvcs_get_partner_info */
static int hvcs_next_partner(uint32_t unit_address,
unsigned long last_p_partition_ID,
unsigned long last_p_unit_address, unsigned long *pi_buff)
{
long retval;
retval = plpar_hcall_norets(H_VTERM_PARTNER_INFO, unit_address,
last_p_partition_ID,
last_p_unit_address, virt_to_phys(pi_buff));
return hvcs_convert(retval);
}
/**
* hvcs_get_partner_info - Get all of the partner info for a vty-server adapter
* @unit_address: The unit_address of the vty-server adapter for which this
* function is fetching partner info.
* @head: An initialized list_head pointer to an empty list to use to return the
* list of partner info fetched from the hypervisor to the caller.
* @pi_buff: A page sized buffer pre-allocated prior to calling this function
* that is to be used to be used by firmware as an iterator to keep track
* of the partner info retrieval.
*
* This function returns non-zero on success, or if there is no partner info.
*
* The pi_buff is pre-allocated prior to calling this function because this
* function may be called with a spin_lock held and kmalloc of a page is not
* recommended as GFP_ATOMIC.
*
* The first long of this buffer is used to store a partner unit address. The
* second long is used to store a partner partition ID and starting at
* pi_buff[2] is the 79 character Converged Location Code (diff size than the
* unsigned longs, hence the casting mumbo jumbo you see later).
*
* Invocation of this function should always be followed by an invocation of
* hvcs_free_partner_info() using a pointer to the SAME list head instance
* that was passed as a parameter to this function.
*/
int hvcs_get_partner_info(uint32_t unit_address, struct list_head *head,
unsigned long *pi_buff)
{
/*
* Dealt with as longs because of the hcall interface even though the
* values are uint32_t.
*/
unsigned long last_p_partition_ID;
unsigned long last_p_unit_address;
struct hvcs_partner_info *next_partner_info = NULL;
int more = 1;
int retval;
memset(pi_buff, 0x00, PAGE_SIZE);
/* invalid parameters */
if (!head || !pi_buff)
return -EINVAL;
last_p_partition_ID = last_p_unit_address = ~0UL;
INIT_LIST_HEAD(head);
do {
retval = hvcs_next_partner(unit_address, last_p_partition_ID,
last_p_unit_address, pi_buff);
if (retval) {
/*
* Don't indicate that we've failed if we have
* any list elements.
*/
if (!list_empty(head))
return 0;
return retval;
}
last_p_partition_ID = pi_buff[0];
last_p_unit_address = pi_buff[1];
/* This indicates that there are no further partners */
if (last_p_partition_ID == ~0UL
&& last_p_unit_address == ~0UL)
break;
/* This is a very small struct and will be freed soon in
* hvcs_free_partner_info(). */
next_partner_info = kmalloc(sizeof(struct hvcs_partner_info),
GFP_ATOMIC);
if (!next_partner_info) {
printk(KERN_WARNING "HVCONSOLE: kmalloc() failed to"
" allocate partner info struct.\n");
hvcs_free_partner_info(head);
return -ENOMEM;
}
next_partner_info->unit_address
= (unsigned int)last_p_unit_address;
next_partner_info->partition_ID
= (unsigned int)last_p_partition_ID;
/* copy the Null-term char too */
strncpy(&next_partner_info->location_code[0],
(char *)&pi_buff[2],
strlen((char *)&pi_buff[2]) + 1);
list_add_tail(&(next_partner_info->node), head);
next_partner_info = NULL;
} while (more);
return 0;
}
EXPORT_SYMBOL(hvcs_get_partner_info);
/**
* hvcs_register_connection - establish a connection between this vty-server and
* a vty.
* @unit_address: The unit address of the vty-server adapter that is to be
* establish a connection.
* @p_partition_ID: The partition ID of the vty adapter that is to be connected.
* @p_unit_address: The unit address of the vty adapter to which the vty-server
* is to be connected.
*
* If this function is called once and -EINVAL is returned it may
* indicate that the partner info needs to be refreshed for the
* target unit address at which point the caller must invoke
* hvcs_get_partner_info() and then call this function again. If,
* for a second time, -EINVAL is returned then it indicates that
* there is probably already a partner connection registered to a
* different vty-server adapter. It is also possible that a second
* -EINVAL may indicate that one of the parms is not valid, for
* instance if the link was removed between the vty-server adapter
* and the vty adapter that you are trying to open. Don't shoot the
* messenger. Firmware implemented it this way.
*/
int hvcs_register_connection( uint32_t unit_address,
uint32_t p_partition_ID, uint32_t p_unit_address)
{
long retval;
retval = plpar_hcall_norets(H_REGISTER_VTERM, unit_address,
p_partition_ID, p_unit_address);
return hvcs_convert(retval);
}
EXPORT_SYMBOL(hvcs_register_connection);
/**
* hvcs_free_connection - free the connection between a vty-server and vty
* @unit_address: The unit address of the vty-server that is to have its
* connection severed.
*
* This function is used to free the partner connection between a vty-server
* adapter and a vty adapter.
*
* If -EBUSY is returned continue to call this function until 0 is returned.
*/
int hvcs_free_connection(uint32_t unit_address)
{
long retval;
retval = plpar_hcall_norets(H_FREE_VTERM, unit_address);
return hvcs_convert(retval);
}
EXPORT_SYMBOL(hvcs_free_connection);
| gpl-2.0 |
profglavcho/sdwq | drivers/misc/mediatek/masp/asf/core/sec_mtd_util.c | 135 | 4241 | #include "sec_error.h"
#include "sec_boot.h"
#include "sec_mtd.h"
#include "sec_typedef.h"
#include "sec_osal_light.h"
/**************************************************************************
* MODULE NAME
**************************************************************************/
#define MOD "MTD_UTIL"
/**************************************************************************
* PART NAME QUERY
**************************************************************************/
char* mtd2pl (char* part_name)
{
/* sync mtd partition name with PL's and DA's */
/* ----------------- */
/* seccfg */
/* ----------------- */
if(0 == mcmp(part_name,MTD_SECCFG,strlen(MTD_SECCFG)))
{
return (char*) PL_SECCFG;
}
/* ----------------- */
/* uboot */
/* ----------------- */
else if(0 == mcmp(part_name,MTD_UBOOT,strlen(MTD_UBOOT)))
{
return (char*) PL_UBOOT;
}
/* ----------------- */
/* logo */
/* ----------------- */
else if(0 == mcmp(part_name,MTD_LOGO,strlen(MTD_LOGO)))
{
return (char*) PL_LOGO;
}
/* ----------------- */
/* boot image */
/* ----------------- */
else if(0 == mcmp(part_name,MTD_BOOTIMG,strlen(MTD_BOOTIMG)))
{
return (char*) PL_BOOTIMG;
}
/* ----------------- */
/* user data */
/* ----------------- */
else if(0 == mcmp(part_name,MTD_USER,strlen(MTD_USER)))
{
return (char*) PL_USER;
}
/* ----------------- */
/* system image */
/* ----------------- */
else if(0 == mcmp(part_name,MTD_ANDSYSIMG,strlen(MTD_ANDSYSIMG)))
{
return (char*) PL_ANDSYSIMG;
}
/* ----------------- */
/* recovery */
/* ----------------- */
else if(0 == mcmp(part_name,MTD_RECOVERY,strlen(MTD_RECOVERY)))
{
return (char*) PL_RECOVERY;
}
/* ----------------- */
/* sec ro */
/* ----------------- */
else if(0 == mcmp(part_name,MTD_SECRO,strlen(MTD_SECRO)))
{
return (char*) PL_SECRO;
}
/* ----------------- */
/* not found */
/* ----------------- */
else
{
return part_name;
}
}
char* pl2mtd (char* part_name)
{
/* sync mtd partition name with PL's and DA's */
/* ----------------- */
/* seccfg */
/* ----------------- */
if(0 == mcmp(part_name,PL_SECCFG,strlen(PL_SECCFG)))
{
return (char*) MTD_SECCFG;
}
/* ----------------- */
/* uboot */
/* ----------------- */
else if(0 == mcmp(part_name,PL_UBOOT,strlen(PL_UBOOT)))
{
return (char*) MTD_UBOOT;
}
/* ----------------- */
/* logo */
/* ----------------- */
else if(0 == mcmp(part_name,PL_LOGO,strlen(PL_LOGO)))
{
return (char*) MTD_LOGO;
}
/* ----------------- */
/* boot image */
/* ----------------- */
else if(0 == mcmp(part_name,PL_BOOTIMG,strlen(PL_BOOTIMG)))
{
return (char*) MTD_BOOTIMG;
}
/* ----------------- */
/* user data */
/* ----------------- */
else if(0 == mcmp(part_name,PL_USER,strlen(PL_USER)))
{
return (char*) MTD_USER;
}
/* ----------------- */
/* system image */
/* ----------------- */
else if(0 == mcmp(part_name,PL_ANDSYSIMG,strlen(PL_ANDSYSIMG)))
{
return (char*) MTD_ANDSYSIMG;
}
/* ----------------- */
/* recovery */
/* ----------------- */
else if(0 == mcmp(part_name,PL_RECOVERY,strlen(PL_RECOVERY)))
{
return (char*) MTD_RECOVERY;
}
/* ----------------- */
/* sec ro */
/* ----------------- */
else if(0 == mcmp(part_name,PL_SECRO,strlen(PL_SECRO)))
{
return (char*) MTD_SECRO;
}
/* ----------------- */
/* not found */
/* ----------------- */
else
{
return part_name;
}
}
| gpl-2.0 |
Tesla-Redux-Devices/android_kernel_samsung_msm8930-common | drivers/staging/prima/CORE/MAC/src/pe/lim/limProcessMlmRspMessages.c | 135 | 187844 | /*
* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, Inc.
*
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Airgo Networks, Inc proprietary. All rights reserved.
* This file limProcessMlmRspMessages.cc contains the code
* for processing response messages from MLM state machine.
* Author: Chandra Modumudi
* Date: 02/11/02
* History:-
* Date Modified by Modification Information
* --------------------------------------------------------------------
*
*/
#include "wniApi.h"
#include "wniCfgSta.h"
#include "cfgApi.h"
#include "sirApi.h"
#include "schApi.h"
#include "utilsApi.h"
#include "limUtils.h"
#include "limAssocUtils.h"
#include "limSecurityUtils.h"
#include "limSerDesUtils.h"
#include "limTimerUtils.h"
#include "limSendMessages.h"
#include "limAdmitControl.h"
#include "limSendMessages.h"
#include "limIbssPeerMgmt.h"
#include "limSession.h"
#include "limSessionUtils.h"
#if defined WLAN_FEATURE_VOWIFI
#include "rrmApi.h"
#endif
#if defined WLAN_FEATURE_VOWIFI_11R
#include <limFT.h>
#endif
#include "wlan_qct_wda.h"
#ifdef DEBUG_ROAM_DELAY
#include "vos_utils.h"
#endif
static void limHandleSmeJoinResult(tpAniSirGlobal, tSirResultCodes, tANI_U16,tpPESession);
static void limHandleSmeReaasocResult(tpAniSirGlobal, tSirResultCodes, tANI_U16, tpPESession);
void limProcessMlmScanCnf(tpAniSirGlobal, tANI_U32 *);
#ifdef FEATURE_OEM_DATA_SUPPORT
void limProcessMlmOemDataReqCnf(tpAniSirGlobal, tANI_U32 *);
#endif
void limProcessMlmJoinCnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmAuthCnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmStartCnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmAuthInd(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmAssocInd(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmAssocCnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmReassocCnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmReassocInd(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmSetKeysCnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmDisassocInd(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmDisassocCnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmDeauthInd(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmDeauthCnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmPurgeStaInd(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmAddBACnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmDelBACnf(tpAniSirGlobal, tANI_U32 *);
void limProcessMlmRemoveKeyCnf(tpAniSirGlobal pMac, tANI_U32 * pMsgBuf);
static void limHandleDelBssInReAssocContext(tpAniSirGlobal pMac, tpDphHashNode pStaDs,tpPESession psessionEntry);
void limGetSessionInfo(tpAniSirGlobal pMac, tANI_U8 *, tANI_U8 *, tANI_U16 *);
static void
limProcessBtampAddBssRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ ,tpPESession psessionEntry);
/**
* limProcessMlmRspMessages()
*
*FUNCTION:
* This function is called to processes various MLM response (CNF/IND
* messages from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param msgType Indicates the MLM message type
* @param *pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmRspMessages(tpAniSirGlobal pMac, tANI_U32 msgType, tANI_U32 *pMsgBuf)
{
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
MTRACE(macTrace(pMac, TRACE_CODE_TX_LIM_MSG, 0, msgType));
switch (msgType)
{
case LIM_MLM_SCAN_CNF:
limProcessMlmScanCnf(pMac, pMsgBuf);
break;
#ifdef FEATURE_OEM_DATA_SUPPORT
case LIM_MLM_OEM_DATA_CNF:
limProcessMlmOemDataReqCnf(pMac, pMsgBuf);
pMsgBuf = NULL;
break;
#endif
case LIM_MLM_AUTH_CNF:
limProcessMlmAuthCnf(pMac, pMsgBuf);
break;
case LIM_MLM_AUTH_IND:
limProcessMlmAuthInd(pMac, pMsgBuf);
break;
case LIM_MLM_ASSOC_CNF:
limProcessMlmAssocCnf(pMac, pMsgBuf);
break;
case LIM_MLM_START_CNF:
limProcessMlmStartCnf(pMac, pMsgBuf);
break;
case LIM_MLM_JOIN_CNF:
limProcessMlmJoinCnf(pMac, pMsgBuf);
break;
case LIM_MLM_ASSOC_IND:
limProcessMlmAssocInd(pMac, pMsgBuf);
break;
case LIM_MLM_REASSOC_CNF:
limProcessMlmReassocCnf(pMac, pMsgBuf);
break;
case LIM_MLM_REASSOC_IND:
limProcessMlmReassocInd(pMac, pMsgBuf);
break;
case LIM_MLM_DISASSOC_CNF:
limProcessMlmDisassocCnf(pMac, pMsgBuf);
break;
case LIM_MLM_DISASSOC_IND:
limProcessMlmDisassocInd(pMac, pMsgBuf);
break;
case LIM_MLM_PURGE_STA_IND:
limProcessMlmPurgeStaInd(pMac, pMsgBuf);
break;
case LIM_MLM_DEAUTH_CNF:
limProcessMlmDeauthCnf(pMac, pMsgBuf);
break;
case LIM_MLM_DEAUTH_IND:
limProcessMlmDeauthInd(pMac, pMsgBuf);
break;
case LIM_MLM_SETKEYS_CNF:
limProcessMlmSetKeysCnf(pMac, pMsgBuf);
break;
case LIM_MLM_REMOVEKEY_CNF:
limProcessMlmRemoveKeyCnf(pMac, pMsgBuf);
break;
case LIM_MLM_TSPEC_CNF:
break;
case LIM_MLM_ADDBA_CNF:
limProcessMlmAddBACnf( pMac, pMsgBuf );
pMsgBuf = NULL;
break;
case LIM_MLM_DELBA_CNF:
limProcessMlmDelBACnf( pMac, pMsgBuf );
pMsgBuf = NULL;
break;
default:
break;
} // switch (msgType)
return;
} /*** end limProcessMlmRspMessages() ***/
/**
* limProcessMlmScanCnf()
*
*FUNCTION:
* This function is called to processes MLM_SCAN_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmScanCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
switch(pMac->lim.gLimSmeState)
{
case eLIM_SME_WT_SCAN_STATE:
//case eLIM_SME_LINK_EST_WT_SCAN_STATE: //TO SUPPORT BT-AMP
//case eLIM_SME_NORMAL_CHANNEL_SCAN_STATE: //TO SUPPORT BT-AMP
pMac->lim.gLimSmeState = pMac->lim.gLimPrevSmeState;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, NO_SESSION, pMac->lim.gLimSmeState));
pMac->lim.gLimSystemInScanLearnMode = 0;
break;
default:
/**
* Should not have received scan confirm
* from MLM in other states.
* Log error
*/
PELOGE(limLog(pMac, LOGE,
FL("received unexpected MLM_SCAN_CNF in state %X"),
pMac->lim.gLimSmeState);)
return;
}
/// Process received scan confirm
/// Increment length of cached scan results
pMac->lim.gLimSmeScanResultLength +=
((tLimMlmScanCnf *) pMsgBuf)->scanResultLength;
if ((pMac->lim.gLimRspReqd) || pMac->lim.gLimReportBackgroundScanResults)
{
tANI_U16 scanRspLen = 0;
/// Need to send response to Host
pMac->lim.gLimRspReqd = false;
if ((((tLimMlmScanCnf *) pMsgBuf)->resultCode ==
eSIR_SME_SUCCESS) ||
pMac->lim.gLimSmeScanResultLength)
{
scanRspLen = sizeof(tSirSmeScanRsp) +
pMac->lim.gLimSmeScanResultLength -
sizeof(tSirBssDescription);
}
else
{
scanRspLen = sizeof(tSirSmeScanRsp);
}
if(pMac->lim.gLimReportBackgroundScanResults)
{
pMac->lim.gLimBackgroundScanTerminate = TRUE;
}
if (pMac->lim.gLimSmeScanResultLength == 0)
{
limSendSmeScanRsp(pMac, scanRspLen, eSIR_SME_SUCCESS, pMac->lim.gSmeSessionId, pMac->lim.gTransactionId);
}
else
{
limSendSmeScanRsp(pMac, scanRspLen,
eSIR_SME_SUCCESS,pMac->lim.gSmeSessionId, pMac->lim.gTransactionId);
}
} // if (pMac->lim.gLimRspReqd)
//check to see whether we need to run bgScan timer
if(pMac->lim.gLimBackgroundScanTerminate == FALSE)
{
if (tx_timer_activate(
&pMac->lim.limTimers.gLimBackgroundScanTimer) != TX_SUCCESS)
{
/// Could not activate background scan timer.
// Log error
limLog(pMac, LOGP,
FL("could not activate background scan timer"));
pMac->lim.gLimBackgroundScanStarted = FALSE;
}
else
{
pMac->lim.gLimBackgroundScanStarted = TRUE;
}
}
} /*** end limProcessMlmScanCnf() ***/
#ifdef FEATURE_OEM_DATA_SUPPORT
/**
* limProcessMlmOemDataReqCnf()
*
*FUNCTION:
* This function is called to processes LIM_MLM_OEM_DATA_REQ_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void limProcessMlmOemDataReqCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tLimMlmOemDataRsp* measRsp;
tSirResultCodes resultCode = eSIR_SME_SUCCESS;
measRsp = (tLimMlmOemDataRsp*)(pMsgBuf);
//Now send the meas confirm message to the sme
limSendSmeOemDataRsp(pMac, (tANI_U32*)measRsp, resultCode);
//Dont free the memory here. It will be freed up by the callee
return;
}
#endif
/**
* limProcessMlmStartCnf()
*
*FUNCTION:
* This function is called to processes MLM_START_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmStartCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tpPESession psessionEntry = NULL;
tLimMlmStartCnf *pLimMlmStartCnf;
tANI_U8 smesessionId;
tANI_U16 smetransactionId;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
pLimMlmStartCnf = (tLimMlmStartCnf*)pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac,pLimMlmStartCnf->sessionId))==NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Session does Not exist with given sessionId "));)
return;
}
smesessionId = psessionEntry->smeSessionId;
smetransactionId = psessionEntry->transactionId;
if (psessionEntry->limSmeState != eLIM_SME_WT_START_BSS_STATE)
{
/**
* Should not have received Start confirm from MLM
* in other states.
* Log error
*/
PELOGE(limLog(pMac, LOGE,
FL("received unexpected MLM_START_CNF in state %X"),
psessionEntry->limSmeState);)
return;
}
if (((tLimMlmStartCnf *) pMsgBuf)->resultCode ==
eSIR_SME_SUCCESS)
{
/**
* Update global SME state so that Beacon Generation
* module starts writing Beacon frames into TFP's
* Beacon file register.
*/
psessionEntry->limSmeState = eLIM_SME_NORMAL_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
if(psessionEntry->bssType == eSIR_BTAMP_STA_MODE)
{
limLog(pMac, LOG1, FL("*** Started BSS in BT_AMP STA SIDE***"));
}
else if(psessionEntry->bssType == eSIR_BTAMP_AP_MODE)
{
limLog(pMac, LOG1, FL("*** Started BSS in BT_AMP AP SIDE***"));
}
else if(psessionEntry->bssType == eSIR_INFRA_AP_MODE)
{
limLog(pMac, LOG1, FL("*** Started BSS in INFRA AP SIDE***"));
}
else
PELOG1(limLog(pMac, LOG1, FL("*** Started BSS ***"));)
}
else
{
/// Start BSS is a failure
peDeleteSession(pMac,psessionEntry);
psessionEntry = NULL;
}
/// Send response to Host
limSendSmeStartBssRsp(pMac, eWNI_SME_START_BSS_RSP,
((tLimMlmStartCnf *) pMsgBuf)->resultCode,psessionEntry,
smesessionId,smetransactionId);
if (((tLimMlmStartCnf *) pMsgBuf)->resultCode == eSIR_SME_SUCCESS)
{
//Configure beacon and send beacons to HAL
limSendBeaconInd(pMac, psessionEntry);
}
}
/*** end limProcessMlmStartCnf() ***/
/**
* limProcessMlmJoinCnf()
*
*FUNCTION:
* This function is called to processes MLM_JOIN_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmJoinCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tSirResultCodes resultCode;
tLimMlmJoinCnf *pLimMlmJoinCnf;
tpPESession psessionEntry;
pLimMlmJoinCnf = (tLimMlmJoinCnf*)pMsgBuf;
if( (psessionEntry = peFindSessionBySessionId(pMac,pLimMlmJoinCnf->sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Session does not exist for given sessionId"));)
return;
}
if (psessionEntry->limSmeState!= eLIM_SME_WT_JOIN_STATE)
{
PELOGE(limLog(pMac, LOGE,
FL("received unexpected MLM_JOIN_CNF in state %X"),
psessionEntry->limSmeState);)
return;
}
resultCode = ((tLimMlmJoinCnf *) pMsgBuf)->resultCode ;
/// Process Join confirm from MLM
if (resultCode == eSIR_SME_SUCCESS)
{
PELOG1(limLog(pMac, LOG1, FL("*** Joined ESS ***"));)
//Setup hardware upfront
//Done: 7-27-2009. JIM_FIX_ME sessionize the following function
if(limStaSendAddBssPreAssoc( pMac, false, psessionEntry) == eSIR_SUCCESS)
return;
else
resultCode = eSIR_SME_REFUSED;
}
{
/// Join failure
psessionEntry->limSmeState = eLIM_SME_JOIN_FAILURE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
/// Send Join response to Host
limHandleSmeJoinResult(pMac, resultCode, ((tLimMlmJoinCnf *) pMsgBuf)->protStatusCode, psessionEntry );
}
} /*** end limProcessMlmJoinCnf() ***/
/**
* limProcessMlmAuthCnf()
*
*FUNCTION:
* This function is called to processes MLM_AUTH_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmAuthCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tANI_U16 caps;
tANI_U32 val;
tAniAuthType cfgAuthType, authMode;
tLimMlmAuthReq *pMlmAuthReq;
tLimMlmAssocReq *pMlmAssocReq;
tLimMlmAuthCnf *pMlmAuthCnf;
tpPESession psessionEntry;
tANI_U32 teleBcnEn = 0;
// tANI_U8 sessionId;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
pMlmAuthCnf = (tLimMlmAuthCnf*)pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac,pMlmAuthCnf->sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE, FL("session does not exist for given sessionId"));)
return;
}
if (((psessionEntry->limSmeState != eLIM_SME_WT_AUTH_STATE) &&
(psessionEntry->limSmeState != eLIM_SME_WT_PRE_AUTH_STATE)) ||
(psessionEntry->limSystemRole == eLIM_AP_ROLE)|| (psessionEntry->limSystemRole == eLIM_BT_AMP_AP_ROLE))
{
/**
* Should not have received AUTH confirm
* from MLM in other states or on AP.
* Log error
*/
PELOGE(limLog(pMac, LOGE,
FL("received unexpected MLM_AUTH_CNF in state %X"),
psessionEntry->limSmeState);)
return;
}
/// Process AUTH confirm from MLM
if (((tLimMlmAuthCnf *) pMsgBuf)->resultCode != eSIR_SME_SUCCESS)
{
if (psessionEntry->limSmeState == eLIM_SME_WT_AUTH_STATE)
{
if (wlan_cfgGetInt(pMac, WNI_CFG_AUTHENTICATION_TYPE,
(tANI_U32 *) &cfgAuthType) != eSIR_SUCCESS)
{
/**
* Could not get AuthType value from CFG.
* Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve AuthType value"));
}
}
else
cfgAuthType = pMac->lim.gLimPreAuthType;
if ((cfgAuthType == eSIR_AUTO_SWITCH) &&
(((tLimMlmAuthCnf *) pMsgBuf)->authType == eSIR_OPEN_SYSTEM)
&& (eSIR_MAC_AUTH_ALGO_NOT_SUPPORTED_STATUS == ((tLimMlmAuthCnf *) pMsgBuf)->protStatusCode))
{
/**
* When Open authentication fails with reason code "13" and
* authType set to 'auto switch', Try with Shared Authentication
*/
authMode = eSIR_SHARED_KEY;
// Trigger MAC based Authentication
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd, (void **)&pMlmAuthReq, sizeof(tLimMlmAuthReq)))
{
// Log error
limLog(pMac, LOGP,
FL("call to palAllocateMemory failed for mlmAuthReq"));
return;
}
palZeroMemory( pMac->hHdd, (tANI_U8 *) pMlmAuthReq, sizeof(tLimMlmAuthReq));
val = sizeof(tSirMacAddr);
if (psessionEntry->limSmeState == eLIM_SME_WT_AUTH_STATE)
{
sirCopyMacAddr(pMlmAuthReq->peerMacAddr,psessionEntry->bssId);
}
else
palCopyMemory( pMac->hHdd, (tANI_U8 *) &pMlmAuthReq->peerMacAddr,
(tANI_U8 *) &pMac->lim.gLimPreAuthPeerAddr,
sizeof(tSirMacAddr));
pMlmAuthReq->authType = authMode;
/* Update PE session Id*/
pMlmAuthReq->sessionId = pMlmAuthCnf->sessionId;
if (wlan_cfgGetInt(pMac, WNI_CFG_AUTHENTICATE_FAILURE_TIMEOUT,
(tANI_U32 *) &pMlmAuthReq->authFailureTimeout)
!= eSIR_SUCCESS)
{
/**
* Could not get AuthFailureTimeout value from CFG.
* Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve AuthFailureTimeout value"));
}
limPostMlmMessage(pMac,
LIM_MLM_AUTH_REQ,
(tANI_U32 *) pMlmAuthReq);
return;
}
else
{
// MAC based authentication failure
if (psessionEntry->limSmeState == eLIM_SME_WT_AUTH_STATE)
{
PELOGE(limLog(pMac, LOGE, FL("Auth Failure occurred."));)
psessionEntry->limSmeState = eLIM_SME_JOIN_FAILURE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
/**
* Need to send Join response with
* auth failure to Host.
*/
limHandleSmeJoinResult(pMac,
((tLimMlmAuthCnf *) pMsgBuf)->resultCode, ((tLimMlmAuthCnf *) pMsgBuf)->protStatusCode,psessionEntry);
}
else
{
/**
* Pre-authentication failure.
* Send Pre-auth failure response to host
*/
psessionEntry->limSmeState = psessionEntry->limPrevSmeState;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
limSendSmeAuthRsp(
pMac,
((tLimMlmAuthCnf *) pMsgBuf)->resultCode,
((tLimMlmAuthCnf *) pMsgBuf)->peerMacAddr,
((tLimMlmAuthCnf *) pMsgBuf)->authType,
((tLimMlmAuthCnf *) pMsgBuf)->protStatusCode,psessionEntry,psessionEntry->smeSessionId,psessionEntry->transactionId);
}
} // end if (cfgAuthType == eAUTO_SWITCH)
} // if (((tLimMlmAuthCnf *) pMsgBuf)->resultCode != ...
else
{
if (psessionEntry->limSmeState == eLIM_SME_WT_AUTH_STATE)
{
/**
* Successful MAC based authentication
* Trigger Association with BSS
*/
PELOG1(limLog(pMac, LOG1,
FL("*** Authenticated with BSS ***"));)
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd, (void **)&pMlmAssocReq, sizeof(tLimMlmAssocReq)))
{
// Log error
limLog(pMac, LOGP,
FL("call to palAllocateMemory failed for mlmAssocReq"));
return;
}
val = sizeof(tSirMacAddr);
#if 0
if (cfgGetStr(pMac, WNI_CFG_BSSID,
pMlmAssocReq->peerMacAddr,
&val) != eSIR_SUCCESS)
{
/// Could not get BSSID from CFG. Log error.
limLog(pMac, LOGP, FL("could not retrieve BSSID"));
}
#endif //SUPPORT BT-AMP
sirCopyMacAddr(pMlmAssocReq->peerMacAddr,psessionEntry->bssId);
if (wlan_cfgGetInt(pMac, WNI_CFG_ASSOCIATION_FAILURE_TIMEOUT,
(tANI_U32 *) &pMlmAssocReq->assocFailureTimeout)
!= eSIR_SUCCESS)
{
/**
* Could not get AssocFailureTimeout value
* from CFG. Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve AssocFailureTimeout value"));
}
if (cfgGetCapabilityInfo(pMac, &caps,psessionEntry) != eSIR_SUCCESS)
{
/**
* Could not get Capabilities value
* from CFG. Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve Capabilities value"));
}
/*Clear spectrum management bit if AP doesn't support it*/
if(!(psessionEntry->pLimJoinReq->bssDescription.capabilityInfo & LIM_SPECTRUM_MANAGEMENT_BIT_MASK))
{
/*AP doesn't support spectrum management clear spectrum management bit*/
caps &= (~LIM_SPECTRUM_MANAGEMENT_BIT_MASK);
}
pMlmAssocReq->capabilityInfo = caps;
PELOG3(limLog(pMac, LOG3,
FL("Capabilities to be used in AssocReq=0x%X, privacy bit=%x shortSlotTime %x"),
caps,
((tpSirMacCapabilityInfo) &pMlmAssocReq->capabilityInfo)->privacy,
((tpSirMacCapabilityInfo) &pMlmAssocReq->capabilityInfo)->shortSlotTime);)
/* If telescopic beaconing is enabled, set listen interval to
WNI_CFG_TELE_BCN_MAX_LI */
if(wlan_cfgGetInt(pMac, WNI_CFG_TELE_BCN_WAKEUP_EN, &teleBcnEn) !=
eSIR_SUCCESS)
limLog(pMac, LOGP, FL("Couldn't get WNI_CFG_TELE_BCN_WAKEUP_EN"));
val = WNI_CFG_LISTEN_INTERVAL_STADEF;
if(teleBcnEn)
{
if(wlan_cfgGetInt(pMac, WNI_CFG_TELE_BCN_MAX_LI, &val) !=
eSIR_SUCCESS)
{
/**
* Could not get ListenInterval value
* from CFG. Log error.
*/
limLog(pMac, LOGP, FL("could not retrieve ListenInterval"));
}
}
else
{
if (wlan_cfgGetInt(pMac, WNI_CFG_LISTEN_INTERVAL, &val) != eSIR_SUCCESS)
{
/**
* Could not get ListenInterval value
* from CFG. Log error.
*/
limLog(pMac, LOGP, FL("could not retrieve ListenInterval"));
}
}
pMlmAssocReq->listenInterval = (tANI_U16)val;
/* Update PE session ID*/
pMlmAssocReq->sessionId = psessionEntry->peSessionId;
psessionEntry->limPrevSmeState = psessionEntry->limSmeState;
psessionEntry->limSmeState = eLIM_SME_WT_ASSOC_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
limPostMlmMessage(pMac,
LIM_MLM_ASSOC_REQ,
(tANI_U32 *) pMlmAssocReq);
}
else
{
/**
* Successful Pre-authentication.
* Send Pre-auth response to host
*/
psessionEntry->limSmeState = psessionEntry->limPrevSmeState;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
limSendSmeAuthRsp(
pMac,
((tLimMlmAuthCnf *) pMsgBuf)->resultCode,
((tLimMlmAuthCnf *) pMsgBuf)->peerMacAddr,
((tLimMlmAuthCnf *) pMsgBuf)->authType,
((tLimMlmAuthCnf *) pMsgBuf)->protStatusCode,psessionEntry,psessionEntry->smeSessionId,psessionEntry->transactionId);
}
} // end if (((tLimMlmAuthCnf *) pMsgBuf)->resultCode != ...
} /*** end limProcessMlmAuthCnf() ***/
/**
* limProcessMlmAssocCnf()
*
*FUNCTION:
* This function is called to processes MLM_ASSOC_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmAssocCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tpPESession psessionEntry;
tLimMlmAssocCnf *pLimMlmAssocCnf;
if(pMsgBuf == NULL)
{
limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));
return;
}
pLimMlmAssocCnf = (tLimMlmAssocCnf*)pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac,pLimMlmAssocCnf->sessionId)) == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Session does not exist for given sessionId"));)
return;
}
if (psessionEntry->limSmeState != eLIM_SME_WT_ASSOC_STATE ||
psessionEntry->limSystemRole == eLIM_AP_ROLE || psessionEntry ->limSystemRole == eLIM_BT_AMP_AP_ROLE)
{
/**
* Should not have received Assocication confirm
* from MLM in other states OR on AP.
* Log error
*/
PELOGE(limLog(pMac, LOGE,
FL("received unexpected MLM_ASSOC_CNF in state %X"),
psessionEntry->limSmeState);)
return;
}
if (((tLimMlmAssocCnf *) pMsgBuf)->resultCode != eSIR_SME_SUCCESS)
{
// Association failure
PELOG1(limLog(pMac, LOG1,
FL("SessionId:%d Association failure resultCode:%d"
"limSmeState:%d"), psessionEntry->peSessionId,
((tLimMlmAssocCnf *) pMsgBuf)->resultCode,
psessionEntry->limSmeState);)
/* If driver gets deauth when its waiting for ADD_STA_RSP then we need
* to do DEL_STA followed by DEL_BSS. So based on below reason-code here
* we decide whether to do only DEL_BSS or DEL_STA + DEL_BSS
*/
if(((tLimMlmAssocCnf *) pMsgBuf)->resultCode
!= eSIR_SME_JOIN_DEAUTH_FROM_AP_DURING_ADD_STA)
{
psessionEntry->limSmeState = eLIM_SME_JOIN_FAILURE_STATE;
}
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId,
pMac->lim.gLimSmeState));
/**
* Need to send Join response with
* Association failure to Host.
*/
limHandleSmeJoinResult(pMac,
((tLimMlmAssocCnf *) pMsgBuf)->resultCode,
((tLimMlmAssocCnf *) pMsgBuf)->protStatusCode,psessionEntry);
} // if (((tLimMlmAssocCnf *) pMsgBuf)->resultCode != ...
else
{
// Successful Association
PELOG1(limLog(pMac, LOG1, FL("*** Associated with BSS ***"));)
psessionEntry->limSmeState = eLIM_SME_LINK_EST_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
/**
* Need to send Join response with
* Association success to Host.
*/
limHandleSmeJoinResult(pMac,
((tLimMlmAssocCnf *) pMsgBuf)->resultCode,
((tLimMlmAssocCnf *) pMsgBuf)->protStatusCode,psessionEntry);
} // end if (((tLimMlmAssocCnf *) pMsgBuf)->resultCode != ....
} /*** end limProcessMlmAssocCnf() ***/
/**
* limProcessMlmReassocCnf()
*
*FUNCTION:
* This function is called to processes MLM_REASSOC_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmReassocCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tpPESession psessionEntry;
tLimMlmReassocCnf *pLimMlmReassocCnf;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
pLimMlmReassocCnf = (tLimMlmReassocCnf*) pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac,pLimMlmReassocCnf->sessionId))==NULL)
{
PELOGE(limLog(pMac, LOGE, FL("session Does not exist for given session Id"));)
return;
}
if ((psessionEntry->limSmeState != eLIM_SME_WT_REASSOC_STATE) ||
(psessionEntry->limSystemRole == eLIM_AP_ROLE)||(psessionEntry->limSystemRole == eLIM_BT_AMP_AP_ROLE))
{
/**
* Should not have received Reassocication confirm
* from MLM in other states OR on AP.
* Log error
*/
PELOGE(limLog(pMac, LOGE,
FL("Rcv unexpected MLM_REASSOC_CNF in role %d, sme state 0x%X"),
psessionEntry->limSystemRole, psessionEntry->limSmeState);)
return;
}
if (psessionEntry->pLimReAssocReq) {
palFreeMemory( pMac->hHdd, psessionEntry->pLimReAssocReq);
psessionEntry->pLimReAssocReq = NULL;
}
PELOGE(limLog(pMac, LOG1, FL("Rcv MLM_REASSOC_CNF with result code %d"), pLimMlmReassocCnf->resultCode);)
if (pLimMlmReassocCnf->resultCode == eSIR_SME_SUCCESS) {
// Successful Reassociation
PELOG1(limLog(pMac, LOG1, FL("*** Reassociated with new BSS ***"));)
psessionEntry->limSmeState = eLIM_SME_LINK_EST_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
/**
* Need to send Reassoc response with
* Reassociation success to Host.
*/
limSendSmeJoinReassocRsp(
pMac, eWNI_SME_REASSOC_RSP,
pLimMlmReassocCnf->resultCode, pLimMlmReassocCnf->protStatusCode,psessionEntry,
psessionEntry->smeSessionId,psessionEntry->transactionId);
}else if (pLimMlmReassocCnf->resultCode == eSIR_SME_REASSOC_REFUSED) {
/** Reassociation failure With the New AP
* but we still have the link with the Older AP
*/
psessionEntry->limSmeState = eLIM_SME_LINK_EST_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
/**
* Need to send Reassoc response with
* Association failure to Host.
*/
limSendSmeJoinReassocRsp(pMac, eWNI_SME_REASSOC_RSP,
pLimMlmReassocCnf->resultCode, pLimMlmReassocCnf->protStatusCode,psessionEntry,
psessionEntry->smeSessionId,psessionEntry->transactionId);
}else {
/* If driver gets deauth when its waiting for ADD_STA_RSP then we need
* to do DEL_STA followed by DEL_BSS. So based on below reason-code here
* we decide whether to do only DEL_BSS or DEL_STA + DEL_BSS
*/
if(pLimMlmReassocCnf->resultCode
!= eSIR_SME_JOIN_DEAUTH_FROM_AP_DURING_ADD_STA)
{
// Reassociation failure
psessionEntry->limSmeState = eLIM_SME_JOIN_FAILURE_STATE;
}
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
/**
* Need to send Reassoc response with
* Association failure to Host.
*/
limHandleSmeReaasocResult(pMac, pLimMlmReassocCnf->resultCode, pLimMlmReassocCnf->protStatusCode, psessionEntry);
}
} /*** end limProcessMlmReassocCnf() ***/
/**
* limProcessMlmReassocInd()
*
*FUNCTION:
* This function is called to processes MLM_REASSOC_IND
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmReassocInd(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tANI_U32 len;
tSirMsgQ msgQ;
tSirSmeReassocInd *pSirSmeReassocInd;
tpDphHashNode pStaDs=0;
tpPESession psessionEntry;
tANI_U8 sessionId;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
if((psessionEntry = peFindSessionByBssid(pMac,((tpLimMlmReassocInd)pMsgBuf)->peerMacAddr, &sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given BSSId"));)
return;
}
/// Inform Host of STA reassociation
len = sizeof(tSirSmeReassocInd);
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd, (void **)&pSirSmeReassocInd, len))
{
// Log error
limLog(pMac, LOGP,
FL("call to palAllocateMemory failed for eWNI_SME_REASSOC_IND"));
return;
}
sirStoreU16N((tANI_U8 *) &pSirSmeReassocInd->messageType,
eWNI_SME_REASSOC_IND);
limReassocIndSerDes(pMac, (tpLimMlmReassocInd) pMsgBuf,
(tANI_U8 *) &(pSirSmeReassocInd->length), psessionEntry);
// Required for indicating the frames to upper layer
pSirSmeReassocInd->assocReqLength = ((tpLimMlmReassocInd) pMsgBuf)->assocReqLength;
pSirSmeReassocInd->assocReqPtr = ((tpLimMlmReassocInd) pMsgBuf)->assocReqPtr;
pSirSmeReassocInd->beaconPtr = psessionEntry->beacon;
pSirSmeReassocInd->beaconLength = psessionEntry->bcnLen;
msgQ.type = eWNI_SME_REASSOC_IND;
msgQ.bodyptr = pSirSmeReassocInd;
msgQ.bodyval = 0;
MTRACE(macTraceMsgTx(pMac, psessionEntry->peSessionId, msgQ.type));
#ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT
limDiagEventReport(pMac, WLAN_PE_DIAG_REASSOC_IND_EVENT, psessionEntry, 0, 0);
#endif //FEATURE_WLAN_DIAG_SUPPORT
pStaDs = dphGetHashEntry(pMac, ((tpLimMlmReassocInd) pMsgBuf)->aid, &psessionEntry->dph.dphHashTable);
if (! pStaDs)
{
limLog( pMac, LOGP, FL("MLM ReAssocInd: Station context no longer valid (aid %d)"),
((tpLimMlmReassocInd) pMsgBuf)->aid);
palFreeMemory(pMac->hHdd, pSirSmeReassocInd);
return;
}
limSysProcessMmhMsgApi(pMac, &msgQ, ePROT);
PELOG1(limLog(pMac, LOG1,
FL("Create CNF_WAIT_TIMER after received LIM_MLM_REASSOC_IND"));)
/*
** turn on a timer to detect the loss of REASSOC CNF
**/
limActivateCnfTimer(pMac,
(tANI_U16) ((tpLimMlmReassocInd) pMsgBuf)->aid, psessionEntry);
} /*** end limProcessMlmReassocInd() ***/
/**
* limProcessMlmAuthInd()
*
*FUNCTION:
* This function is called to processes MLM_AUTH_IND
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmAuthInd(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tSirMsgQ msgQ;
tSirSmeAuthInd *pSirSmeAuthInd;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd, (void **)&pSirSmeAuthInd, sizeof(tSirSmeAuthInd)))
{
// Log error
limLog(pMac, LOGP,
FL("call to palAllocateMemory failed for eWNI_SME_AUTH_IND"));
}
limCopyU16((tANI_U8 *) &pSirSmeAuthInd->messageType, eWNI_SME_AUTH_IND);
limAuthIndSerDes(pMac, (tpLimMlmAuthInd) pMsgBuf,
(tANI_U8 *) &(pSirSmeAuthInd->length));
msgQ.type = eWNI_SME_AUTH_IND;
msgQ.bodyptr = pSirSmeAuthInd;
msgQ.bodyval = 0;
MTRACE(macTraceMsgTx(pMac, NO_SESSION, msgQ.type));
#ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT
limDiagEventReport(pMac, WLAN_PE_DIAG_AUTH_IND_EVENT, NULL, 0, 0);
#endif //FEATURE_WLAN_DIAG_SUPPORT
limSysProcessMmhMsgApi(pMac, &msgQ, ePROT);
} /*** end limProcessMlmAuthInd() ***/
void
limFillAssocIndParams(tpAniSirGlobal pMac, tpLimMlmAssocInd pAssocInd,
tSirSmeAssocInd *pSirSmeAssocInd,
tpPESession psessionEntry)
{
pSirSmeAssocInd->length = sizeof(tSirSmeAssocInd);
pSirSmeAssocInd->sessionId = psessionEntry->smeSessionId;
// Required for indicating the frames to upper layer
pSirSmeAssocInd->assocReqLength = pAssocInd->assocReqLength;
pSirSmeAssocInd->assocReqPtr = pAssocInd->assocReqPtr;
pSirSmeAssocInd->beaconPtr = psessionEntry->beacon;
pSirSmeAssocInd->beaconLength = psessionEntry->bcnLen;
// Fill in peerMacAddr
palCopyMemory( pMac->hHdd, pSirSmeAssocInd->peerMacAddr, pAssocInd->peerMacAddr, sizeof(tSirMacAddr));
// Fill in aid
pSirSmeAssocInd->aid = pAssocInd->aid;
// Fill in bssId
palCopyMemory( pMac->hHdd, pSirSmeAssocInd->bssId, psessionEntry->bssId, sizeof(tSirMacAddr));
// Fill in staId
//pSirSmeAssocInd->staId = psessionEntry->staId;
// Fill in authType
pSirSmeAssocInd->authType = pAssocInd->authType;
// Fill in ssId
palCopyMemory( pMac->hHdd, (tANI_U8*)&pSirSmeAssocInd->ssId,
(tANI_U8 *) &(pAssocInd->ssId), pAssocInd->ssId.length + 1);
pSirSmeAssocInd->rsnIE.length = pAssocInd->rsnIE.length;
palCopyMemory( pMac->hHdd, (tANI_U8*) &pSirSmeAssocInd->rsnIE.rsnIEdata,
(tANI_U8 *) &(pAssocInd->rsnIE.rsnIEdata),
pAssocInd->rsnIE.length);
pSirSmeAssocInd->addIE.length = pAssocInd->addIE.length;
palCopyMemory( pMac->hHdd, (tANI_U8*) &pSirSmeAssocInd->addIE.addIEdata,
(tANI_U8 *) &(pAssocInd->addIE.addIEdata),
pAssocInd->addIE.length);
// Copy the new TITAN capabilities
pSirSmeAssocInd->spectrumMgtIndicator = pAssocInd->spectrumMgtIndicator;
if (pAssocInd->spectrumMgtIndicator == eSIR_TRUE)
{
pSirSmeAssocInd->powerCap.minTxPower = pAssocInd->powerCap.minTxPower;
pSirSmeAssocInd->powerCap.maxTxPower = pAssocInd->powerCap.maxTxPower;
pSirSmeAssocInd->supportedChannels.numChnl = pAssocInd->supportedChannels.numChnl;
palCopyMemory( pMac->hHdd, (tANI_U8*) &pSirSmeAssocInd->supportedChannels.channelList,
(tANI_U8 *) &(pAssocInd->supportedChannels.channelList),
pAssocInd->supportedChannels.numChnl);
}
// Fill in WmmInfo
pSirSmeAssocInd->wmmEnabledSta = pAssocInd->WmmStaInfoPresent;
} /*** end limAssocIndSerDes() ***/
/**
* limProcessMlmAssocInd()
*
*FUNCTION:
* This function is called to processes MLM_ASSOC_IND
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmAssocInd(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tANI_U32 len;
tSirMsgQ msgQ;
tSirSmeAssocInd *pSirSmeAssocInd;
tpDphHashNode pStaDs=0;
tpPESession psessionEntry;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
if((psessionEntry = peFindSessionBySessionId(pMac,((tpLimMlmAssocInd) pMsgBuf)->sessionId))== NULL)
{
limLog( pMac, LOGE, FL( "Session Does not exist for given sessionId" ));
return;
}
/// Inform Host of STA association
len = sizeof(tSirSmeAssocInd);
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd, (void **)&pSirSmeAssocInd, len))
{
// Log error
limLog(pMac, LOGP,
FL("call to palAllocateMemory failed for eWNI_SME_ASSOC_IND"));
return;
}
pSirSmeAssocInd->messageType = eWNI_SME_ASSOC_IND;
limFillAssocIndParams(pMac, (tpLimMlmAssocInd) pMsgBuf, pSirSmeAssocInd, psessionEntry);
msgQ.type = eWNI_SME_ASSOC_IND;
msgQ.bodyptr = pSirSmeAssocInd;
msgQ.bodyval = 0;
pStaDs = dphGetHashEntry(pMac,
((tpLimMlmAssocInd) pMsgBuf)->aid, &psessionEntry->dph.dphHashTable);
if (! pStaDs)
{ // good time to panic...
limLog(pMac, LOGE, FL("MLM AssocInd: Station context no longer valid (aid %d)"),
((tpLimMlmAssocInd) pMsgBuf)->aid);
palFreeMemory(pMac->hHdd, pSirSmeAssocInd);
return;
}
pSirSmeAssocInd->staId = pStaDs->staIndex;
pSirSmeAssocInd->reassocReq = pStaDs->mlmStaContext.subType;
MTRACE(macTraceMsgTx(pMac, psessionEntry->peSessionId, msgQ.type));
#ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT
limDiagEventReport(pMac, WLAN_PE_DIAG_ASSOC_IND_EVENT, psessionEntry, 0, 0);
#endif //FEATURE_WLAN_DIAG_SUPPORT
limSysProcessMmhMsgApi(pMac, &msgQ, ePROT);
PELOG1(limLog(pMac, LOG1,
FL("Create CNF_WAIT_TIMER after received LIM_MLM_ASSOC_IND"));)
/*
** turn on a timer to detect the loss of ASSOC CNF
**/
limActivateCnfTimer(pMac, (tANI_U16) ((tpLimMlmAssocInd) pMsgBuf)->aid, psessionEntry);
// Enable this Compile flag to test the BT-AMP -AP assoc sequence
#ifdef TEST_BTAMP_AP
//tANI_U32 *pMsgBuf;
{
tpSirSmeAssocCnf pSmeAssoccnf;
if(!palAllocateMemory(pMac->hHdd,(void **)&pSmeAssoccnf,sizeof(tSirSmeAssocCnf)))
PELOGE(limLog(pMac, LOGE, FL("palAllocateMemory failed for pSmeAssoccnf "));)
pSmeAssoccnf->messageType = eWNI_SME_ASSOC_CNF;
pSmeAssoccnf->length = sizeof(tSirSmeAssocCnf);
palCopyMemory( pMac->hHdd,pSmeAssoccnf->peerMacAddr,((tpLimMlmAssocInd)pMsgBuf)->peerMacAddr,6);
pSmeAssoccnf->statusCode = eSIR_SME_SUCCESS;
pSmeAssoccnf->aid = ((tpLimMlmAssocInd)pMsgBuf)->aid;
palCopyMemory( pMac->hHdd, pSmeAssoccnf->alternateBssId,pSmeAssoccnf->peerMacAddr,sizeof(tSirMacAddr));
pSmeAssoccnf->alternateChannelId = 6;
palCopyMemory( pMac->hHdd,pSmeAssoccnf->bssId,psessionEntry->selfMacAddr,6);
pMsgBuf = (tANI_U32)pSmeAssoccnf;
__limProcessSmeAssocCnfNew(pMac, eWNI_SME_ASSOC_CNF, pMsgBuf);
palFreeMemory(pMac->hHdd,pSmeAssoccnf);
}
#endif
} /*** end limProcessMlmAssocInd() ***/
/**
* limProcessMlmDisassocInd()
*
*FUNCTION:
* This function is called to processes MLM_DISASSOC_IND
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmDisassocInd(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tLimMlmDisassocInd *pMlmDisassocInd;
tpPESession psessionEntry;
pMlmDisassocInd = (tLimMlmDisassocInd *) pMsgBuf;
if( (psessionEntry = peFindSessionBySessionId(pMac,pMlmDisassocInd->sessionId) )== NULL)
{
limLog(pMac, LOGP,FL("Session Does not exist for given sessionID"));
return;
}
switch (psessionEntry->limSystemRole)
{
case eLIM_STA_IN_IBSS_ROLE:
break;
case eLIM_STA_ROLE:
case eLIM_BT_AMP_STA_ROLE:
psessionEntry->limSmeState = eLIM_SME_WT_DISASSOC_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
break;
default: // eLIM_AP_ROLE //eLIM_BT_AMP_AP_ROLE
PELOG1(limLog(pMac, LOG1,
FL("*** Peer staId=%d Disassociated ***"),
pMlmDisassocInd->aid);)
// Send SME_DISASOC_IND after Polaris cleanup
// (after receiving LIM_MLM_PURGE_STA_IND)
break;
} // end switch (psessionEntry->limSystemRole)
} /*** end limProcessMlmDisassocInd() ***/
/**
* limProcessMlmDisassocCnf()
*
*FUNCTION:
* This function is called to processes MLM_DISASSOC_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmDisassocCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tSirResultCodes resultCode;
tLimMlmDisassocCnf *pMlmDisassocCnf;
tpPESession psessionEntry;
pMlmDisassocCnf = (tLimMlmDisassocCnf *) pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac,pMlmDisassocCnf->sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session Does not exist for given session Id"));)
return;
}
resultCode = (tSirResultCodes)
(pMlmDisassocCnf->disassocTrigger ==
eLIM_LINK_MONITORING_DISASSOC) ?
eSIR_SME_LOST_LINK_WITH_PEER_RESULT_CODE :
pMlmDisassocCnf->resultCode;
if ((psessionEntry->limSystemRole == eLIM_STA_ROLE)|| (psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE))
{
// Disassociate Confirm from MLM
if ( (psessionEntry->limSmeState != eLIM_SME_WT_DISASSOC_STATE) &&
(psessionEntry->limSmeState != eLIM_SME_WT_DEAUTH_STATE) )
{
/**
* Should not have received
* Disassocate confirm
* from MLM in other states.
* Log error
*/
PELOGE(limLog(pMac, LOGE,
FL("received unexpected MLM_DISASSOC_CNF in state %X"),psessionEntry->limSmeState);)
return;
}
if (pMac->lim.gLimRspReqd)
pMac->lim.gLimRspReqd = false;
if (pMlmDisassocCnf->disassocTrigger ==
eLIM_PROMISCUOUS_MODE_DISASSOC)
{
if (pMlmDisassocCnf->resultCode != eSIR_SME_SUCCESS)
psessionEntry->limSmeState = psessionEntry->limPrevSmeState;
else
psessionEntry->limSmeState = eLIM_SME_OFFLINE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
// Send Promiscuous mode response to host
limSendSmePromiscuousModeRsp(pMac);
}
else
{
if (pMlmDisassocCnf->resultCode != eSIR_SME_SUCCESS)
psessionEntry->limSmeState = psessionEntry->limPrevSmeState;
else
psessionEntry->limSmeState = eLIM_SME_IDLE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
limSendSmeDisassocNtf(pMac, pMlmDisassocCnf->peerMacAddr,
resultCode,
pMlmDisassocCnf->disassocTrigger,
pMlmDisassocCnf->aid,psessionEntry->smeSessionId,psessionEntry->transactionId,psessionEntry);
}
}
else if ( (psessionEntry->limSystemRole == eLIM_AP_ROLE)|| (psessionEntry->limSystemRole == eLIM_BT_AMP_AP_ROLE) )
{
limSendSmeDisassocNtf(pMac, pMlmDisassocCnf->peerMacAddr,
resultCode,
pMlmDisassocCnf->disassocTrigger,
pMlmDisassocCnf->aid,psessionEntry->smeSessionId,psessionEntry->transactionId,psessionEntry);
}
} /*** end limProcessMlmDisassocCnf() ***/
/**
* limProcessMlmDeauthInd()
*
*FUNCTION:
* This function is called to processes MLM_DEAUTH_IND
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmDeauthInd(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tLimMlmDeauthInd *pMlmDeauthInd;
tpPESession psessionEntry;
tANI_U8 sessionId;
pMlmDeauthInd = (tLimMlmDeauthInd *) pMsgBuf;
if((psessionEntry = peFindSessionByBssid(pMac,pMlmDeauthInd->peerMacAddr,&sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given BSSId"));)
return;
}
switch (psessionEntry->limSystemRole)
{
case eLIM_STA_IN_IBSS_ROLE:
break;
case eLIM_STA_ROLE:
case eLIM_BT_AMP_STA_ROLE:
psessionEntry->limSmeState = eLIM_SME_WT_DEAUTH_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
default: // eLIM_AP_ROLE
{
PELOG1(limLog(pMac, LOG1,
FL("*** Received Deauthentication from staId=%d ***"),
pMlmDeauthInd->aid);)
}
// Send SME_DEAUTH_IND after Polaris cleanup
// (after receiving LIM_MLM_PURGE_STA_IND)
break;
} // end switch (psessionEntry->limSystemRole)
} /*** end limProcessMlmDeauthInd() ***/
/**
* limProcessMlmDeauthCnf()
*
*FUNCTION:
* This function is called to processes MLM_DEAUTH_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmDeauthCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tANI_U16 aid;
tSirResultCodes resultCode;
tLimMlmDeauthCnf *pMlmDeauthCnf;
tpPESession psessionEntry;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
pMlmDeauthCnf = (tLimMlmDeauthCnf *) pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac,pMlmDeauthCnf->sessionId))==NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given session Id "));)
return;
}
resultCode = (tSirResultCodes)
(pMlmDeauthCnf->deauthTrigger ==
eLIM_LINK_MONITORING_DEAUTH) ?
eSIR_SME_LOST_LINK_WITH_PEER_RESULT_CODE :
pMlmDeauthCnf->resultCode;
aid = (psessionEntry->limSystemRole == eLIM_AP_ROLE) ?
pMlmDeauthCnf->aid : 1;
if ((psessionEntry->limSystemRole == eLIM_STA_ROLE)|| (psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE))
{
// Deauth Confirm from MLM
if (psessionEntry->limSmeState != eLIM_SME_WT_DEAUTH_STATE)
{
/**
* Should not have received Deauth confirm
* from MLM in other states.
* Log error
*/
PELOGE(limLog(pMac, LOGE,
FL("received unexpected MLM_DEAUTH_CNF in state %X"),
psessionEntry->limSmeState);)
return;
}
if (pMlmDeauthCnf->resultCode == eSIR_SME_SUCCESS)
{
psessionEntry->limSmeState = eLIM_SME_IDLE_STATE;
PELOG1(limLog(pMac, LOG1,
FL("*** Deauthenticated with BSS ***"));)
}
else
psessionEntry->limSmeState = psessionEntry->limPrevSmeState;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
if (pMac->lim.gLimRspReqd)
pMac->lim.gLimRspReqd = false;
}
// On STA or on BASIC AP, send SME_DEAUTH_RSP to host
limSendSmeDeauthNtf(pMac, pMlmDeauthCnf->peerMacAddr,
resultCode,
pMlmDeauthCnf->deauthTrigger,
aid,psessionEntry->smeSessionId,psessionEntry->transactionId);
} /*** end limProcessMlmDeauthCnf() ***/
/**
* limProcessMlmPurgeStaInd()
*
*FUNCTION:
* This function is called to processes MLM_PURGE_STA_IND
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmPurgeStaInd(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
tSirResultCodes resultCode;
tpLimMlmPurgeStaInd pMlmPurgeStaInd;
tpPESession psessionEntry;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
pMlmPurgeStaInd = (tpLimMlmPurgeStaInd) pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac,pMlmPurgeStaInd->sessionId))==NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given bssId"));)
return;
}
// Purge STA indication from MLM
resultCode = (tSirResultCodes) pMlmPurgeStaInd->reasonCode;
switch (psessionEntry->limSystemRole)
{
case eLIM_STA_IN_IBSS_ROLE:
break;
case eLIM_STA_ROLE:
case eLIM_BT_AMP_STA_ROLE:
default: // eLIM_AP_ROLE
if ((psessionEntry->limSystemRole == eLIM_STA_ROLE) &&
(psessionEntry->limSmeState !=
eLIM_SME_WT_DISASSOC_STATE) &&
(psessionEntry->limSmeState != eLIM_SME_WT_DEAUTH_STATE))
{
/**
* Should not have received
* Purge STA indication
* from MLM in other states.
* Log error
*/
PELOGE(limLog(pMac, LOGE,
FL("received unexpected MLM_PURGE_STA_IND in state %X"),
psessionEntry->limSmeState);)
break;
}
PELOG1(limLog(pMac, LOG1,
FL("*** Polaris cleanup completed for staId=%d ***"),
pMlmPurgeStaInd->aid);)
if ((psessionEntry->limSystemRole == eLIM_STA_ROLE)||(psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE))
{
psessionEntry->limSmeState = eLIM_SME_IDLE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
}
if (pMlmPurgeStaInd->purgeTrigger == eLIM_PEER_ENTITY_DEAUTH)
{
limSendSmeDeauthNtf(pMac,
pMlmPurgeStaInd->peerMacAddr,
resultCode,
pMlmPurgeStaInd->purgeTrigger,
pMlmPurgeStaInd->aid,psessionEntry->smeSessionId,psessionEntry->transactionId);
}
else
limSendSmeDisassocNtf(pMac,
pMlmPurgeStaInd->peerMacAddr,
resultCode,
pMlmPurgeStaInd->purgeTrigger,
pMlmPurgeStaInd->aid,psessionEntry->smeSessionId,psessionEntry->transactionId,psessionEntry);
} // end switch (psessionEntry->limSystemRole)
} /*** end limProcessMlmPurgeStaInd() ***/
/**
* limProcessMlmSetKeysCnf()
*
*FUNCTION:
* This function is called to processes MLM_SETKEYS_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmSetKeysCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
// Prepare and send SME_SETCONTEXT_RSP message
tLimMlmSetKeysCnf *pMlmSetKeysCnf;
tpPESession psessionEntry;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
pMlmSetKeysCnf = (tLimMlmSetKeysCnf *) pMsgBuf;
if ((psessionEntry = peFindSessionBySessionId(pMac, pMlmSetKeysCnf->sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given sessionId "));)
return;
}
limLog( pMac, LOG1,
FL("Received MLM_SETKEYS_CNF with resultCode = %d"),
pMlmSetKeysCnf->resultCode );
limSendSmeSetContextRsp(pMac,
pMlmSetKeysCnf->peerMacAddr,
1,
(tSirResultCodes) pMlmSetKeysCnf->resultCode,psessionEntry,psessionEntry->smeSessionId,
psessionEntry->transactionId);
} /*** end limProcessMlmSetKeysCnf() ***/
/**
* limProcessMlmRemoveKeyCnf()
*
*FUNCTION:
* This function is called to processes MLM_REMOVEKEY_CNF
* message from MLM State machine.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param pMsgBuf A pointer to the MLM message buffer
*
* @return None
*/
void
limProcessMlmRemoveKeyCnf(tpAniSirGlobal pMac, tANI_U32 *pMsgBuf)
{
// Prepare and send SME_REMOVECONTEXT_RSP message
tLimMlmRemoveKeyCnf *pMlmRemoveKeyCnf;
tpPESession psessionEntry;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
pMlmRemoveKeyCnf = (tLimMlmRemoveKeyCnf *) pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac,pMlmRemoveKeyCnf->sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session Does not exist for given session Id"));)
return;
}
limLog( pMac, LOG1,
FL("Received MLM_REMOVEKEYS_CNF with resultCode = %d"),
pMlmRemoveKeyCnf->resultCode );
limSendSmeRemoveKeyRsp(pMac,
pMlmRemoveKeyCnf->peerMacAddr,
(tSirResultCodes) pMlmRemoveKeyCnf->resultCode,psessionEntry,
psessionEntry->smeSessionId,psessionEntry->transactionId);
} /*** end limProcessMlmRemoveKeyCnf() ***/
/**
* limHandleSmeJoinResult()
*
*FUNCTION:
* This function is called to process join/auth/assoc failures
* upon receiving MLM_JOIN/AUTH/ASSOC_CNF with a failure code or
* MLM_ASSOC_CNF with a success code in case of STA role and
* MLM_JOIN_CNF with success in case of STA in IBSS role.
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param resultCode Failure code to be sent
*
*
* @return None
*/
static void
limHandleSmeJoinResult(tpAniSirGlobal pMac, tSirResultCodes resultCode, tANI_U16 protStatusCode, tpPESession psessionEntry)
{
tpDphHashNode pStaDs = NULL;
tANI_U8 smesessionId;
tANI_U16 smetransactionId;
/* Newly Added on oct 11 th*/
if(psessionEntry == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("psessionEntry is NULL "));)
return;
}
smesessionId = psessionEntry->smeSessionId;
smetransactionId = psessionEntry->transactionId;
/* When associations is failed , delete the session created and pass NULL to limsendsmeJoinReassocRsp() */
if(resultCode != eSIR_SME_SUCCESS)
{
pStaDs = dphGetHashEntry(pMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable);
if (pStaDs != NULL)
{
pStaDs->mlmStaContext.disassocReason = eSIR_MAC_UNSPEC_FAILURE_REASON;
pStaDs->mlmStaContext.cleanupTrigger = eLIM_JOIN_FAILURE;
pStaDs->mlmStaContext.resultCode = resultCode;
pStaDs->mlmStaContext.protStatusCode = protStatusCode;
//Done: 7-27-2009. JIM_FIX_ME: at the end of limCleanupRxPath, make sure PE is sending eWNI_SME_JOIN_RSP to SME
limCleanupRxPath(pMac, pStaDs, psessionEntry);
palFreeMemory( pMac->hHdd, psessionEntry->pLimJoinReq);
psessionEntry->pLimJoinReq = NULL;
return;
}
}
palFreeMemory( pMac->hHdd, psessionEntry->pLimJoinReq);
psessionEntry->pLimJoinReq = NULL;
//Delete teh session if JOIN failure occurred.
if(resultCode != eSIR_SME_SUCCESS)
{
if(NULL != psessionEntry)
{
if(limSetLinkState(pMac, eSIR_LINK_IDLE_STATE,psessionEntry->bssId,
psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS)
PELOGE(limLog(pMac, LOGE, FL("Failed to set the LinkState."));)
peDeleteSession(pMac,psessionEntry);
psessionEntry = NULL;
}
}
limSendSmeJoinReassocRsp(pMac, eWNI_SME_JOIN_RSP, resultCode, protStatusCode,psessionEntry,
smesessionId, smetransactionId);
} /*** end limHandleSmeJoinResult() ***/
/**
* limHandleSmeReaasocResult()
*
*FUNCTION:
* This function is called to process reassoc failures
* upon receiving REASSOC_CNF with a failure code or
* MLM_REASSOC_CNF with a success code in case of STA role
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param resultCode Failure code to be sent
*
*
* @return None
*/
static void
limHandleSmeReaasocResult(tpAniSirGlobal pMac, tSirResultCodes resultCode, tANI_U16 protStatusCode, tpPESession psessionEntry)
{
tpDphHashNode pStaDs = NULL;
tANI_U8 smesessionId;
tANI_U16 smetransactionId;
if(psessionEntry == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("psessionEntry is NULL "));)
return;
}
smesessionId = psessionEntry->smeSessionId;
smetransactionId = psessionEntry->transactionId;
/* When associations is failed , delete the session created and pass NULL to limsendsmeJoinReassocRsp() */
if(resultCode != eSIR_SME_SUCCESS)
{
pStaDs = dphGetHashEntry(pMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable);
if (pStaDs != NULL)
{
pStaDs->mlmStaContext.disassocReason = eSIR_MAC_UNSPEC_FAILURE_REASON;
pStaDs->mlmStaContext.cleanupTrigger = eLIM_JOIN_FAILURE;
pStaDs->mlmStaContext.resultCode = resultCode;
pStaDs->mlmStaContext.protStatusCode = protStatusCode;
limCleanupRxPath(pMac, pStaDs, psessionEntry);
return;
}
}
//Delete teh session if REASSOC failure occurred.
if(resultCode != eSIR_SME_SUCCESS)
{
if(NULL != psessionEntry)
{
peDeleteSession(pMac,psessionEntry);
psessionEntry = NULL;
}
}
limSendSmeJoinReassocRsp(pMac, eWNI_SME_REASSOC_RSP, resultCode, protStatusCode,psessionEntry,
smesessionId, smetransactionId);
} /*** end limHandleSmeReassocResult() ***/
/**
* limProcessMlmAddStaRsp()
*
*FUNCTION:
* This function is called to process a WDA_ADD_STA_RSP from HAL.
* Upon receipt of this message from HAL, MLME -
* > Determines the "state" in which this message was received
* > Forwards it to the appropriate callback
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param tSirMsgQ The MsgQ header, which contains the response buffer
*
* @return None
*/
void limProcessMlmAddStaRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ,tpPESession psessionEntry )
{
//we need to process the deferred message since the initiating req. there might be nested request.
//in the case of nested request the new request initiated from the response will take care of resetting
//the deffered flag.
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
if ((psessionEntry->limSystemRole == eLIM_BT_AMP_AP_ROLE)
|| (psessionEntry->limSystemRole == eLIM_AP_ROLE)
)
{
limProcessBtAmpApMlmAddStaRsp(pMac, limMsgQ,psessionEntry);
return;
}
limProcessStaMlmAddStaRsp(pMac, limMsgQ,psessionEntry);
}
void limProcessStaMlmAddStaRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ ,tpPESession psessionEntry)
{
tLimMlmAssocCnf mlmAssocCnf;
tpDphHashNode pStaDs;
tANI_U32 mesgType = LIM_MLM_ASSOC_CNF;
tpAddStaParams pAddStaParams = (tpAddStaParams) limMsgQ->bodyptr;
if(NULL == pAddStaParams )
{
limLog( pMac, LOGE, FL( "Encountered NULL Pointer" ));
return;
}
if (true == psessionEntry->fDeauthReceived)
{
PELOGE(limLog(pMac, LOGE,
FL("Received Deauth frame in ADD_STA_RESP state"));)
if (eHAL_STATUS_SUCCESS == pAddStaParams->status)
{
PELOGE(limLog(pMac, LOGE,
FL("ADD_STA success, send update result code with"
"eSIR_SME_JOIN_DEAUTH_FROM_AP_DURING_ADD_STA staIdx: %d"
"limMlmState: %d"), pAddStaParams->staIdx,
psessionEntry->limMlmState);)
if(psessionEntry->limSmeState == eLIM_SME_WT_REASSOC_STATE)
mesgType = LIM_MLM_REASSOC_CNF;
//We are sending result code eSIR_SME_JOIN_DEAUTH_FROM_AP_DURING_ADD_STA
//which will trigger proper cleanup (DEL_STA/DEL_BSS both required) in
//either assoc cnf or reassoc cnf handler.
mlmAssocCnf.resultCode =
(tSirResultCodes) eSIR_SME_JOIN_DEAUTH_FROM_AP_DURING_ADD_STA;
psessionEntry->staId = pAddStaParams->staIdx;
goto end;
}
}
if ( eHAL_STATUS_SUCCESS == pAddStaParams->status )
{
if ( eLIM_MLM_WT_ADD_STA_RSP_STATE != psessionEntry->limMlmState)
{
//TODO: any response to be sent out here ?
limLog( pMac, LOGE,
FL( "Received unexpected WDA_ADD_STA_RSP in state %X" ),
psessionEntry->limMlmState);
mlmAssocCnf.resultCode = (tSirResultCodes) eSIR_SME_REFUSED;
goto end;
}
if(psessionEntry->limSmeState == eLIM_SME_WT_REASSOC_STATE)
mesgType = LIM_MLM_REASSOC_CNF;
//
// Update the DPH Hash Entry for this STA
// with proper state info
//
pStaDs = dphGetHashEntry( pMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable);
if( NULL != pStaDs)
pStaDs->mlmStaContext.mlmState = eLIM_MLM_LINK_ESTABLISHED_STATE;
else
limLog( pMac, LOGW,
FL( "Unable to get the DPH Hash Entry for AID - %d" ),
DPH_STA_HASH_INDEX_PEER);
psessionEntry->limMlmState = eLIM_MLM_LINK_ESTABLISHED_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
/*
* Storing the self StaIndex(Generated by HAL) in session context,
* instead of storing it in DPH Hash entry for Self STA.
* DPH entry for the self STA stores the sta index for the BSS entry
* to which the STA is associated.
*/
psessionEntry->staId = pAddStaParams->staIdx;
//if the AssocRsp frame is not acknowledged, then keep alive timer will take care of the state
#ifdef WLAN_ACTIVEMODE_OFFLOAD_FEATURE
if(!IS_ACTIVEMODE_OFFLOAD_FEATURE_ENABLE)
#endif
{
limReactivateHeartBeatTimer(pMac, psessionEntry);
}
MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, psessionEntry->peSessionId, eLIM_KEEPALIVE_TIMER));
//assign the sessionId to the timer Object
pMac->lim.limTimers.gLimKeepaliveTimer.sessionId = psessionEntry->peSessionId;
if (tx_timer_activate(&pMac->lim.limTimers.gLimKeepaliveTimer) != TX_SUCCESS)
limLog(pMac, LOGP, FL("Cannot activate keepalive timer."));
#ifdef WLAN_DEBUG
pMac->lim.gLimNumLinkEsts++;
#endif
#ifdef FEATURE_WLAN_TDLS
/* initialize TDLS peer related data */
limInitTdlsData(pMac,psessionEntry);
#endif
// Return Assoc confirm to SME with success
// FIXME_GEN4 - Need the correct ASSOC RSP code to
// be passed in here....
//mlmAssocCnf.resultCode = (tSirResultCodes) assoc.statusCode;
mlmAssocCnf.resultCode = (tSirResultCodes) eSIR_SME_SUCCESS;
}
else
{
limLog( pMac, LOGE, FL( "ADD_STA failed!"));
if(psessionEntry->limSmeState == eLIM_SME_WT_REASSOC_STATE)
mesgType = LIM_MLM_REASSOC_CNF;
mlmAssocCnf.resultCode = (tSirResultCodes) eSIR_SME_REFUSED;
}
end:
if( 0 != limMsgQ->bodyptr )
{
palFreeMemory( pMac->hHdd, (void *) pAddStaParams );
}
/* Updating PE session Id*/
mlmAssocCnf.sessionId = psessionEntry->peSessionId;
limPostSmeMessage( pMac, mesgType, (tANI_U32 *) &mlmAssocCnf );
if (true == psessionEntry->fDeauthReceived)
{
psessionEntry->fDeauthReceived = false;
}
return;
}
void limProcessMlmDelBssRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ,tpPESession psessionEntry)
{
//we need to process the deferred message since the initiating req. there might be nested request.
//in the case of nested request the new request initiated from the response will take care of resetting
//the deffered flag.
// tpPESession psessionEntry;
// tpDeleteBssParams pDeleteBssParams =( tpDeleteBssParams)limMsgQ->bodyptr;
// if((psessionEntry = peFindSessionBySessionId(pMac,pDeleteBssParams->sessionId)) == NULL)
// {
// limLog( pMac, LOGE, FL( "Session deos not exist with given sessionId" ));
// return;
// }
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
if (((psessionEntry->limSystemRole == eLIM_BT_AMP_AP_ROLE) ||
(psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE)
|| (psessionEntry->limSystemRole == eLIM_AP_ROLE)
) &&
(psessionEntry->statypeForBss == STA_ENTRY_SELF))
{
limProcessBtAmpApMlmDelBssRsp(pMac, limMsgQ,psessionEntry);
return;
}
limProcessStaMlmDelBssRsp(pMac, limMsgQ,psessionEntry);
if(!limIsInMCC(pMac))
{
WDA_TrafficStatsTimerActivate(FALSE);
}
}
void limProcessStaMlmDelBssRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ,tpPESession psessionEntry)
{
tpDeleteBssParams pDelBssParams = (tpDeleteBssParams) limMsgQ->bodyptr;
tpDphHashNode pStaDs = dphGetHashEntry(pMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable);
tSirResultCodes statusCode = eSIR_SME_SUCCESS;
if (NULL == pDelBssParams)
{
limLog( pMac, LOGE, FL( "Invalid body pointer in message"));
goto end;
}
if( eHAL_STATUS_SUCCESS == pDelBssParams->status )
{
PELOGW(limLog( pMac, LOGW,
FL( "STA received the DEL_BSS_RSP for BSSID: %X."),pDelBssParams->bssIdx);)
if (limSetLinkState(pMac, eSIR_LINK_IDLE_STATE, psessionEntry->bssId,
psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS)
{
PELOGE(limLog( pMac, LOGE, FL( "Failure in setting link state to IDLE"));)
statusCode = eSIR_SME_REFUSED;
goto end;
}
if(pStaDs == NULL)
{
limLog( pMac, LOGE, FL( "DPH Entry for STA 1 missing."));
statusCode = eSIR_SME_REFUSED;
goto end;
}
if( eLIM_MLM_WT_DEL_BSS_RSP_STATE != pStaDs->mlmStaContext.mlmState)
{
PELOGE(limLog( pMac, LOGE, FL( "Received unexpected WDA_DEL_BSS_RSP in state %X" ),
pStaDs->mlmStaContext.mlmState);)
statusCode = eSIR_SME_REFUSED;
goto end;
}
PELOG1(limLog( pMac, LOG1, FL("STA AssocID %d MAC "), pStaDs->assocId );
limPrintMacAddr(pMac, pStaDs->staAddr, LOG1);)
}
else
{
limLog( pMac, LOGE, FL( "DEL BSS failed!" ) );
palFreeMemory( pMac->hHdd, (void *) pDelBssParams );
limMsgQ->bodyptr = NULL;
return;
}
end:
if( 0 != limMsgQ->bodyptr )
{
palFreeMemory( pMac->hHdd, (void *) pDelBssParams );
limMsgQ->bodyptr = NULL;
}
if(pStaDs == NULL)
return;
if ( ((psessionEntry->limSystemRole == eLIM_STA_ROLE) || (psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE)) &&
(psessionEntry->limSmeState != eLIM_SME_WT_DISASSOC_STATE &&
psessionEntry->limSmeState != eLIM_SME_WT_DEAUTH_STATE) &&
pStaDs->mlmStaContext.cleanupTrigger != eLIM_JOIN_FAILURE)
{
/** The Case where the DelBss is invoked from
* context of other than normal DisAssoc / Deauth OR
* as part of Join Failure.
*/
limHandleDelBssInReAssocContext(pMac, pStaDs,psessionEntry);
return;
}
limPrepareAndSendDelStaCnf(pMac, pStaDs, statusCode,psessionEntry);
return;
}
void limProcessBtAmpApMlmDelBssRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ,tpPESession psessionEntry)
{
tSirResultCodes rc = eSIR_SME_SUCCESS;
tSirRetStatus status;
tpDeleteBssParams pDelBss = (tpDeleteBssParams) limMsgQ->bodyptr;
tSirMacAddr nullBssid = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
if(psessionEntry == NULL)
{
limLog(pMac, LOGE,FL("Session entry passed is NULL"));
if(pDelBss != NULL)
{
palFreeMemory( pMac->hHdd, (void *) pDelBss );
limMsgQ->bodyptr = NULL;
}
return;
}
if (pDelBss == NULL)
{
PELOGE(limLog(pMac, LOGE, FL("BSS: DEL_BSS_RSP with no body!"));)
rc = eSIR_SME_REFUSED;
goto end;
}
pMac->lim.gLimMlmState = eLIM_MLM_IDLE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, NO_SESSION, pMac->lim.gLimMlmState));
if( eLIM_MLM_WT_DEL_BSS_RSP_STATE != psessionEntry->limMlmState)
{
limLog( pMac, LOGE,
FL( "Received unexpected WDA_DEL_BSS_RSP in state %X" ),
psessionEntry->limMlmState);
rc = eSIR_SME_REFUSED;
goto end;
}
if (pDelBss->status != eHAL_STATUS_SUCCESS)
{
limLog(pMac, LOGE, FL("BSS: DEL_BSS_RSP error (%x) Bss %d "),
pDelBss->status, pDelBss->bssIdx);
rc = eSIR_SME_STOP_BSS_FAILURE;
goto end;
}
status = limSetLinkState(pMac, eSIR_LINK_IDLE_STATE, nullBssid,
psessionEntry->selfMacAddr, NULL, NULL);
if (status != eSIR_SUCCESS)
{
rc = eSIR_SME_REFUSED;
goto end;
}
/** Softmac may send all the buffered packets right after resuming the transmission hence
* to occupy the medium during non channel occupancy period. So resume the transmission after
* HAL gives back the response.
*/
#if 0 //TODO: How to handle this per session
if (LIM_IS_RADAR_DETECTED(pMac))
{
limFrameTransmissionControl(pMac, eLIM_TX_BSS_BUT_BEACON, eLIM_RESUME_TX);
LIM_SET_RADAR_DETECTED(pMac, eANI_BOOLEAN_FALSE);
}
#endif
dphHashTableClassInit(pMac, &psessionEntry->dph.dphHashTable);//TBD-RAJESH is it needed ?
limDeletePreAuthList(pMac);
//Initialize number of associated stations during cleanup
psessionEntry->gLimNumOfCurrentSTAs = 0;
end:
limSendSmeRsp(pMac, eWNI_SME_STOP_BSS_RSP, rc, psessionEntry->smeSessionId, psessionEntry->transactionId);
peDeleteSession(pMac, psessionEntry);
if(pDelBss != NULL)
{
palFreeMemory( pMac->hHdd, (void *) pDelBss );
limMsgQ->bodyptr = NULL;
}
}
void limProcessMlmDelStaRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ )
{
//we need to process the deferred message since the initiating req. there might be nested request.
//in the case of nested request the new request initiated from the response will take care of resetting
//the deffered flag.
tpPESession psessionEntry;
tpDeleteStaParams pDeleteStaParams;
pDeleteStaParams = (tpDeleteStaParams)limMsgQ->bodyptr;
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
if(NULL == pDeleteStaParams ||
NULL == (psessionEntry = peFindSessionBySessionId(pMac, pDeleteStaParams->sessionId)))
{
limLog(pMac, LOGP,FL("Session Does not exist or invalid body pointer in message"));
if(pDeleteStaParams != NULL)
{
palFreeMemory( pMac->hHdd, (void *) pDeleteStaParams );
limMsgQ->bodyptr = NULL;
}
return;
}
if ((psessionEntry->limSystemRole == eLIM_BT_AMP_AP_ROLE)
|| (psessionEntry->limSystemRole == eLIM_AP_ROLE)
)
{
limProcessBtAmpApMlmDelStaRsp(pMac,limMsgQ,psessionEntry);
return;
}
limProcessStaMlmDelStaRsp(pMac, limMsgQ,psessionEntry);
}
void limProcessBtAmpApMlmDelStaRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ,tpPESession psessionEntry)
{
tpDeleteStaParams pDelStaParams = (tpDeleteStaParams) limMsgQ->bodyptr;
tpDphHashNode pStaDs;
tSirResultCodes statusCode = eSIR_SME_SUCCESS;
if(limMsgQ->bodyptr == NULL)
{
return;
}
pStaDs = dphGetHashEntry(pMac, pDelStaParams->assocId, &psessionEntry->dph.dphHashTable);
if(pStaDs == NULL)
{
limLog( pMac, LOGE,
FL( "DPH Entry for STA %X missing."), pDelStaParams->assocId);
statusCode = eSIR_SME_REFUSED;
palFreeMemory( pMac->hHdd, (void *) pDelStaParams );
limMsgQ->bodyptr = NULL;
return;
}
if( eHAL_STATUS_SUCCESS == pDelStaParams->status )
{
limLog( pMac, LOGW,
FL( "AP received the DEL_STA_RSP for assocID: %X."), pDelStaParams->assocId);
if(( eLIM_MLM_WT_DEL_STA_RSP_STATE != pStaDs->mlmStaContext.mlmState) &&
( eLIM_MLM_WT_ASSOC_DEL_STA_RSP_STATE != pStaDs->mlmStaContext.mlmState))
{
limLog( pMac, LOGE,
FL( "Received unexpected WDA_DEL_STA_RSP in state %s for staId %d assocId %d " ),
limMlmStateStr(pStaDs->mlmStaContext.mlmState), pStaDs->staIndex, pStaDs->assocId);
statusCode = eSIR_SME_REFUSED;
goto end;
}
limLog( pMac, LOG1,
FL("Deleted STA AssocID %d staId %d MAC "),
pStaDs->assocId, pStaDs->staIndex);
limPrintMacAddr(pMac, pStaDs->staAddr, LOG1);
if(eLIM_MLM_WT_ASSOC_DEL_STA_RSP_STATE == pStaDs->mlmStaContext.mlmState)
{
palFreeMemory( pMac->hHdd, (void *) pDelStaParams );
limMsgQ->bodyptr = NULL;
if (limAddSta(pMac, pStaDs, false, psessionEntry) != eSIR_SUCCESS)
{
PELOGE(limLog(pMac, LOGE,
FL("could not Add STA with assocId=%d"),
pStaDs->assocId);)
// delete the TS if it has already been added.
// send the response with error status.
if(pStaDs->qos.addtsPresent)
{
tpLimTspecInfo pTspecInfo;
if(eSIR_SUCCESS == limTspecFindByAssocId(pMac, pStaDs->assocId,
&pStaDs->qos.addts.tspec, &pMac->lim.tspecInfo[0], &pTspecInfo))
{
limAdmitControlDeleteTS(pMac, pStaDs->assocId, &pStaDs->qos.addts.tspec.tsinfo,
NULL, &pTspecInfo->idx);
}
}
limRejectAssociation(pMac,
pStaDs->staAddr,
pStaDs->mlmStaContext.subType,
true, pStaDs->mlmStaContext.authType,
pStaDs->assocId, true,
(tSirResultCodes) eSIR_MAC_UNSPEC_FAILURE_STATUS,
psessionEntry);
}
return;
}
}
else
{
limLog( pMac, LOGW,
FL( "DEL STA failed!" ));
statusCode = eSIR_SME_REFUSED;
}
end:
palFreeMemory( pMac->hHdd, (void *) pDelStaParams );
limMsgQ->bodyptr = NULL;
if(eLIM_MLM_WT_ASSOC_DEL_STA_RSP_STATE != pStaDs->mlmStaContext.mlmState)
{
limPrepareAndSendDelStaCnf(pMac, pStaDs, statusCode,psessionEntry);
}
return;
}
void limProcessStaMlmDelStaRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ,tpPESession psessionEntry)
{
tSirResultCodes statusCode = eSIR_SME_SUCCESS;
tpDeleteStaParams pDelStaParams = (tpDeleteStaParams) limMsgQ->bodyptr;
tpDphHashNode pStaDs = NULL;
if(NULL == pDelStaParams )
{
limLog( pMac, LOGE, FL( "Encountered NULL Pointer" ));
goto end;
}
if( eHAL_STATUS_SUCCESS == pDelStaParams->status )
{
pStaDs = dphGetHashEntry(pMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable);
if (pStaDs == NULL)
{
//TODO: any response to be sent out here ?
limLog( pMac, LOGE, FL( "DPH Entry for STA %X missing."),
pDelStaParams->assocId);
statusCode = eSIR_SME_REFUSED;
goto end;
}
if( eLIM_MLM_WT_DEL_STA_RSP_STATE != psessionEntry->limMlmState)
{
//TODO: any response to be sent out here ?
limLog( pMac, LOGE, FL( "Received unexpected WDA_DELETE_STA_RSP in state %s" ),
limMlmStateStr(psessionEntry->limMlmState));
statusCode = eSIR_SME_REFUSED;
goto end;
}
PELOG1(limLog( pMac, LOG1, FL("STA AssocID %d MAC "), pStaDs->assocId );
limPrintMacAddr(pMac, pStaDs->staAddr, LOG1);)
limLog( pMac, LOGW, FL( "DEL_STA_RSP received for assocID: %X"), pDelStaParams->assocId);
//we must complete all cleanup related to delSta before calling limDelBSS.
if( 0 != limMsgQ->bodyptr )
{
palFreeMemory( pMac->hHdd, (void *) pDelStaParams );
limMsgQ->bodyptr = NULL;
}
statusCode = (tSirResultCodes) limDelBss(pMac, pStaDs, 0,psessionEntry);
return;
}
else
{
limLog( pMac, LOGE, FL( "DEL_STA failed for sta Id %d" ), pDelStaParams->staIdx);
statusCode = eSIR_SME_REFUSED;
}
end:
if( 0 != limMsgQ->bodyptr )
{
palFreeMemory( pMac->hHdd, (void *) pDelStaParams );
limMsgQ->bodyptr = NULL;
}
return;
}
void limProcessBtAmpApMlmAddStaRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ,tpPESession psessionEntry)
{
tpAddStaParams pAddStaParams = (tpAddStaParams) limMsgQ->bodyptr;
tpDphHashNode pStaDs = NULL;
if (NULL == pAddStaParams)
{
limLog( pMac, LOGE, FL( "Invalid body pointer in message"));
goto end;
}
pStaDs = dphGetHashEntry(pMac, pAddStaParams->assocId, &psessionEntry->dph.dphHashTable);
if(pStaDs == NULL)
{
//TODO: any response to be sent out here ?
limLog( pMac, LOGE, FL( "DPH Entry for STA %X missing."), pAddStaParams->assocId);
goto end;
}
//
// TODO & FIXME_GEN4
// Need to inspect tSirMsgQ.reserved for a valid Dialog token!
//
//TODO: any check for pMac->lim.gLimMlmState ?
if( eLIM_MLM_WT_ADD_STA_RSP_STATE != pStaDs->mlmStaContext.mlmState)
{
//TODO: any response to be sent out here ?
limLog( pMac, LOGE,
FL( "Received unexpected WDA_ADD_STA_RSP in state %X" ),
pStaDs->mlmStaContext.mlmState);
goto end;
}
if(eHAL_STATUS_SUCCESS != pAddStaParams->status)
{
PELOGE(limLog(pMac, LOGE, FL("Error! rcvd delSta rsp from HAL with status %d"),pAddStaParams->status);)
limRejectAssociation(pMac, pStaDs->staAddr,
pStaDs->mlmStaContext.subType,
true, pStaDs->mlmStaContext.authType,
pStaDs->assocId, true,
(tSirResultCodes) eSIR_MAC_UNSPEC_FAILURE_STATUS,
psessionEntry);
goto end;
}
pStaDs->bssId = pAddStaParams->bssIdx;
pStaDs->staIndex = pAddStaParams->staIdx;
//if the AssocRsp frame is not acknowledged, then keep alive timer will take care of the state
pStaDs->valid = 1;
pStaDs->mlmStaContext.mlmState = eLIM_MLM_WT_ASSOC_CNF_STATE;
limLog( pMac, LOG1,
FL("STA AssocID %d staId %d MAC "),
pStaDs->assocId,
pStaDs->staIndex);
limPrintMacAddr(pMac, pStaDs->staAddr, LOG1);
/* For BTAMP-AP, the flow sequence shall be:
* 1) PE sends eWNI_SME_ASSOC_IND to SME
* 2) PE receives eWNI_SME_ASSOC_CNF from SME
* 3) BTAMP-AP sends Re/Association Response to BTAMP-STA
*/
limSendMlmAssocInd(pMac, pStaDs, psessionEntry);
// fall though to reclaim the original Add STA Response message
end:
if( 0 != limMsgQ->bodyptr )
{
palFreeMemory( pMac->hHdd, (void *) pAddStaParams );
limMsgQ->bodyptr = NULL;
}
return;
}
/**
* limProcessApMlmAddBssRsp()
*
*FUNCTION:
* This function is called to process a WDA_ADD_BSS_RSP from HAL.
* Upon receipt of this message from HAL, MLME -
* > Validates the result of WDA_ADD_BSS_REQ
* > Init other remaining LIM variables
* > Init the AID pool, for that BSSID
* > Init the Pre-AUTH list, for that BSSID
* > Create LIM timers, specific to that BSSID
* > Init DPH related parameters that are specific to that BSSID
* > TODO - When do we do the actual change channel?
*
*LOGIC:
* SME sends eWNI_SME_START_BSS_REQ to LIM
* LIM sends LIM_MLM_START_REQ to MLME
* MLME sends WDA_ADD_BSS_REQ to HAL
* HAL responds with WDA_ADD_BSS_RSP to MLME
* MLME responds with LIM_MLM_START_CNF to LIM
* LIM responds with eWNI_SME_START_BSS_RSP to SME
*
*ASSUMPTIONS:
* tSirMsgQ.body is allocated by MLME during limProcessMlmStartReq
* tSirMsgQ.body will now be freed by this routine
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param tSirMsgQ The MsgQ header, which contains the response buffer
*
* @return None
*/
static void
limProcessApMlmAddBssRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ)
{
tLimMlmStartCnf mlmStartCnf;
tANI_U32 val;
tpPESession psessionEntry;
// tANI_U8 sessionId;
tpAddBssParams pAddBssParams = (tpAddBssParams) limMsgQ->bodyptr;
if(NULL == pAddBssParams )
{
limLog( pMac, LOGE, FL( "Encountered NULL Pointer" ));
goto end;
}
//TBD: free the memory before returning, do it for all places where lookup fails.
if((psessionEntry = peFindSessionBySessionId(pMac,pAddBssParams->sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given sessionId"));)
if( NULL != pAddBssParams )
{
palFreeMemory( pMac->hHdd, (void *) pAddBssParams );
limMsgQ->bodyptr = NULL;
}
return;
}
/* Update PE session Id*/
mlmStartCnf.sessionId = pAddBssParams->sessionId;
if( eHAL_STATUS_SUCCESS == pAddBssParams->status )
{
PELOG2(limLog(pMac, LOG2, FL("WDA_ADD_BSS_RSP returned with eHAL_STATUS_SUCCESS"));)
if (limSetLinkState(pMac, eSIR_LINK_AP_STATE,psessionEntry->bssId,
psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS )
goto end;
// Set MLME state
psessionEntry->limMlmState = eLIM_MLM_BSS_STARTED_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
if( eSIR_IBSS_MODE == pAddBssParams->bssType )
{
/** IBSS is 'active' when we receive
* Beacon frames from other STAs that are part of same IBSS.
* Mark internal state as inactive until then.
*/
psessionEntry->limIbssActive = false;
psessionEntry->statypeForBss = STA_ENTRY_PEER; //to know session created for self/peer
limResetHBPktCount( psessionEntry );
limHeartBeatDeactivateAndChangeTimer(pMac, psessionEntry);
MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, psessionEntry->peSessionId, eLIM_HEART_BEAT_TIMER));
if (limActivateHearBeatTimer(pMac) != TX_SUCCESS)
limLog(pMac, LOGP, FL("could not activate Heartbeat timer"));
}
psessionEntry->bssIdx = (tANI_U8) pAddBssParams->bssIdx;
psessionEntry->limSystemRole = eLIM_STA_IN_IBSS_ROLE;
if ( eSIR_INFRA_AP_MODE == pAddBssParams->bssType )
psessionEntry->limSystemRole = eLIM_AP_ROLE;
else
psessionEntry->limSystemRole = eLIM_STA_IN_IBSS_ROLE;
schEdcaProfileUpdate(pMac, psessionEntry);
limInitPreAuthList(pMac);
limInitPeerIdxpool(pMac,psessionEntry);
// Create timers used by LIM
if (!pMac->lim.gLimTimersCreated)
limCreateTimers(pMac);
// Start OLBC timer
if (tx_timer_activate(&pMac->lim.limTimers.gLimUpdateOlbcCacheTimer) != TX_SUCCESS)
{
limLog(pMac, LOGE, FL("tx_timer_activate failed"));
}
/* Update the lim global gLimTriggerBackgroundScanDuringQuietBss */
if( eSIR_SUCCESS != wlan_cfgGetInt( pMac, WNI_CFG_TRIG_STA_BK_SCAN, &val ))
limLog( pMac, LOGP, FL("Failed to get WNI_CFG_TRIG_STA_BK_SCAN!"));
pMac->lim.gLimTriggerBackgroundScanDuringQuietBss = (val) ? 1 : 0;
// Apply previously set configuration at HW
limApplyConfiguration(pMac,psessionEntry);
psessionEntry->staId = pAddBssParams->staContext.staIdx;
mlmStartCnf.resultCode = eSIR_SME_SUCCESS;
}
else
{
limLog( pMac, LOGE, FL( "WDA_ADD_BSS_REQ failed with status %d" ),pAddBssParams->status );
mlmStartCnf.resultCode = eSIR_SME_HAL_SEND_MESSAGE_FAIL;
}
limPostSmeMessage( pMac, LIM_MLM_START_CNF, (tANI_U32 *) &mlmStartCnf );
end:
if( 0 != limMsgQ->bodyptr )
{
palFreeMemory( pMac->hHdd, (void *) pAddBssParams );
limMsgQ->bodyptr = NULL;
}
}
/**
* limProcessIbssMlmAddBssRsp()
*
*FUNCTION:
* This function is called to process a WDA_ADD_BSS_RSP from HAL.
* Upon receipt of this message from HAL, MLME -
* > Validates the result of WDA_ADD_BSS_REQ
* > Init other remaining LIM variables
* > Init the AID pool, for that BSSID
* > Init the Pre-AUTH list, for that BSSID
* > Create LIM timers, specific to that BSSID
* > Init DPH related parameters that are specific to that BSSID
* > TODO - When do we do the actual change channel?
*
*LOGIC:
* SME sends eWNI_SME_START_BSS_REQ to LIM
* LIM sends LIM_MLM_START_REQ to MLME
* MLME sends WDA_ADD_BSS_REQ to HAL
* HAL responds with WDA_ADD_BSS_RSP to MLME
* MLME responds with LIM_MLM_START_CNF to LIM
* LIM responds with eWNI_SME_START_BSS_RSP to SME
*
*ASSUMPTIONS:
* tSirMsgQ.body is allocated by MLME during limProcessMlmStartReq
* tSirMsgQ.body will now be freed by this routine
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param tSirMsgQ The MsgQ header, which contains the response buffer
*
* @return None
*/
static void
limProcessIbssMlmAddBssRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ ,tpPESession psessionEntry)
{
tLimMlmStartCnf mlmStartCnf;
tpAddBssParams pAddBssParams = (tpAddBssParams) limMsgQ->bodyptr;
tANI_U32 val;
if (NULL == pAddBssParams)
{
limLog( pMac, LOGE, FL( "Invalid body pointer in message"));
goto end;
}
if( eHAL_STATUS_SUCCESS == pAddBssParams->status )
{
PELOG1(limLog(pMac, LOG1, FL("WDA_ADD_BSS_RSP returned with eHAL_STATUS_SUCCESS"));)
if (limSetLinkState(pMac, eSIR_LINK_IBSS_STATE,psessionEntry->bssId,
psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS )
goto end;
// Set MLME state
psessionEntry->limMlmState = eLIM_MLM_BSS_STARTED_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
/** IBSS is 'active' when we receive
* Beacon frames from other STAs that are part of same IBSS.
* Mark internal state as inactive until then.
*/
psessionEntry->limIbssActive = false;
limResetHBPktCount( psessionEntry );
/* Timer related functions are not modified for BT-AMP : To be Done */
limHeartBeatDeactivateAndChangeTimer(pMac, psessionEntry);
MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, psessionEntry->peSessionId, eLIM_HEART_BEAT_TIMER));
if (limActivateHearBeatTimer(pMac) != TX_SUCCESS)
limLog(pMac, LOGP, FL("could not activate Heartbeat timer"));
psessionEntry->bssIdx = (tANI_U8) pAddBssParams->bssIdx;
psessionEntry->limSystemRole = eLIM_STA_IN_IBSS_ROLE;
psessionEntry->statypeForBss = STA_ENTRY_SELF;
schEdcaProfileUpdate(pMac, psessionEntry);
//TBD-RAJESH limInitPreauthList should re removed for IBSS also ?????
//limInitPreAuthList(pMac);
limInitPeerIdxpool(pMac,psessionEntry);
// Create timers used by LIM
#ifdef FIXME_GEN6 //following code may not be required, as limCreateTimers is now invoked from limInitialize (peStart)
if (!pMac->lim.gLimTimersCreated)
limCreateTimers(pMac);
#endif
/* Update the lim global gLimTriggerBackgroundScanDuringQuietBss */
if( eSIR_SUCCESS != wlan_cfgGetInt( pMac, WNI_CFG_TRIG_STA_BK_SCAN, &val ))
limLog( pMac, LOGP, FL("Failed to get WNI_CFG_TRIG_STA_BK_SCAN!"));
pMac->lim.gLimTriggerBackgroundScanDuringQuietBss = (val) ? 1 : 0;
// Apply previously set configuration at HW
limApplyConfiguration(pMac,psessionEntry);
psessionEntry->staId = pAddBssParams->staContext.staIdx;
mlmStartCnf.resultCode = eSIR_SME_SUCCESS;
//If ADD BSS was issued as part of IBSS coalescing, don't send the message to SME, as that is internal to LIM
if(true == pMac->lim.gLimIbssCoalescingHappened)
{
limIbssAddBssRspWhenCoalescing(pMac, limMsgQ->bodyptr, psessionEntry);
goto end;
}
}
else
{
limLog( pMac, LOGE, FL( "WDA_ADD_BSS_REQ failed with status %d" ),
pAddBssParams->status );
mlmStartCnf.resultCode = eSIR_SME_HAL_SEND_MESSAGE_FAIL;
}
//Send this message to SME, when ADD_BSS is initiated by SME
//If ADD_BSS is done as part of coalescing, this won't happen.
/* Update PE session Id*/
mlmStartCnf.sessionId =psessionEntry->peSessionId;
limPostSmeMessage( pMac, LIM_MLM_START_CNF, (tANI_U32 *) &mlmStartCnf );
end:
if( 0 != limMsgQ->bodyptr )
{
palFreeMemory( pMac->hHdd, (void *) pAddBssParams );
limMsgQ->bodyptr = NULL;
}
}
static void
limProcessStaMlmAddBssRspPreAssoc( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ, tpPESession psessionEntry )
{
tpAddBssParams pAddBssParams = (tpAddBssParams) limMsgQ->bodyptr;
tAniAuthType cfgAuthType, authMode;
tLimMlmAuthReq *pMlmAuthReq;
tpDphHashNode pStaDs = NULL;
if (NULL == pAddBssParams)
{
limLog( pMac, LOGE, FL( "Invalid body pointer in message"));
goto joinFailure;
}
if( eHAL_STATUS_SUCCESS == pAddBssParams->status )
{
if ((pStaDs = dphAddHashEntry(pMac, pAddBssParams->staContext.staMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable)) == NULL)
{
// Could not add hash table entry
PELOGE(limLog(pMac, LOGE, FL("could not add hash entry at DPH for "));)
limPrintMacAddr(pMac, pAddBssParams->staContext.staMac, LOGE);
goto joinFailure;
}
psessionEntry->bssIdx = (tANI_U8) pAddBssParams->bssIdx;
//Success, handle below
pStaDs->bssId = pAddBssParams->bssIdx;
//STA Index(genr by HAL) for the BSS entry is stored here
pStaDs->staIndex = pAddBssParams->staContext.staIdx;
// Trigger Authentication with AP
if (wlan_cfgGetInt(pMac, WNI_CFG_AUTHENTICATION_TYPE,
(tANI_U32 *) &cfgAuthType) != eSIR_SUCCESS)
{
/**
* Could not get AuthType from CFG.
* Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve AuthType"));
}
if (cfgAuthType == eSIR_AUTO_SWITCH)
authMode = eSIR_OPEN_SYSTEM; // Try Open Authentication first
else
authMode = cfgAuthType;
// Trigger MAC based Authentication
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd, (void **)&pMlmAuthReq, sizeof(tLimMlmAuthReq)))
{
// Log error
limLog(pMac, LOGP,
FL("call to palAllocateMemory failed for mlmAuthReq"));
return;
}
#if 0
val = sizeof(tSirMacAddr);
if (wlan_cfgGetStr(pMac, WNI_CFG_BSSID,
pMlmAuthReq->peerMacAddr,
&val) != eSIR_SUCCESS)
{
/// Could not get BSSID from CFG. Log error.
limLog(pMac, LOGP, FL("could not retrieve BSSID"));
}
#endif //TO SUPPORT BT-AMP
sirCopyMacAddr(pMlmAuthReq->peerMacAddr,psessionEntry->bssId);
pMlmAuthReq->authType = authMode;
if (wlan_cfgGetInt(pMac, WNI_CFG_AUTHENTICATE_FAILURE_TIMEOUT,
(tANI_U32 *) &pMlmAuthReq->authFailureTimeout)
!= eSIR_SUCCESS)
{
/**
* Could not get AuthFailureTimeout
* value from CFG. Log error.
*/
limLog(pMac, LOGP,
FL("could not retrieve AuthFailureTimeout value"));
}
// SUNIT_FIX_ME: Set BOTH? Assume not. Please verify here and below.
//pMac->lim.gLimMlmState = eLIM_MLM_JOINED_STATE;
psessionEntry->limMlmState = eLIM_MLM_JOINED_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, eLIM_MLM_JOINED_STATE));
pMlmAuthReq->sessionId = psessionEntry->peSessionId;
psessionEntry->limPrevSmeState = psessionEntry->limSmeState;
psessionEntry->limSmeState = eLIM_SME_WT_AUTH_STATE;
// remember staId in case of assoc timeout/failure handling
psessionEntry->staId = pAddBssParams->staContext.staIdx;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
limPostMlmMessage(pMac,
LIM_MLM_AUTH_REQ,
(tANI_U32 *) pMlmAuthReq);
return;
}
joinFailure:
{
psessionEntry->limSmeState = eLIM_SME_JOIN_FAILURE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_SME_STATE, psessionEntry->peSessionId, psessionEntry->limSmeState));
/// Send Join response to Host
limHandleSmeJoinResult(pMac, eSIR_SME_REFUSED, eSIR_MAC_UNSPEC_FAILURE_STATUS, psessionEntry);
}
}
#ifdef WLAN_FEATURE_VOWIFI_11R
/*------------------------------------------------------------------------------------------
*
* Function to handle callback after setting link state to post assoc.
*
*
*------------------------------------------------------------------------------------------
*/
void limSetLinkStateForPostAssocCallback(tpAniSirGlobal pMac, void *msgParam )
{
tLimMlmReassocCnf mlmReassocCnf; // keep sme
tSetLinkCbackParams * pCbackParams = (tSetLinkCbackParams *)msgParam;
tpPESession psessionEntry = NULL;
tpAddBssParams pAddBssParams = NULL;
tpDphHashNode pStaDs = NULL;
tpAddStaParams pAddStaParams = NULL;
tLimMlmReassocReq * pMlmReassocReq = NULL;
tANI_U32 listenInterval = WNI_CFG_LISTEN_INTERVAL_STADEF;
tANI_U32 selfStaDot11Mode = 0;
/* Sanity Checks */
if (pCbackParams == NULL)
{
PELOGE(limLog(pMac, LOGE, FL("Invalid parameters"));)
goto end;
}
pAddBssParams = (tpAddBssParams)(pCbackParams->cbackDataPtr);
if (pAddBssParams == NULL)
{
PELOGE(limLog(pMac, LOGE, FL("Invalid parameters"));)
goto end;
}
if((psessionEntry = peFindSessionBySessionId(pMac,pAddBssParams->sessionId))== NULL)
{
limLog( pMac, LOGE, FL( "Session Does not exist for given sessionId" ));
goto end;
}
pMlmReassocReq = (tLimMlmReassocReq *)(psessionEntry->pLimMlmReassocReq);
limPrintMacAddr(pMac, pAddBssParams->bssId, LOG1);
if ((pStaDs = dphAddHashEntry(pMac, pAddBssParams->bssId, DPH_STA_HASH_INDEX_PEER,
&psessionEntry->dph.dphHashTable)) == NULL)
{
// Could not add hash table entry
PELOGE(limLog(pMac, LOGE, FL("could not add hash entry at DPH for "));)
limPrintMacAddr(pMac, pAddBssParams->staContext.staMac, LOGE);
goto end;
}
#ifdef DEBUG_ROAM_DELAY
vos_record_roam_event(e_LIM_ADD_BS_RSP, NULL, 0);
#endif
// Prepare and send Reassociation request frame
// start reassoc timer.
pMac->lim.limTimers.gLimReassocFailureTimer.sessionId = psessionEntry->peSessionId;
/// Start reassociation failure timer
MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, psessionEntry->peSessionId, eLIM_REASSOC_FAIL_TIMER));
if (tx_timer_activate(&pMac->lim.limTimers.gLimReassocFailureTimer)
!= TX_SUCCESS)
{
/// Could not start reassoc failure timer.
// Log error
limLog(pMac, LOGP,
FL("could not start Reassociation failure timer"));
// Return Reassoc confirm with
// Resources Unavailable
mlmReassocCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE;
mlmReassocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS;
goto end;
}
// remember staId
psessionEntry->staId = pAddBssParams->staContext.staIdx;
#if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_CCX) || defined(FEATURE_WLAN_LFR)
pMac->lim.pSessionEntry = psessionEntry;
if(NULL == pMac->lim.pSessionEntry->pLimMlmReassocRetryReq)
{
/* Take a copy of reassoc request for retrying */
if ( !HAL_STATUS_SUCCESS(palAllocateMemory(pMac->hHdd, (void **)&pMac->lim.pSessionEntry->pLimMlmReassocRetryReq, sizeof(tLimMlmReassocReq))) ) goto end;
palZeroMemory(pMac->hHdd, pMac->lim.pSessionEntry->pLimMlmReassocRetryReq, sizeof(tLimMlmReassocReq));
palCopyMemory( pMac->hHdd,pMac->lim.pSessionEntry->pLimMlmReassocRetryReq, psessionEntry->pLimMlmReassocReq, sizeof(tLimMlmReassocReq));
}
pMac->lim.reAssocRetryAttempt = 0;
#endif
limSendReassocReqWithFTIEsMgmtFrame(pMac, psessionEntry->pLimMlmReassocReq, psessionEntry);
#ifdef DEBUG_ROAM_DELAY
vos_record_roam_event(e_LIM_SEND_REASSOC_REQ, NULL, 0);
#endif
psessionEntry->limPrevMlmState = psessionEntry->limMlmState;
psessionEntry->limMlmState = eLIM_MLM_WT_FT_REASSOC_RSP_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, eLIM_MLM_WT_FT_REASSOC_RSP_STATE));
PELOGE(limLog(pMac, LOG1, FL("Set the mlm state to %d session=%d"),
psessionEntry->limMlmState, psessionEntry->peSessionId);)
psessionEntry->bssIdx = (tANI_U8) pAddBssParams->bssIdx;
//Success, handle below
pStaDs->bssId = pAddBssParams->bssIdx;
//STA Index(genr by HAL) for the BSS entry is stored here
pStaDs->staIndex = pAddBssParams->staContext.staIdx;
pStaDs->ucUcastSig = pAddBssParams->staContext.ucUcastSig;
pStaDs->ucBcastSig = pAddBssParams->staContext.ucBcastSig;
#if defined WLAN_FEATURE_VOWIFI
rrmCacheMgmtTxPower( pMac, pAddBssParams->txMgmtPower, psessionEntry );
#endif
if( eHAL_STATUS_SUCCESS !=
palAllocateMemory( pMac->hHdd, (void **) &pAddStaParams, sizeof( tAddStaParams )))
{
limLog( pMac, LOGP, FL( "Unable to PAL allocate memory during ADD_STA" ));
goto end;
}
palZeroMemory( pMac->hHdd, (tANI_U8 *) pAddStaParams, sizeof(tAddStaParams));
/// Add STA context at MAC HW (BMU, RHP & TFP)
palCopyMemory( pMac->hHdd, (tANI_U8 *) pAddStaParams->staMac,
(tANI_U8 *) psessionEntry->selfMacAddr, sizeof(tSirMacAddr));
palCopyMemory( pMac->hHdd, (tANI_U8 *) pAddStaParams->bssId,
psessionEntry->bssId, sizeof(tSirMacAddr));
// Update this when we get reassoc rsp , with success.
// pAddStaParams->assocId = psessionEntry->limAID;
pAddStaParams->staType = STA_ENTRY_SELF;
pAddStaParams->status = eHAL_STATUS_SUCCESS;
pAddStaParams->respReqd = 1;
/* Update PE session ID */
pAddStaParams->sessionId = psessionEntry->peSessionId;
// This will indicate HAL to "allocate" a new STA index
pAddStaParams->staIdx = HAL_STA_INVALID_IDX;
pAddStaParams->updateSta = FALSE;
pAddStaParams->shortPreambleSupported = (tANI_U8)psessionEntry->beaconParams.fShortPreamble;
#ifdef WLAN_FEATURE_11AC
limPopulatePeerRateSet(pMac, &pAddStaParams->supportedRates, NULL, false,psessionEntry, NULL);
#else
limPopulatePeerRateSet(pMac, &pAddStaParams->supportedRates, NULL, false,psessionEntry);
#endif
if( psessionEntry->htCapability)
{
pAddStaParams->htCapable = psessionEntry->htCapability;
#ifdef WLAN_FEATURE_11AC
pAddStaParams->vhtCapable = psessionEntry->vhtCapability;
pAddStaParams->vhtTxChannelWidthSet = psessionEntry->vhtTxChannelWidthSet;
#endif
#ifdef DISABLE_GF_FOR_INTEROP
/*
* To resolve the interop problem with Broadcom AP,
* where TQ STA could not pass traffic with GF enabled,
* TQ STA will do Greenfield only with TQ AP, for
* everybody else it will be turned off.
*/
if( (psessionEntry->pLimJoinReq != NULL) && (!psessionEntry->pLimJoinReq->bssDescription.aniIndicator))
{
limLog( pMac, LOGE, FL(" Turning off Greenfield, when adding self entry"));
pAddStaParams->greenFieldCapable = WNI_CFG_GREENFIELD_CAPABILITY_DISABLE;
}
else
#endif
pAddStaParams->greenFieldCapable = limGetHTCapability( pMac, eHT_GREENFIELD, psessionEntry);
if (psessionEntry->limRFBand == SIR_BAND_2_4_GHZ)
{
pAddStaParams->txChannelWidthSet =
pMac->roam.configParam.channelBondingMode24GHz;
}
else
{
pAddStaParams->txChannelWidthSet =
pMac->roam.configParam.channelBondingMode5GHz;
}
pAddStaParams->mimoPS = limGetHTCapability( pMac, eHT_MIMO_POWER_SAVE, psessionEntry );
pAddStaParams->rifsMode = limGetHTCapability( pMac, eHT_RIFS_MODE, psessionEntry );
pAddStaParams->lsigTxopProtection = limGetHTCapability( pMac, eHT_LSIG_TXOP_PROTECTION, psessionEntry );
pAddStaParams->delBASupport = limGetHTCapability( pMac, eHT_DELAYED_BA, psessionEntry );
pAddStaParams->maxAmpduDensity = limGetHTCapability( pMac, eHT_MPDU_DENSITY, psessionEntry );
pAddStaParams->maxAmpduSize = limGetHTCapability(pMac, eHT_MAX_RX_AMPDU_FACTOR, psessionEntry);
pAddStaParams->maxAmsduSize = limGetHTCapability( pMac, eHT_MAX_AMSDU_LENGTH, psessionEntry );
pAddStaParams->fDsssCckMode40Mhz = limGetHTCapability( pMac, eHT_DSSS_CCK_MODE_40MHZ, psessionEntry);
pAddStaParams->fShortGI20Mhz = limGetHTCapability( pMac, eHT_SHORT_GI_20MHZ, psessionEntry);
pAddStaParams->fShortGI40Mhz = limGetHTCapability( pMac, eHT_SHORT_GI_40MHZ, psessionEntry);
}
if (wlan_cfgGetInt(pMac, WNI_CFG_LISTEN_INTERVAL, &listenInterval) != eSIR_SUCCESS)
limLog(pMac, LOGP, FL("Couldn't get LISTEN_INTERVAL"));
pAddStaParams->listenInterval = (tANI_U16)listenInterval;
wlan_cfgGetInt(pMac, WNI_CFG_DOT11_MODE, &selfStaDot11Mode);
pAddStaParams->supportedRates.opRateMode = limGetStaRateMode((tANI_U8)selfStaDot11Mode);
// Lets save this for when we receive the Reassoc Rsp
pMac->ft.ftPEContext.pAddStaReq = pAddStaParams;
if (pCbackParams != NULL)
{
if (pCbackParams->cbackDataPtr != NULL)
{
palFreeMemory( pMac->hHdd, (tANI_U8 *) pCbackParams->cbackDataPtr);
}
palFreeMemory( pMac->hHdd, (tANI_U8 *) pCbackParams);
}
return;
end:
// Free up buffer allocated for reassocReq
if (pMlmReassocReq != NULL)
{
palFreeMemory( pMac->hHdd, (tANI_U8 *) pMlmReassocReq);
}
if (pCbackParams != NULL)
{
if (pCbackParams->cbackDataPtr != NULL)
{
palFreeMemory( pMac->hHdd, (tANI_U8 *) pCbackParams->cbackDataPtr);
}
palFreeMemory( pMac->hHdd, (tANI_U8 *) pCbackParams);
}
mlmReassocCnf.resultCode = eSIR_SME_FT_REASSOC_FAILURE;
mlmReassocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS;
/* Update PE session Id*/
if (psessionEntry != NULL)
mlmReassocCnf.sessionId = psessionEntry->peSessionId;
else
mlmReassocCnf.sessionId = 0;
limPostSmeMessage(pMac, LIM_MLM_REASSOC_CNF, (tANI_U32 *) &mlmReassocCnf);
}
/*------------------------------------------------------------------------------------------
*
* Function to handle WDA_ADD_BSS_RSP, in FT reassoc state.
*
*
*------------------------------------------------------------------------------------------
*/
static inline void
limProcessStaMlmAddBssRspFT(tpAniSirGlobal pMac, tpSirMsgQ limMsgQ, tpPESession psessionEntry)
{
tSetLinkCbackParams * pCbackParam = NULL;
tAddBssParams * pAddBssCbackInfo = NULL;
tLimMlmReassocCnf mlmReassocCnf;
tpAddBssParams pAddBssParams = (tpAddBssParams) limMsgQ->bodyptr;
if ( eLIM_MLM_WT_ADD_BSS_RSP_FT_REASSOC_STATE != psessionEntry->limMlmState )
{
goto end;
}
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd, (void **) &pCbackParam, sizeof( tSetLinkCbackParams )))
{
PELOGE(limLog(pMac, LOGE, FL("Could not allocate memory for LinkState callback params"));)
goto end;
}
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd, (void **) &pAddBssCbackInfo, sizeof( tAddBssParams )))
{
PELOGE(limLog(pMac, LOGE, FL("Could not allocate memory for Add BSS info callback param"));)
goto end;
}
vos_mem_copy(pAddBssCbackInfo, pAddBssParams, sizeof(tAddBssParams));
pCbackParam->cbackDataPtr = (void*)pAddBssCbackInfo;
// Set the filter state to post assoc and send out re-assoc request OTA only after response is received
if (limSetLinkState(pMac, eSIR_LINK_POSTASSOC_STATE,
pAddBssParams->bssId, psessionEntry->selfMacAddr,
(tpSetLinkStateCallback)limSetLinkStateForPostAssocCallback,
(void *)pCbackParam) != eSIR_SUCCESS)
{
PELOGE(limLog(pMac, LOGE, FL("Failed to set the LinkState"));)
goto end;
}
return;
end:
if (pCbackParam != NULL)
{
if (pCbackParam->cbackDataPtr != NULL)
{
palFreeMemory( pMac->hHdd, (tANI_U8 *) pCbackParam->cbackDataPtr);
}
palFreeMemory( pMac->hHdd, (tANI_U8 *) pCbackParam);
}
mlmReassocCnf.resultCode = eSIR_SME_FT_REASSOC_FAILURE;
mlmReassocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS;
/* Update PE sessio Id*/
mlmReassocCnf.sessionId = psessionEntry->peSessionId;
limPostSmeMessage(pMac, LIM_MLM_REASSOC_CNF, (tANI_U32 *) &mlmReassocCnf);
}
#endif /* WLAN_FEATURE_VOWIFI_11R */
/**
* limProcessStaMlmAddBssRsp()
*
*FUNCTION:
* This function is called to process a WDA_ADD_BSS_RSP from HAL.
* Upon receipt of this message from HAL, MLME -
* > Validates the result of WDA_ADD_BSS_REQ
* > Now, send an ADD_STA to HAL and ADD the "local" STA itself
*
*LOGIC:
* MLME had sent WDA_ADD_BSS_REQ to HAL
* HAL responded with WDA_ADD_BSS_RSP to MLME
* MLME now sends WDA_ADD_STA_REQ to HAL
*
*ASSUMPTIONS:
* tSirMsgQ.body is allocated by MLME during limProcessMlmJoinReq
* tSirMsgQ.body will now be freed by this routine
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param tSirMsgQ The MsgQ header, which contains the response buffer
*
* @return None
*/
static void
limProcessStaMlmAddBssRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ,tpPESession psessionEntry)
{
tpAddBssParams pAddBssParams = (tpAddBssParams) limMsgQ->bodyptr;
tLimMlmAssocCnf mlmAssocCnf;
tANI_U32 mesgType = LIM_MLM_ASSOC_CNF;
tANI_U32 subType = LIM_ASSOC;
tpDphHashNode pStaDs = NULL;
tANI_U16 staIdx = HAL_STA_INVALID_IDX;
tANI_U8 updateSta = false;
mlmAssocCnf.resultCode = eSIR_SME_SUCCESS;
if(eLIM_MLM_WT_ADD_BSS_RSP_PREASSOC_STATE == psessionEntry->limMlmState)
{
//Done: 7-28-2009. JIM_FIX_ME: sessionize the following function
limProcessStaMlmAddBssRspPreAssoc(pMac, limMsgQ, psessionEntry);
goto end;
}
if(( eLIM_MLM_WT_ADD_BSS_RSP_REASSOC_STATE == psessionEntry->limMlmState ) ||
( eLIM_MLM_WT_ADD_BSS_RSP_FT_REASSOC_STATE == psessionEntry->limMlmState ))
{
mesgType = LIM_MLM_REASSOC_CNF;
subType = LIM_REASSOC;
//If Reassoc is happening for the same BSS, then use the existing StaId and indicate to HAL
//to update the existing STA entry.
//If Reassoc is happening for the new BSS, then old BSS and STA entry would have been already deleted
//before PE tries to add BSS for the new BSS, so set the updateSta to false and pass INVALID STA Index.
if (sirCompareMacAddr( psessionEntry->bssId, psessionEntry->limReAssocbssId))
{
staIdx = psessionEntry->staId;
updateSta = true;
}
}
if(pAddBssParams == 0)
goto end;
if( eHAL_STATUS_SUCCESS == pAddBssParams->status )
{
#if defined(WLAN_FEATURE_VOWIFI_11R) || defined(FEATURE_WLAN_CCX) || defined(FEATURE_WLAN_LFR)
if( eLIM_MLM_WT_ADD_BSS_RSP_FT_REASSOC_STATE == psessionEntry->limMlmState )
{
#ifdef WLAN_FEATURE_VOWIFI_11R_DEBUG
PELOGE(limLog(pMac, LOG1, FL("Mlm=%d %d"),
psessionEntry->limMlmState,
eLIM_MLM_WT_ADD_BSS_RSP_REASSOC_STATE);)
#endif
limProcessStaMlmAddBssRspFT( pMac, limMsgQ, psessionEntry);
goto end;
}
#endif /* WLAN_FEATURE_VOWIFI_11R */
// Set MLME state
psessionEntry->limMlmState = eLIM_MLM_WT_ADD_STA_RSP_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
psessionEntry->statypeForBss = STA_ENTRY_PEER; //to know the session started for self or for peer oct6th
// Now, send WDA_ADD_STA_REQ
limLog( pMac, LOGW, FL( "On STA: ADD_BSS was successful" ));
pStaDs = dphGetHashEntry(pMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable);
if (pStaDs == NULL)
{
PELOGE(limLog(pMac, LOGE, FL("could not Add Self Entry for the station"));)
mlmAssocCnf.resultCode = (tSirResultCodes) eSIR_SME_REFUSED;
}
else
{
psessionEntry->bssIdx = (tANI_U8) pAddBssParams->bssIdx;
//Success, handle below
pStaDs->bssId = pAddBssParams->bssIdx;
//STA Index(genr by HAL) for the BSS entry is stored here
pStaDs->staIndex = pAddBssParams->staContext.staIdx;
pStaDs->ucUcastSig = pAddBssParams->staContext.ucUcastSig;
pStaDs->ucBcastSig = pAddBssParams->staContext.ucBcastSig;
// Downgrade the EDCA parameters if needed
limSetActiveEdcaParams(pMac, psessionEntry->gLimEdcaParams, psessionEntry);
// Send the active EDCA parameters to HAL
if (pStaDs->aniPeer == eANI_BOOLEAN_TRUE) {
limSendEdcaParams(pMac, psessionEntry->gLimEdcaParamsActive, pStaDs->bssId, eANI_BOOLEAN_TRUE);
} else {
limSendEdcaParams(pMac, psessionEntry->gLimEdcaParamsActive, pStaDs->bssId, eANI_BOOLEAN_FALSE);
}
#if defined WLAN_FEATURE_VOWIFI
rrmCacheMgmtTxPower( pMac, pAddBssParams->txMgmtPower, psessionEntry );
#endif
if (subType == LIM_REASSOC)
limDeactivateAndChangeTimer(pMac, eLIM_KEEPALIVE_TIMER);
if (limAddStaSelf(pMac,staIdx, updateSta, psessionEntry) != eSIR_SUCCESS)
{
// Add STA context at HW
PELOGE(limLog(pMac, LOGE, FL("could not Add Self Entry for the station"));)
mlmAssocCnf.resultCode = (tSirResultCodes) eSIR_SME_REFUSED;
}
}
}
else
{
limLog( pMac, LOGP, FL( "SessionId:%d ADD_BSS failed! mlmState = %d" ),
psessionEntry->peSessionId, psessionEntry->limMlmState);
// Return Assoc confirm to SME with failure
if(eLIM_MLM_WT_ADD_BSS_RSP_FT_REASSOC_STATE == psessionEntry->limMlmState)
mlmAssocCnf.resultCode = (tSirResultCodes) eSIR_SME_FT_REASSOC_FAILURE;
else
mlmAssocCnf.resultCode = (tSirResultCodes) eSIR_SME_REFUSED;
}
if(mlmAssocCnf.resultCode != eSIR_SME_SUCCESS)
{
psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE;
//Set the RXP mode to IDLE, so it starts filtering the frames.
if(limSetLinkState(pMac, eSIR_LINK_IDLE_STATE,psessionEntry->bssId,
psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS)
PELOGE(limLog(pMac, LOGE, FL("Failed to set the LinkState\n"));)
/* Update PE session Id*/
mlmAssocCnf.sessionId = psessionEntry->peSessionId;
limPostSmeMessage( pMac, mesgType, (tANI_U32 *) &mlmAssocCnf );
}
end:
if( 0 != limMsgQ->bodyptr )
palFreeMemory( pMac->hHdd,(void *) pAddBssParams );
}
/**
* limProcessMlmAddBssRsp()
*
*FUNCTION:
* This function is called to process a WDA_ADD_BSS_RSP from HAL.
* Upon receipt of this message from HAL, MLME -
* > Determines the "state" in which this message was received
* > Forwards it to the appropriate callback
*
*LOGIC:
* WDA_ADD_BSS_RSP can be received by MLME while the LIM is
* in the following two states:
* 1) As AP, LIM state = eLIM_SME_WT_START_BSS_STATE
* 2) As STA, LIM state = eLIM_SME_WT_JOIN_STATE
* Based on these two states, this API will determine where to
* route the message to
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param tSirMsgQ The MsgQ header, which contains the response buffer
*
* @return None
*/
void limProcessMlmAddBssRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ )
{
tLimMlmStartCnf mlmStartCnf;
tpPESession psessionEntry;
tpAddBssParams pAddBssParams = (tpAddBssParams) (limMsgQ->bodyptr);
if(NULL == pAddBssParams )
{
limLog( pMac, LOGE, FL( "Encountered NULL Pointer" ));
return;
}
//
// TODO & FIXME_GEN4
// Need to inspect tSirMsgQ.reserved for a valid Dialog token!
//
//we need to process the deferred message since the initiating req. there might be nested request.
//in the case of nested request the new request initiated from the response will take care of resetting
//the deffered flag.
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
// Validate SME/LIM state
// Validate MLME state
if((psessionEntry = peFindSessionBySessionId(pMac,pAddBssParams->sessionId))== NULL)
{
limLog( pMac, LOGE, FL( "Session Does not exist for given sessionId" ));
if( NULL != pAddBssParams )
{
palFreeMemory( pMac->hHdd, (void *) pAddBssParams );
limMsgQ->bodyptr = NULL;
}
return;
}
/* update PE session Id*/
mlmStartCnf.sessionId = psessionEntry->peSessionId;
if( eSIR_IBSS_MODE == psessionEntry->bssType )
limProcessIbssMlmAddBssRsp( pMac, limMsgQ, psessionEntry );
else
{
if( eLIM_SME_WT_START_BSS_STATE == psessionEntry->limSmeState )
{
if( eLIM_MLM_WT_ADD_BSS_RSP_STATE != psessionEntry->limMlmState )
{
// Mesg received from HAL in Invalid state!
limLog( pMac, LOGE,
FL( "Received unexpected WDA_ADD_BSS_RSP in state %X" ),
psessionEntry->limMlmState );
mlmStartCnf.resultCode = eSIR_SME_BSS_ALREADY_STARTED_OR_JOINED;
if( 0 != limMsgQ->bodyptr )
{
palFreeMemory( pMac->hHdd, (void *) pAddBssParams );
limMsgQ->bodyptr = NULL;
}
limPostSmeMessage( pMac, LIM_MLM_START_CNF, (tANI_U32 *) &mlmStartCnf );
}
else if ((psessionEntry->bssType == eSIR_BTAMP_AP_MODE)||(psessionEntry->bssType == eSIR_BTAMP_STA_MODE))
{
limProcessBtampAddBssRsp(pMac,limMsgQ,psessionEntry);
}
else
limProcessApMlmAddBssRsp( pMac,limMsgQ);
}
else
/* Called while processing assoc response */
limProcessStaMlmAddBssRsp( pMac, limMsgQ,psessionEntry);
}
if(limIsInMCC(pMac))
{
WDA_TrafficStatsTimerActivate(TRUE);
}
}
/**
* limProcessMlmSetKeyRsp()
*
*FUNCTION:
* This function is called to process the following two
* messages from HAL:
* 1) WDA_SET_BSSKEY_RSP
* 2) WDA_SET_STAKEY_RSP
* 3) WDA_SET_STA_BCASTKEY_RSP
* Upon receipt of this message from HAL,
* MLME -
* > Determines the "state" in which this message was received
* > Forwards it to the appropriate callback
*
*LOGIC:
* WDA_SET_BSSKEY_RSP/WDA_SET_STAKEY_RSP can be
* received by MLME while in the following state:
* MLME state = eLIM_MLM_WT_SET_BSS_KEY_STATE --OR--
* MLME state = eLIM_MLM_WT_SET_STA_KEY_STATE --OR--
* MLME state = eLIM_MLM_WT_SET_STA_BCASTKEY_STATE
* Based on this state, this API will determine where to
* route the message to
*
*ASSUMPTIONS:
* ONLY the MLME state is being taken into account for now.
* This is because, it appears that the handling of the
* SETKEYS REQ is handled symmetrically on both the AP & STA
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param tSirMsgQ The MsgQ header, which contains the response buffer
*
* @return None
*/
void limProcessMlmSetStaKeyRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ )
{
tANI_U8 respReqd = 1;
tLimMlmSetKeysCnf mlmSetKeysCnf;
tANI_U8 sessionId = 0;
tpPESession psessionEntry;
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
palZeroMemory( pMac->hHdd, (void *)&mlmSetKeysCnf, sizeof( tLimMlmSetKeysCnf ));
//BTAMP
if( NULL == limMsgQ->bodyptr )
{
PELOGE(limLog(pMac, LOGE,FL("limMsgQ bodyptr is NULL"));)
return;
}
sessionId = ((tpSetStaKeyParams) limMsgQ->bodyptr)->sessionId;
if((psessionEntry = peFindSessionBySessionId(pMac, sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given sessionId"));)
palFreeMemory( pMac->hHdd, (void *) limMsgQ->bodyptr );
limMsgQ->bodyptr = NULL;
return;
}
if( eLIM_MLM_WT_SET_STA_KEY_STATE != psessionEntry->limMlmState )
{
// Mesg received from HAL in Invalid state!
limLog( pMac, LOGW, FL( "Received unexpected [Mesg Id - %d] in state %X" ), limMsgQ->type, psessionEntry->limMlmState );
// There's not much that MLME can do at this stage...
respReqd = 0;
}
else
mlmSetKeysCnf.resultCode = (tANI_U16) (((tpSetStaKeyParams) limMsgQ->bodyptr)->status);
palFreeMemory( pMac->hHdd, (void *) limMsgQ->bodyptr );
limMsgQ->bodyptr = NULL;
// Restore MLME state
psessionEntry->limMlmState = psessionEntry->limPrevMlmState;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
if( respReqd )
{
tpLimMlmSetKeysReq lpLimMlmSetKeysReq = (tpLimMlmSetKeysReq) pMac->lim.gpLimMlmSetKeysReq;
// Prepare and Send LIM_MLM_SETKEYS_CNF
if( NULL != lpLimMlmSetKeysReq )
{
palCopyMemory( pMac->hHdd, (tANI_U8 *) &mlmSetKeysCnf.peerMacAddr, (tANI_U8 *) lpLimMlmSetKeysReq->peerMacAddr, sizeof(tSirMacAddr) );
// Free the buffer cached for the global pMac->lim.gpLimMlmSetKeysReq
palFreeMemory(pMac->hHdd, (tANI_U8 *) pMac->lim.gpLimMlmSetKeysReq);
pMac->lim.gpLimMlmSetKeysReq = NULL;
}
mlmSetKeysCnf.sessionId = sessionId;
limPostSmeMessage(pMac, LIM_MLM_SETKEYS_CNF, (tANI_U32 *) &mlmSetKeysCnf);
}
}
void limProcessMlmSetBssKeyRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ )
{
tANI_U8 respReqd = 1;
tLimMlmSetKeysCnf mlmSetKeysCnf;
tANI_U16 resultCode;
tANI_U8 sessionId = 0;
tpPESession psessionEntry;
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
palZeroMemory( pMac->hHdd, (void *)&mlmSetKeysCnf, sizeof( tLimMlmSetKeysCnf ));
//BTAMP
if( NULL == limMsgQ->bodyptr )
{
PELOGE(limLog(pMac, LOGE,FL("limMsgQ bodyptr is null"));)
return;
}
sessionId = ((tpSetBssKeyParams) limMsgQ->bodyptr)->sessionId;
if((psessionEntry = peFindSessionBySessionId(pMac, sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given sessionId"));)
palFreeMemory( pMac->hHdd, (void *) limMsgQ->bodyptr );
limMsgQ->bodyptr = NULL;
return;
}
if( eLIM_MLM_WT_SET_BSS_KEY_STATE == psessionEntry->limMlmState )
resultCode = (tANI_U16) (((tpSetBssKeyParams) limMsgQ->bodyptr)->status);
else
resultCode = (tANI_U16) (((tpSetStaKeyParams) limMsgQ->bodyptr)->status); //BCAST key also uses tpSetStaKeyParams. Done this way for readabilty.
//
// TODO & FIXME_GEN4
// Need to inspect tSirMsgQ.reserved for a valid Dialog token!
//
// Validate SME/LIM state - Read the above "ASSUMPTIONS"
//if( eLIM_SME_LINK_EST_STATE == pMac->lim.gLimSmeState )
//{
// Validate MLME state
if( eLIM_MLM_WT_SET_BSS_KEY_STATE != psessionEntry->limMlmState &&
eLIM_MLM_WT_SET_STA_BCASTKEY_STATE != psessionEntry->limMlmState )
{
// Mesg received from HAL in Invalid state!
limLog( pMac, LOGW, FL( "Received unexpected [Mesg Id - %d] in state %X" ), limMsgQ->type, psessionEntry->limMlmState );
// There's not much that MLME can do at this stage...
respReqd = 0;
}
else
mlmSetKeysCnf.resultCode = resultCode;
palFreeMemory( pMac->hHdd, (void *) limMsgQ->bodyptr );
limMsgQ->bodyptr = NULL;
// Restore MLME state
psessionEntry->limMlmState = psessionEntry->limPrevMlmState;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
if( respReqd )
{
tpLimMlmSetKeysReq lpLimMlmSetKeysReq = (tpLimMlmSetKeysReq) pMac->lim.gpLimMlmSetKeysReq;
mlmSetKeysCnf.sessionId = sessionId;
// Prepare and Send LIM_MLM_SETKEYS_CNF
if( NULL != lpLimMlmSetKeysReq )
{
palCopyMemory( pMac->hHdd, (tANI_U8 *) &mlmSetKeysCnf.peerMacAddr, (tANI_U8 *) lpLimMlmSetKeysReq->peerMacAddr, sizeof(tSirMacAddr) );
// Free the buffer cached for the global pMac->lim.gpLimMlmSetKeysReq
palFreeMemory(pMac->hHdd, (tANI_U8 *) pMac->lim.gpLimMlmSetKeysReq);
pMac->lim.gpLimMlmSetKeysReq = NULL;
}
limPostSmeMessage(pMac, LIM_MLM_SETKEYS_CNF, (tANI_U32 *) &mlmSetKeysCnf);
}
}
/**
* limProcessMlmRemoveKeyRsp()
*
*FUNCTION:
*
*LOGIC:
*
*ASSUMPTIONS:
*
*NOTE:
*
* @param pMac Pointer to Global MAC structure
* @param tSirMsgQ The MsgQ header, which contains the response buffer
*
* @return None
*/
void limProcessMlmRemoveKeyRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ )
{
tANI_U8 respReqd = 1;
tLimMlmRemoveKeyCnf mlmRemoveCnf;
tANI_U16 resultCode;
tANI_U8 sessionId = 0;
tpPESession psessionEntry;
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
palZeroMemory( pMac->hHdd, (void *) &mlmRemoveCnf, sizeof( tLimMlmRemoveKeyCnf ));
if( NULL == limMsgQ->bodyptr )
{
PELOGE(limLog(pMac, LOGE,FL("limMsgQ bodyptr is NULL"));)
return;
}
if (limMsgQ->type == WDA_REMOVE_STAKEY_RSP)
sessionId = ((tpRemoveStaKeyParams) limMsgQ->bodyptr)->sessionId;
else if (limMsgQ->type == WDA_REMOVE_BSSKEY_RSP)
sessionId = ((tpRemoveBssKeyParams) limMsgQ->bodyptr)->sessionId;
if((psessionEntry = peFindSessionBySessionId(pMac, sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given sessionId"));)
return;
}
if( eLIM_MLM_WT_REMOVE_BSS_KEY_STATE == psessionEntry->limMlmState )
resultCode = (tANI_U16) (((tpRemoveBssKeyParams) limMsgQ->bodyptr)->status);
else
resultCode = (tANI_U16) (((tpRemoveStaKeyParams) limMsgQ->bodyptr)->status);
// Validate MLME state
if( eLIM_MLM_WT_REMOVE_BSS_KEY_STATE != psessionEntry->limMlmState &&
eLIM_MLM_WT_REMOVE_STA_KEY_STATE != psessionEntry->limMlmState )
{
// Mesg received from HAL in Invalid state!
limLog(pMac, LOGW,
FL("Received unexpected [Mesg Id - %d] in state %X"),
limMsgQ->type,
psessionEntry->limMlmState );
respReqd = 0;
}
else
mlmRemoveCnf.resultCode = resultCode;
//
// TODO & FIXME_GEN4
// Need to inspect tSirMsgQ.reserved for a valid Dialog token!
//
palFreeMemory( pMac->hHdd, (void *) limMsgQ->bodyptr );
limMsgQ->bodyptr = NULL;
// Restore MLME state
psessionEntry->limMlmState = psessionEntry->limPrevMlmState;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
if( respReqd )
{
tpLimMlmRemoveKeyReq lpLimMlmRemoveKeyReq = (tpLimMlmRemoveKeyReq) pMac->lim.gpLimMlmRemoveKeyReq;
mlmRemoveCnf.sessionId = sessionId;
// Prepare and Send LIM_MLM_REMOVEKEY_CNF
if( NULL != lpLimMlmRemoveKeyReq )
{
palCopyMemory( pMac->hHdd, (tANI_U8 *) &mlmRemoveCnf.peerMacAddr, (tANI_U8 *) lpLimMlmRemoveKeyReq->peerMacAddr,
sizeof( tSirMacAddr ));
// Free the buffer cached for the global pMac->lim.gpLimMlmRemoveKeyReq
palFreeMemory(pMac->hHdd, (tANI_U8 *) pMac->lim.gpLimMlmRemoveKeyReq);
pMac->lim.gpLimMlmRemoveKeyReq = NULL;
}
limPostSmeMessage( pMac, LIM_MLM_REMOVEKEY_CNF, (tANI_U32 *) &mlmRemoveCnf );
}
}
/** ---------------------------------------------------------------------
\fn limProcessInitScanRsp
\brief This function is called when LIM receives WDA_INIT_SCAN_RSP
\ message from HAL. If status code is failure, then
\ update the gLimNumOfConsecutiveBkgndScanFailure count.
\param tpAniSirGlobal pMac
\param tANI_U32 body
\return none
\ ----------------------------------------------------------------------- */
void limProcessInitScanRsp(tpAniSirGlobal pMac, void *body)
{
tpInitScanParams pInitScanParam;
eHalStatus status;
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
pInitScanParam = (tpInitScanParams) body;
status = pInitScanParam->status;
palFreeMemory( pMac->hHdd, (char *)body);
//Only abort scan if the we are scanning.
if( pMac->lim.abortScan &&
(eLIM_HAL_INIT_SCAN_WAIT_STATE == pMac->lim.gLimHalScanState) )
{
limLog( pMac, LOGW, FL(" abort scan") );
pMac->lim.abortScan = 0;
limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER);
limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER);
//Set the resume channel to Any valid channel (invalid).
//This will instruct HAL to set it to any previous valid channel.
peSetResumeChannel(pMac, 0, 0);
if (status != eHAL_STATUS_SUCCESS)
{
PELOGW(limLog(pMac, LOGW, FL("InitScnRsp failed status=%d"),status);)
pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE;
pMac->lim.gLimNumOfConsecutiveBkgndScanFailure += 1;
limCompleteMlmScan(pMac, eSIR_SME_HAL_SCAN_INIT_FAILED);
return;
}
else
{
limSendHalFinishScanReq(pMac, eLIM_HAL_FINISH_SCAN_WAIT_STATE);
}
}
switch(pMac->lim.gLimHalScanState)
{
case eLIM_HAL_INIT_SCAN_WAIT_STATE:
if (status != (tANI_U32) eHAL_STATUS_SUCCESS)
{
PELOGW(limLog(pMac, LOGW, FL("InitScanRsp with failed status= %d"), status);)
pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE;
pMac->lim.gLimNumOfConsecutiveBkgndScanFailure += 1;
/*
* On Windows eSIR_SME_HAL_SCAN_INIT_FAILED message to CSR may trigger
* another Scan request in the same context (happens when 11d is enabled
* and first scan request with 11d channels fails for whatever reason, then CSR issues next init
* scan in the same context but with bigger channel list), so the state needs to be
* changed before this response message is sent.
*/
limCompleteMlmScan(pMac, eSIR_SME_HAL_SCAN_INIT_FAILED);
return;
}
else if (status == eHAL_STATUS_SUCCESS)
{
/* since we have successfully triggered a background scan,
* reset the "consecutive bkgnd scan failure" count to 0
*/
pMac->lim.gLimNumOfConsecutiveBkgndScanFailure = 0;
pMac->lim.gLimNumOfBackgroundScanSuccess += 1;
}
limContinueChannelScan(pMac);
break;
//WLAN_SUSPEND_LINK Related
case eLIM_HAL_SUSPEND_LINK_WAIT_STATE:
if( pMac->lim.gpLimSuspendCallback )
{
if( eHAL_STATUS_SUCCESS == status )
{
pMac->lim.gLimHalScanState = eLIM_HAL_SUSPEND_LINK_STATE;
}
else
{
pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE;
pMac->lim.gLimSystemInScanLearnMode = 0;
}
pMac->lim.gpLimSuspendCallback( pMac, status, pMac->lim.gpLimSuspendData );
pMac->lim.gpLimSuspendCallback = NULL;
pMac->lim.gpLimSuspendData = NULL;
}
else
{
limLog( pMac, LOGP, "No suspend link callback set but station is in suspend state");
return;
}
break;
//end WLAN_SUSPEND_LINK Related
default:
limLog(pMac, LOGW, FL("limProcessInitScanRsp: Rcvd InitScanRsp not in WAIT State, state %d"),
pMac->lim.gLimHalScanState);
break;
}
return;
}
/**
* limProcessSwitchChannelReAssocReq()
*
*FUNCTION:
* This function is called to send the reassoc req mgmt frame after the
* switchChannelRsp message is received from HAL.
*
*LOGIC:
*
*ASSUMPTIONS:
* NA
*
*NOTE:
* NA
*
* @param pMac - Pointer to Global MAC structure.
* @param psessionEntry - session related information.
* @param status - channel switch success/failure.
*
* @return None
*/
static void limProcessSwitchChannelReAssocReq(tpAniSirGlobal pMac, tpPESession psessionEntry, eHalStatus status)
{
tLimMlmReassocCnf mlmReassocCnf;
tLimMlmReassocReq *pMlmReassocReq;
pMlmReassocReq = (tLimMlmReassocReq *)(psessionEntry->pLimMlmReassocReq);
if(pMlmReassocReq == NULL)
{
limLog(pMac, LOGP, FL("pLimMlmReassocReq does not exist for given switchChanSession"));
mlmReassocCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE;
goto end;
}
if(status != eHAL_STATUS_SUCCESS)
{
PELOGE(limLog(pMac, LOGE, FL("Change channel failed!!"));)
mlmReassocCnf.resultCode = eSIR_SME_CHANNEL_SWITCH_FAIL;
goto end;
}
/// Start reassociation failure timer
MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, psessionEntry->peSessionId, eLIM_REASSOC_FAIL_TIMER));
if (tx_timer_activate(&pMac->lim.limTimers.gLimReassocFailureTimer)
!= TX_SUCCESS)
{
/// Could not start reassoc failure timer.
// Log error
limLog(pMac, LOGP,
FL("could not start Reassociation failure timer"));
// Return Reassoc confirm with
// Resources Unavailable
mlmReassocCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE;
goto end;
}
/// Prepare and send Reassociation request frame
limSendReassocReqMgmtFrame(pMac, pMlmReassocReq, psessionEntry);
return;
end:
// Free up buffer allocated for reassocReq
if(pMlmReassocReq != NULL)
{
/* Update PE session Id*/
mlmReassocCnf.sessionId = pMlmReassocReq->sessionId;
palFreeMemory( pMac->hHdd, (tANI_U8 *) pMlmReassocReq);
psessionEntry->pLimMlmReassocReq = NULL;
}
else
{
mlmReassocCnf.sessionId = 0;
}
mlmReassocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS;
/* Update PE sessio Id*/
mlmReassocCnf.sessionId = psessionEntry->peSessionId;
limPostSmeMessage(pMac, LIM_MLM_REASSOC_CNF, (tANI_U32 *) &mlmReassocCnf);
}
/**
* limProcessSwitchChannelJoinReq()
*
*FUNCTION:
* This function is called to send the probe req mgmt frame after the
* switchChannelRsp message is received from HAL.
*
*LOGIC:
*
*ASSUMPTIONS:
* NA
*
*NOTE:
* NA
*
* @param pMac - Pointer to Global MAC structure.
* @param psessionEntry - session related information.
* @param status - channel switch success/failure.
*
* @return None
*/
static void limProcessSwitchChannelJoinReq(tpAniSirGlobal pMac, tpPESession psessionEntry, eHalStatus status)
{
tANI_U32 val;
tSirMacSSid ssId;
tLimMlmJoinCnf mlmJoinCnf;
if(status != eHAL_STATUS_SUCCESS)
{
PELOGE(limLog(pMac, LOGE, FL("Change channel failed!!"));)
goto error;
}
if ( (NULL == psessionEntry ) || (NULL == psessionEntry->pLimMlmJoinReq) )
{
PELOGE(limLog(pMac, LOGE, FL("invalid pointer!!"));)
goto error;
}
/* eSIR_BTAMP_AP_MODE stroed as bss type in session Table when join req is received, is to be veified */
if(psessionEntry->bssType == eSIR_BTAMP_AP_MODE)
{
if (limSetLinkState(pMac, eSIR_LINK_BTAMP_PREASSOC_STATE, psessionEntry->bssId,
psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS )
goto error;
}
/* Update the lim global gLimTriggerBackgroundScanDuringQuietBss */
if(wlan_cfgGetInt(pMac, WNI_CFG_TRIG_STA_BK_SCAN, &val) != eSIR_SUCCESS)
limLog(pMac, LOGP, FL("failed to get WNI_CFG_TRIG_STA_BK_SCAN cfg value!"));
pMac->lim.gLimTriggerBackgroundScanDuringQuietBss = (val) ? 1 : 0;
// Apply previously set configuration at HW
limApplyConfiguration(pMac, psessionEntry);
/// Wait for Beacon to announce join success
palCopyMemory( pMac->hHdd, ssId.ssId,
psessionEntry->ssId.ssId,
psessionEntry->ssId.length);
ssId.length = psessionEntry->ssId.length;
limDeactivateAndChangeTimer(pMac, eLIM_PERIODIC_JOIN_PROBE_REQ_TIMER);
//assign appropriate sessionId to the timer object
pMac->lim.limTimers.gLimPeriodicJoinProbeReqTimer.sessionId = psessionEntry->peSessionId;
// include additional IE if there is
limSendProbeReqMgmtFrame( pMac, &ssId,
psessionEntry->pLimMlmJoinReq->bssDescription.bssId, psessionEntry->currentOperChannel/*chanNum*/,
psessionEntry->selfMacAddr, psessionEntry->dot11mode,
psessionEntry->pLimJoinReq->addIEScan.length, psessionEntry->pLimJoinReq->addIEScan.addIEdata);
// Sending mgmt frame is a blocking call activate Join failure timer now
MTRACE(macTrace(pMac, TRACE_CODE_TIMER_ACTIVATE, psessionEntry->peSessionId, eLIM_JOIN_FAIL_TIMER));
if (tx_timer_activate(&pMac->lim.limTimers.gLimJoinFailureTimer) != TX_SUCCESS)
{
limLog(pMac, LOGP, FL("could not activate Join failure timer"));
psessionEntry->limMlmState = psessionEntry->limPrevMlmState;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, pMac->lim.gLimMlmState));
//memory is freed up below.
psessionEntry->pLimMlmJoinReq = NULL;
goto error;
}
if( psessionEntry->pePersona == VOS_P2P_CLIENT_MODE )
{
// Activate Join Periodic Probe Req timer
if (tx_timer_activate(&pMac->lim.limTimers.gLimPeriodicJoinProbeReqTimer) != TX_SUCCESS)
{
limLog(pMac, LOGP, FL("could not activate Periodic Join req failure timer"));
goto error;
}
}
return;
error:
if(NULL != psessionEntry)
{
palFreeMemory( pMac->hHdd, (tANI_U8 *) (psessionEntry->pLimMlmJoinReq));
psessionEntry->pLimMlmJoinReq = NULL;
mlmJoinCnf.sessionId = psessionEntry->peSessionId;
}
else
{
mlmJoinCnf.sessionId = 0;
}
mlmJoinCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE;
mlmJoinCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS;
limPostSmeMessage(pMac, LIM_MLM_JOIN_CNF, (tANI_U32 *) &mlmJoinCnf);
}
/**
* limProcessSwitchChannelRsp()
*
*FUNCTION:
* This function is called to process switchChannelRsp message from HAL.
*
*LOGIC:
*
*ASSUMPTIONS:
* NA
*
*NOTE:
* NA
*
* @param pMac - Pointer to Global MAC structure
* @param body - message body.
*
* @return None
*/
void limProcessSwitchChannelRsp(tpAniSirGlobal pMac, void *body)
{
tpSwitchChannelParams pChnlParams = NULL;
eHalStatus status;
tANI_U16 channelChangeReasonCode;
tANI_U8 peSessionId;
tpPESession psessionEntry;
//we need to process the deferred message since the initiating req. there might be nested request.
//in the case of nested request the new request initiated from the response will take care of resetting
//the deffered flag.
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
pChnlParams = (tpSwitchChannelParams) body;
status = pChnlParams->status;
peSessionId = pChnlParams->peSessionId;
if((psessionEntry = peFindSessionBySessionId(pMac, peSessionId))== NULL)
{
palFreeMemory( pMac->hHdd, (tANI_U8 *)body);
limLog(pMac, LOGP, FL("session does not exist for given sessionId"));
return;
}
#if defined WLAN_FEATURE_VOWIFI
//HAL fills in the tx power used for mgmt frames in this field.
//Store this value to use in TPC report IE.
rrmCacheMgmtTxPower( pMac, pChnlParams->txMgmtPower, psessionEntry );
#endif
palFreeMemory( pMac->hHdd, (tANI_U8 *)body);
channelChangeReasonCode = psessionEntry->channelChangeReasonCode;
// initialize it back to invalid id
psessionEntry->channelChangeReasonCode = 0xBAD;
switch(channelChangeReasonCode)
{
case LIM_SWITCH_CHANNEL_REASSOC:
limProcessSwitchChannelReAssocReq(pMac, psessionEntry, status);
break;
case LIM_SWITCH_CHANNEL_JOIN:
limProcessSwitchChannelJoinReq(pMac, psessionEntry, status);
break;
case LIM_SWITCH_CHANNEL_OPERATION:
/*
* The above code should also use the callback.
* mechanism below, there is scope for cleanup here.
* THat way all this response handler does is call the call back
* We can get rid of the reason code here.
*/
if (pMac->lim.gpchangeChannelCallback)
{
PELOG1(limLog( pMac, LOG1, "Channel changed hence invoke registered call back");)
pMac->lim.gpchangeChannelCallback(pMac, status, pMac->lim.gpchangeChannelData, psessionEntry);
}
break;
default:
break;
}
}
/**
* limProcessStartScanRsp()
*
*FUNCTION:
* This function is called to process startScanRsp message from HAL. If scan/learn was successful
* then it will start scan/learn on the next channel.
*
*LOGIC:
*
*ASSUMPTIONS:
* NA
*
*NOTE:
* NA
*
* @param pMac - Pointer to Global MAC structure
* @param body - message body.
*
* @return None
*/
void limProcessStartScanRsp(tpAniSirGlobal pMac, void *body)
{
tpStartScanParams pStartScanParam;
eHalStatus status;
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
pStartScanParam = (tpStartScanParams) body;
status = pStartScanParam->status;
#if defined WLAN_FEATURE_VOWIFI
//HAL fills in the tx power used for mgmt frames in this field.
//Store this value to use in TPC report IE.
rrmCacheMgmtTxPower( pMac, pStartScanParam->txMgmtPower, NULL );
//Store start TSF of scan start. This will be stored in BSS params.
rrmUpdateStartTSF( pMac, pStartScanParam->startTSF );
#endif
palFreeMemory( pMac->hHdd, (tANI_U8 *)body);
body = NULL;
if( pMac->lim.abortScan )
{
limLog( pMac, LOGW, FL(" finish scan") );
pMac->lim.abortScan = 0;
limDeactivateAndChangeTimer(pMac, eLIM_MIN_CHANNEL_TIMER);
limDeactivateAndChangeTimer(pMac, eLIM_MAX_CHANNEL_TIMER);
//Set the resume channel to Any valid channel (invalid).
//This will instruct HAL to set it to any previous valid channel.
peSetResumeChannel(pMac, 0, 0);
limSendHalFinishScanReq(pMac, eLIM_HAL_FINISH_SCAN_WAIT_STATE);
}
switch(pMac->lim.gLimHalScanState)
{
case eLIM_HAL_START_SCAN_WAIT_STATE:
if (status != (tANI_U32) eHAL_STATUS_SUCCESS)
{
PELOGW(limLog(pMac, LOGW, FL("StartScanRsp with failed status= %d"), status);)
//
// FIXME - With this, LIM will try and recover state, but
// eWNI_SME_SCAN_CNF maybe reporting an incorrect
// status back to the SME
//
//Set the resume channel to Any valid channel (invalid).
//This will instruct HAL to set it to any previous valid channel.
peSetResumeChannel(pMac, 0, 0);
limSendHalFinishScanReq( pMac, eLIM_HAL_FINISH_SCAN_WAIT_STATE );
//limCompleteMlmScan(pMac, eSIR_SME_HAL_SCAN_INIT_FAILED);
}
else
{
pMac->lim.gLimHalScanState = eLIM_HAL_SCANNING_STATE;
limContinuePostChannelScan(pMac);
}
break;
default:
limLog(pMac, LOGW, FL("Rcvd StartScanRsp not in WAIT State, state %d"),
pMac->lim.gLimHalScanState);
break;
}
return;
}
void limProcessEndScanRsp(tpAniSirGlobal pMac, void *body)
{
tpEndScanParams pEndScanParam;
eHalStatus status;
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
pEndScanParam = (tpEndScanParams) body;
status = pEndScanParam->status;
palFreeMemory( pMac->hHdd, (char *)body);
body = NULL;
switch(pMac->lim.gLimHalScanState)
{
case eLIM_HAL_END_SCAN_WAIT_STATE:
if (status != (tANI_U32) eHAL_STATUS_SUCCESS)
{
PELOGW(limLog(pMac, LOGW, FL("EndScanRsp with failed status= %d"), status);)
pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE;
limCompleteMlmScan(pMac, eSIR_SME_HAL_SCAN_INIT_FAILED);
}
else
{
pMac->lim.gLimCurrentScanChannelId++;
limContinueChannelScan(pMac);
}
break;
default:
limLog(pMac, LOGW, FL("Rcvd endScanRsp not in WAIT State, state %d"),
pMac->lim.gLimHalScanState);
break;
}
return;
}
/**
* limStopTxAndSwitch()
*
*FUNCTION:
* Start channel switch on all sessions that is in channel switch state.
*
* @param pMac - pointer to global adapter context
*
* @return None
*
*/
static void
limStopTxAndSwitch (tpAniSirGlobal pMac)
{
tANI_U8 i;
for(i =0; i < pMac->lim.maxBssId; i++)
{
if(pMac->lim.gpSession[i].valid &&
pMac->lim.gpSession[i].gLimSpecMgmt.dot11hChanSwState == eLIM_11H_CHANSW_RUNNING)
{
limStopTxAndSwitchChannel(pMac, i);
}
}
return;
}
/**
* limStartQuietOnSession()
*
*FUNCTION:
* This function is called to start quiet timer after finish scan if there is
* qeuieting on any session.
*
*LOGIC:
*
*ASSUMPTIONS:
* NA
*
*NOTE:
* NA
*
* @param pMac - Pointer to Global MAC structure
*
* @return None
*/
static void
limStartQuietOnSession (tpAniSirGlobal pMac)
{
tANI_U8 i;
for(i =0; i < pMac->lim.maxBssId; i++)
{
if(pMac->lim.gpSession[i].valid &&
pMac->lim.gpSession[i].gLimSpecMgmt.quietState == eLIM_QUIET_BEGIN)
{
limStartQuietTimer(pMac, i);
}
}
return;
}
void limProcessFinishScanRsp(tpAniSirGlobal pMac, void *body)
{
tpFinishScanParams pFinishScanParam;
eHalStatus status;
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
pFinishScanParam = (tpFinishScanParams) body;
status = pFinishScanParam->status;
palFreeMemory( pMac->hHdd, (char *)body);
body = NULL;
switch(pMac->lim.gLimHalScanState)
{
case eLIM_HAL_FINISH_SCAN_WAIT_STATE:
pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE;
limCompleteMlmScan(pMac, eSIR_SME_SUCCESS);
if (limIsChanSwitchRunning(pMac))
{
/** Right time to stop tx and start the timer for channel switch */
/* Sending Session ID 0, may not be correct, since SCAN is global there should not
* be any associated session id
*/
limStopTxAndSwitch(pMac);
}
else if (limIsQuietBegin(pMac))
{
/** Start the quieting */
/* Sending Session ID 0, may not be correct, since SCAN is global there should not
* be any associated session id
*/
limStartQuietOnSession(pMac);
}
if (status != (tANI_U32) eHAL_STATUS_SUCCESS)
{
PELOGW(limLog(pMac, LOGW, FL("EndScanRsp with failed status= %d"), status);)
}
break;
//WLAN_SUSPEND_LINK Related
case eLIM_HAL_RESUME_LINK_WAIT_STATE:
if( pMac->lim.gpLimResumeCallback )
{
pMac->lim.gLimHalScanState = eLIM_HAL_IDLE_SCAN_STATE;
pMac->lim.gpLimResumeCallback( pMac, status, pMac->lim.gpLimResumeData );
pMac->lim.gpLimResumeCallback = NULL;
pMac->lim.gpLimResumeData = NULL;
pMac->lim.gLimSystemInScanLearnMode = 0;
}
else
{
limLog( pMac, LOGP, "No Resume link callback set but station is in suspend state");
return;
}
break;
//end WLAN_SUSPEND_LINK Related
default:
limLog(pMac, LOGW, FL("Rcvd FinishScanRsp not in WAIT State, state %d"),
pMac->lim.gLimHalScanState);
break;
}
return;
}
/**
* @function : limProcessMlmHalAddBARsp
*
* @brief: Process WDA_ADDBA_RSP coming from HAL
*
*
* @param pMac The global tpAniSirGlobal object
*
* @param tSirMsgQ The MsgQ header containing the response buffer
*
* @return none
*/
void limProcessMlmHalAddBARsp( tpAniSirGlobal pMac,
tpSirMsgQ limMsgQ )
{
// Send LIM_MLM_ADDBA_CNF to LIM
tpLimMlmAddBACnf pMlmAddBACnf;
tpPESession psessionEntry;
tpAddBAParams pAddBAParams = (tpAddBAParams) limMsgQ->bodyptr;
#ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT
limDiagEventReport(pMac, WLAN_PE_DIAG_HAL_ADDBA_RSP_EVENT, psessionEntry, 0, 0);
#endif //FEATURE_WLAN_DIAG_SUPPORT
//now LIM can process any defer message.
SET_LIM_PROCESS_DEFD_MESGS(pMac, true);
if (pAddBAParams == NULL) {
PELOGE(limLog(pMac, LOGE,FL("NULL ADD BA Response from HAL"));)
return;
}
if((psessionEntry = peFindSessionBySessionId(pMac, pAddBAParams->sessionId))==NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given sessionID: %d"),pAddBAParams->sessionId );)
palFreeMemory(pMac->hHdd, (void*)limMsgQ->bodyptr);
limMsgQ->bodyptr = NULL;
return;
}
#ifdef FEATURE_WLAN_DIAG_SUPPORT_LIM //FEATURE_WLAN_DIAG_SUPPORT
limDiagEventReport(pMac, WLAN_PE_DIAG_HAL_ADDBA_RSP_EVENT, psessionEntry, 0, 0);
#endif //FEATURE_WLAN_DIAG_SUPPORT
// Allocate for LIM_MLM_ADDBA_CNF
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd,
(void **) &pMlmAddBACnf, sizeof( tLimMlmAddBACnf ))) {
limLog( pMac, LOGP, FL(" palAllocateMemory failed with error code %d"));
palFreeMemory(pMac->hHdd, (void*)limMsgQ->bodyptr);
limMsgQ->bodyptr = NULL;
return;
}
palZeroMemory( pMac->hHdd, (void *) pMlmAddBACnf, sizeof( tLimMlmAddBACnf ));
// Copy the peer MAC
palCopyMemory( pMac->hHdd, pMlmAddBACnf->peerMacAddr, pAddBAParams->peerMacAddr,
sizeof( tSirMacAddr ));
// Copy other ADDBA Rsp parameters
pMlmAddBACnf->baDialogToken = pAddBAParams->baDialogToken;
pMlmAddBACnf->baTID = pAddBAParams->baTID;
pMlmAddBACnf->baPolicy = pAddBAParams->baPolicy;
pMlmAddBACnf->baBufferSize = pAddBAParams->baBufferSize;
pMlmAddBACnf->baTimeout = pAddBAParams->baTimeout;
pMlmAddBACnf->baDirection = pAddBAParams->baDirection;
pMlmAddBACnf->sessionId = psessionEntry->peSessionId;
if(eHAL_STATUS_SUCCESS == pAddBAParams->status)
pMlmAddBACnf->addBAResultCode = eSIR_MAC_SUCCESS_STATUS;
else
pMlmAddBACnf->addBAResultCode = eSIR_MAC_UNSPEC_FAILURE_STATUS;
palFreeMemory(pMac->hHdd, (void*)limMsgQ->bodyptr);
limMsgQ->bodyptr = NULL;
// Send ADDBA CNF to LIM
limPostSmeMessage( pMac, LIM_MLM_ADDBA_CNF, (tANI_U32 *) pMlmAddBACnf );
}
/**
* \brief Process LIM_MLM_ADDBA_CNF
*
* \sa limProcessMlmAddBACnf
*
* \param pMac The global tpAniSirGlobal object
*
* \param tSirMsgQ The MsgQ header containing the response buffer
*
* \return none
*/
void limProcessMlmAddBACnf( tpAniSirGlobal pMac,
tANI_U32 *pMsgBuf )
{
tpLimMlmAddBACnf pMlmAddBACnf;
tpDphHashNode pSta;
tANI_U16 aid;
tLimBAState curBaState;
tpPESession psessionEntry = NULL;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
pMlmAddBACnf = (tpLimMlmAddBACnf) pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac,pMlmAddBACnf->sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given BSSId"));)
palFreeMemory( pMac->hHdd, (void *) pMsgBuf );
return;
}
// First, extract the DPH entry
pSta = dphLookupHashEntry( pMac, pMlmAddBACnf->peerMacAddr, &aid, &psessionEntry->dph.dphHashTable);
if( NULL == pSta )
{
PELOGE(limLog( pMac, LOGE,
FL( "STA context not found - ignoring ADDBA CNF from HAL" ));)
palFreeMemory( pMac->hHdd, (void *) pMsgBuf );
return;
}
LIM_GET_STA_BA_STATE(pSta, pMlmAddBACnf->baTID, &curBaState);
// Need to validate SME state
if( eLIM_BA_STATE_WT_ADD_RSP != curBaState)
{
PELOGE(limLog( pMac, LOGE,
FL( "Received unexpected ADDBA CNF when STA BA state is %d" ),
curBaState );)
palFreeMemory( pMac->hHdd, (void *) pMsgBuf );
return;
}
// Restore STA BA state
LIM_SET_STA_BA_STATE(pSta, pMlmAddBACnf->baTID, eLIM_BA_STATE_IDLE);
if( eSIR_MAC_SUCCESS_STATUS == pMlmAddBACnf->addBAResultCode )
{
// Update LIM internal cache...
if( eBA_RECIPIENT == pMlmAddBACnf->baDirection )
{
pSta->tcCfg[pMlmAddBACnf->baTID].fUseBARx = 1;
pSta->tcCfg[pMlmAddBACnf->baTID].fRxCompBA = 1;
pSta->tcCfg[pMlmAddBACnf->baTID].fRxBApolicy = pMlmAddBACnf->baPolicy;
pSta->tcCfg[pMlmAddBACnf->baTID].rxBufSize = pMlmAddBACnf->baBufferSize;
pSta->tcCfg[pMlmAddBACnf->baTID].tuRxBAWaitTimeout = pMlmAddBACnf->baTimeout;
// Package LIM_MLM_ADDBA_RSP to MLME, with proper
// status code. MLME will then send an ADDBA RSP
// over the air to the peer MAC entity
if( eSIR_SUCCESS != limPostMlmAddBARsp( pMac,
pMlmAddBACnf->peerMacAddr,
pMlmAddBACnf->addBAResultCode,
pMlmAddBACnf->baDialogToken,
(tANI_U8) pMlmAddBACnf->baTID,
(tANI_U8) pMlmAddBACnf->baPolicy,
pMlmAddBACnf->baBufferSize,
pMlmAddBACnf->baTimeout,psessionEntry))
{
PELOGW(limLog( pMac, LOGW,
FL( "Failed to post LIM_MLM_ADDBA_RSP to " ));
limPrintMacAddr( pMac, pMlmAddBACnf->peerMacAddr, LOGW );)
}
}
else
{
pSta->tcCfg[pMlmAddBACnf->baTID].fUseBATx = 1;
pSta->tcCfg[pMlmAddBACnf->baTID].fTxCompBA = 1;
pSta->tcCfg[pMlmAddBACnf->baTID].fTxBApolicy = pMlmAddBACnf->baPolicy;
pSta->tcCfg[pMlmAddBACnf->baTID].txBufSize = pMlmAddBACnf->baBufferSize;
pSta->tcCfg[pMlmAddBACnf->baTID].tuTxBAWaitTimeout = pMlmAddBACnf->baTimeout;
}
}
// Free the memory allocated for LIM_MLM_ADDBA_CNF
palFreeMemory( pMac->hHdd, (void *) pMsgBuf );
pMsgBuf = NULL;
}
/**
* \brief Process LIM_MLM_DELBA_CNF
*
* \sa limProcessMlmDelBACnf
*
* \param pMac The global tpAniSirGlobal object
*
* \param tSirMsgQ The MsgQ header containing the response buffer
*
* \return none
*/
void limProcessMlmDelBACnf( tpAniSirGlobal pMac,
tANI_U32 *pMsgBuf )
{
tpLimMlmDelBACnf pMlmDelBACnf;
tpDphHashNode pSta;
tANI_U16 aid;
// tANI_U8 sessionId;
tLimBAState curBaState;
tpPESession psessionEntry;
if(pMsgBuf == NULL)
{
PELOGE(limLog(pMac, LOGE,FL("Buffer is Pointing to NULL"));)
return;
}
pMlmDelBACnf = (tpLimMlmDelBACnf) pMsgBuf;
if((psessionEntry = peFindSessionBySessionId(pMac, pMlmDelBACnf->sessionId))== NULL)
{
limLog(pMac, LOGP,FL("Session Does not exist for given sessionID"));
palFreeMemory( pMac->hHdd, (void *) pMsgBuf );
return;
}
// First, extract the DPH entry
pSta = dphLookupHashEntry( pMac, pMlmDelBACnf->peerMacAddr, &aid, &psessionEntry->dph.dphHashTable );
if( NULL == pSta )
{
limLog( pMac, LOGE,
FL( "STA context not found - ignoring DELBA CNF from HAL" ));
palFreeMemory( pMac->hHdd, (void *) pMsgBuf );
return;
}
if(NULL == pMlmDelBACnf)
{
limLog( pMac, LOGE,
FL( "pMlmDelBACnf is NULL - ignoring DELBA CNF from HAL" ));
return;
}
// Need to validate baState
LIM_GET_STA_BA_STATE(pSta, pMlmDelBACnf->baTID, &curBaState);
if( eLIM_BA_STATE_WT_DEL_RSP != curBaState )
{
limLog( pMac, LOGE,
FL( "Received unexpected DELBA CNF when STA BA state is %d" ),
curBaState );
palFreeMemory( pMac->hHdd, (void *) pMsgBuf );
return;
}
// Restore STA BA state
LIM_SET_STA_BA_STATE(pSta, pMlmDelBACnf->baTID, eLIM_BA_STATE_IDLE);
// Free the memory allocated for LIM_MLM_DELBA_CNF
palFreeMemory( pMac->hHdd, (void *) pMsgBuf );
}
/**
* \brief Process SIR_LIM_DEL_BA_IND
*
* \sa limProcessMlmHalBADeleteInd
*
* \param pMac The global tpAniSirGlobal object
*
* \param tSirMsgQ The MsgQ header containing the indication buffer
*
* \return none
*/
void limProcessMlmHalBADeleteInd( tpAniSirGlobal pMac,
tpSirMsgQ limMsgQ )
{
tSirRetStatus status = eSIR_SUCCESS;
tpBADeleteParams pBADeleteParams;
tpDphHashNode pSta;
tANI_U16 aid;
tLimBAState curBaState;
tpPESession psessionEntry;
tANI_U8 sessionId;
pBADeleteParams = (tpBADeleteParams) limMsgQ->bodyptr;
if((psessionEntry = peFindSessionByBssid(pMac,pBADeleteParams->bssId,&sessionId))== NULL)
{
PELOGE(limLog(pMac, LOGE,FL("session does not exist for given BSSId"));)
palFreeMemory( pMac->hHdd, (void *) limMsgQ->bodyptr );
limMsgQ->bodyptr = NULL;
return;
}
// First, extract the DPH entry
pSta = dphLookupHashEntry( pMac, pBADeleteParams->peerMacAddr, &aid, &psessionEntry->dph.dphHashTable );
if( NULL == pSta )
{
limLog( pMac, LOGE,
FL( "STA context not found - ignoring BA Delete IND from HAL" ));
goto returnAfterCleanup;
}
// Need to validate BA state
LIM_GET_STA_BA_STATE(pSta, pBADeleteParams->baTID, &curBaState);
if( eLIM_BA_STATE_IDLE != curBaState )
{
limLog( pMac, LOGE,
FL( "Received unexpected BA Delete IND when STA BA state is %d" ),
curBaState );
goto returnAfterCleanup;
}
// Validate if a BA is active for the requested TID
// AND in that desired direction
if( eBA_INITIATOR == pBADeleteParams->baDirection )
{
if( 0 == pSta->tcCfg[pBADeleteParams->baTID].fUseBATx )
status = eSIR_FAILURE;
}
else
{
if( 0 == pSta->tcCfg[pBADeleteParams->baTID].fUseBARx )
status = eSIR_FAILURE;
}
if( eSIR_FAILURE == status )
{
limLog( pMac, LOGW,
FL("Received an INVALID DELBA Delete Ind for TID %d..."),
pBADeleteParams->baTID );
}
else
{
// Post DELBA REQ to MLME...
if( eSIR_SUCCESS !=
(status = limPostMlmDelBAReq( pMac,
pSta,
pBADeleteParams->baDirection,
pBADeleteParams->baTID,
eSIR_MAC_UNSPEC_FAILURE_REASON,psessionEntry )))
{
limLog( pMac, LOGE,
FL( "Attempt to post LIM_MLM_DELBA_REQ failed with status %d" ), status);
}
else
{
limLog( pMac, LOGE,
FL( "BA Delete - Reason 0x%08x. Attempting to delete BA session for TID %d with peer STA " ),
pBADeleteParams->reasonCode, pBADeleteParams->baTID );
limPrintMacAddr( pMac, pSta->staAddr, LOGE );
}
}
returnAfterCleanup:
// Free the memory allocated for SIR_LIM_DEL_BA_IND
palFreeMemory( pMac->hHdd, (void *) limMsgQ->bodyptr );
limMsgQ->bodyptr = NULL;
}
/**
* @function : limProcessSetMimoRsp()
*
* @brief : This function is called upon receiving the WDA_SET_MIMOPS_RSP from the HAL
* after Processing the Req from the SME (PMC)
*
* LOGIC:
*
* ASSUMPTIONS:
* NA
*
* NOTE:
* NA
*
* @param pMac - Pointer to Global MAC structure
* @param limMsg - Lim Message structure object with the MimoPSparam in body
* @return None
*/
void
limProcessSetMimoRsp(tpAniSirGlobal pMac, tpSirMsgQ limMsg)
{
#if 0
tSirRetStatus retStatus;
tpSetMIMOPS pMIMO_PSParams;
do {
pMIMO_PSParams = (tpSetMIMOPS)limMsg->bodyptr;
if( NULL == pMIMO_PSParams ) {
PELOGE(limLog(pMac, LOGE, "Received the WDA_SET_MIMOPS_RSP with NULL as the PS param");)
return;
}
/** If Updation of the HAL Fail's*/
if (pMIMO_PSParams->status != eSIR_SUCCESS) {
limLog(pMac, LOGP, FL("Update HAL / SW Mac for MIMO State has Failed"));
break;
}
if ((pMac->lim.gLimSystemRole != eSYSTEM_STA_ROLE) ||
(pMac->lim.gLimSmeState != eLIM_SME_LINK_EST_STATE) )
break;
pMac->lim.gLimMlmState = pMac->lim.gLimPrevMlmState;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, 0, pMac->lim.gLimMlmState));
/** In the Case of Exiting out of the Powersave (changing from Dynamic/Static mode to SM Enabled)
* send the action Frame to Peer to update the PS State of the STA , for the case of Entering PowerSave
* the Action Frame is being sent at first before setting the internal structures
*/
if (!isEnteringMimoPS(pMac->lim.gHTMIMOPSState, pMIMO_PSParams->htMIMOPSState)) {
tSirMacAddr macAddr;
/** Obtain the AP's Mac Address */
palCopyMemory(pMac -> hHdd, (tANI_U8 *)macAddr, pMac->lim.gLimBssid, sizeof(tSirMacAddr));
/** Send Action Frame with the corresponding mode */
retStatus = limSendSMPowerStateFrame(pMac, macAddr, pMIMO_PSParams->htMIMOPSState);
if (retStatus != eSIR_SUCCESS) {
PELOGE(limLog(pMac, LOGE, FL("Sending Action Frame has failed"));)
break;
}
}
PELOG1(limLog(pMac, LOG1, FL("The Setting up of LimGlobals is successful for MIMOPS"));)
}while(0);
palFreeMemory( pMac->hHdd, (void *) pMIMO_PSParams );
#endif
}
/**
* @function : limHandleDelBssInReAssocContext
* @brief : While Processing the ReAssociation Response Frame in STA,
* a. immediately after receiving the Reassoc Response the RxCleanUp is
* being issued and the end of DelBSS the new BSS is being added.
*
* b .If an AP rejects the ReAssociation (Disassoc / Deauth) with some context
* change, We need to update CSR with ReAssocCNF Response with the
* ReAssoc Fail and the reason Code, that is also being handled in the DELBSS
* context only
*
* @param : pMac - tpAniSirGlobal
* pStaDs - Station Descriptor
*
* @return : none
*/
static void
limHandleDelBssInReAssocContext(tpAniSirGlobal pMac, tpDphHashNode pStaDs,tpPESession psessionEntry)
{
tLimMlmReassocCnf mlmReassocCnf;
/** Skipped the DeleteDPH Hash Entry as we need it for the new BSS*/
/** Set the MlmState to IDLE*/
psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE;
/* Update PE session Id*/
mlmReassocCnf.sessionId = psessionEntry->peSessionId;
switch (psessionEntry->limMlmState) {
case eLIM_SME_WT_REASSOC_STATE :
{
tpSirAssocRsp assocRsp;
tpDphHashNode pStaDs;
tSirRetStatus retStatus = eSIR_SUCCESS;
tSchBeaconStruct beaconStruct;
/** Delete the older STA Table entry */
limDeleteDphHashEntry(pMac, psessionEntry->bssId, DPH_STA_HASH_INDEX_PEER, psessionEntry);
/**
* Add an entry for AP to hash table
* maintained by DPH module
*/
if ((pStaDs = dphAddHashEntry(pMac, psessionEntry->limReAssocbssId, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable)) == NULL)
{
// Could not add hash table entry
PELOGE(limLog(pMac, LOGE, FL("could not add hash entry at DPH for "));)
limPrintMacAddr(pMac, psessionEntry->limReAssocbssId, LOGE);
mlmReassocCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE;
mlmReassocCnf.protStatusCode = eSIR_SME_SUCCESS;
goto Error;
}
/** While Processing the ReAssoc Response Frame the ReAssocRsp Frame
* is being stored to be used here for sending ADDBSS
*/
assocRsp = (tpSirAssocRsp)psessionEntry->limAssocResponseData;
limUpdateAssocStaDatas(pMac, pStaDs, assocRsp,psessionEntry);
limUpdateReAssocGlobals(pMac, assocRsp,psessionEntry);
limExtractApCapabilities( pMac,
(tANI_U8 *) psessionEntry->pLimReAssocReq->bssDescription.ieFields,
limGetIElenFromBssDescription( &psessionEntry->pLimReAssocReq->bssDescription ),
&beaconStruct );
if(pMac->lim.gLimProtectionControl != WNI_CFG_FORCE_POLICY_PROTECTION_DISABLE)
limDecideStaProtectionOnAssoc(pMac, &beaconStruct, psessionEntry);
if(beaconStruct.erpPresent) {
if (beaconStruct.erpIEInfo.barkerPreambleMode)
psessionEntry->beaconParams.fShortPreamble = 0;
else
psessionEntry->beaconParams.fShortPreamble = 1;
}
//updateBss flag is false, as in this case, PE is first deleting the existing BSS and then adding a new one.
if (eSIR_SUCCESS != limStaSendAddBss( pMac, assocRsp, &beaconStruct,
&psessionEntry->pLimReAssocReq->bssDescription, false, psessionEntry)) {
limLog( pMac, LOGE, FL( "Posting ADDBSS in the ReAssocContext has Failed "));
retStatus = eSIR_FAILURE;
}
if (retStatus != eSIR_SUCCESS)
{
mlmReassocCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE;
mlmReassocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS;
palFreeMemory(pMac->hHdd, assocRsp);
pMac->lim.gLimAssocResponseData = NULL;
goto Error;
}
palFreeMemory(pMac->hHdd, assocRsp);
psessionEntry->limAssocResponseData = NULL;
}
break;
case eLIM_SME_WT_REASSOC_LINK_FAIL_STATE:
{
/** Case wherein the DisAssoc / Deauth
* being sent as response to ReAssoc Req*/
/** Send the Reason code as the same received in Disassoc / Deauth Frame*/
mlmReassocCnf.resultCode = pStaDs->mlmStaContext.disassocReason;
mlmReassocCnf.protStatusCode = pStaDs->mlmStaContext.cleanupTrigger;
/** Set the SME State back to WT_Reassoc State*/
psessionEntry->limSmeState = eLIM_SME_WT_REASSOC_STATE;
limDeleteDphHashEntry(pMac, pStaDs->staAddr, pStaDs->assocId,psessionEntry);
if((psessionEntry->limSystemRole == eLIM_STA_ROLE)||
(psessionEntry->limSystemRole == eLIM_BT_AMP_STA_ROLE))
{
psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE;
}
limPostSmeMessage(pMac, LIM_MLM_REASSOC_CNF, (tANI_U32 *) &mlmReassocCnf);
}
break;
default:
PELOGE(limLog(pMac, LOGE, FL("DelBss is being invoked in the wrong system Role /unhandled SME State"));)
mlmReassocCnf.resultCode = eSIR_SME_REFUSED;
mlmReassocCnf.protStatusCode = eSIR_SME_UNEXPECTED_REQ_RESULT_CODE;
goto Error;
}
return;
Error:
limPostSmeMessage(pMac, LIM_MLM_REASSOC_CNF, (tANI_U32 *) &mlmReassocCnf);
}
/* Added For BT -AMP Support */
static void
limProcessBtampAddBssRsp( tpAniSirGlobal pMac, tpSirMsgQ limMsgQ ,tpPESession psessionEntry)
{
tLimMlmStartCnf mlmStartCnf;
tANI_U32 val;
tpAddBssParams pAddBssParams = (tpAddBssParams) limMsgQ->bodyptr;
if (NULL == pAddBssParams)
{
limLog( pMac, LOGE, FL( "Invalid body pointer in message"));
goto end;
}
if( eHAL_STATUS_SUCCESS == pAddBssParams->status )
{
limLog(pMac, LOG2, FL("WDA_ADD_BSS_RSP returned with eHAL_STATUS_SUCCESS"));
if (psessionEntry->bssType == eSIR_BTAMP_AP_MODE)
{
if (limSetLinkState(pMac, eSIR_LINK_BTAMP_AP_STATE, psessionEntry->bssId,
psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS )
goto end;
} else if (psessionEntry->bssType == eSIR_BTAMP_STA_MODE) {
if (limSetLinkState(pMac, eSIR_LINK_SCAN_STATE, psessionEntry->bssId,
psessionEntry->selfMacAddr, NULL, NULL) != eSIR_SUCCESS )
goto end;
}
// Set MLME state
psessionEntry->limMlmState= eLIM_MLM_BSS_STARTED_STATE;
psessionEntry->statypeForBss = STA_ENTRY_SELF; // to know session started for peer or for self
psessionEntry->bssIdx = (tANI_U8) pAddBssParams->bssIdx;
schEdcaProfileUpdate(pMac, psessionEntry);
limInitPeerIdxpool(pMac,psessionEntry);
// Create timers used by LIM
if (!pMac->lim.gLimTimersCreated)
limCreateTimers(pMac);
/* Update the lim global gLimTriggerBackgroundScanDuringQuietBss */
if( eSIR_SUCCESS != wlan_cfgGetInt( pMac, WNI_CFG_TRIG_STA_BK_SCAN, &val ))
limLog( pMac, LOGP, FL("Failed to get WNI_CFG_TRIG_STA_BK_SCAN!"));
pMac->lim.gLimTriggerBackgroundScanDuringQuietBss = (val) ? 1 : 0;
// Apply previously set configuration at HW
limApplyConfiguration(pMac,psessionEntry);
psessionEntry->staId = pAddBssParams->staContext.staIdx;
mlmStartCnf.resultCode = eSIR_SME_SUCCESS;
}
else
{
limLog( pMac, LOGE, FL( "WDA_ADD_BSS_REQ failed with status %d" ),pAddBssParams->status );
mlmStartCnf.resultCode = eSIR_SME_HAL_SEND_MESSAGE_FAIL;
}
mlmStartCnf.sessionId = psessionEntry->peSessionId;
limPostSmeMessage( pMac, LIM_MLM_START_CNF, (tANI_U32 *) &mlmStartCnf );
end:
if( 0 != limMsgQ->bodyptr )
{
palFreeMemory( pMac->hHdd, (void *) pAddBssParams );
limMsgQ->bodyptr = NULL;
}
}
/**
* @function : limHandleAddBssInReAssocContext
* @brief : While Processing the ReAssociation Response Frame in STA,
* a. immediately after receiving the Reassoc Response the RxCleanUp is
* being issued and the end of DelBSS the new BSS is being added.
*
* b .If an AP rejects the ReAssociation (Disassoc / Deauth) with some context
* change, We need to update CSR with ReAssocCNF Response with the
* ReAssoc Fail and the reason Code, that is also being handled in the DELBSS
* context only
*
* @param : pMac - tpAniSirGlobal
* pStaDs - Station Descriptor
*
* @return : none
*/
void
limHandleAddBssInReAssocContext(tpAniSirGlobal pMac, tpDphHashNode pStaDs, tpPESession psessionEntry)
{
tLimMlmReassocCnf mlmReassocCnf;
/** Skipped the DeleteDPH Hash Entry as we need it for the new BSS*/
/** Set the MlmState to IDLE*/
psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
switch (psessionEntry->limSmeState) {
case eLIM_SME_WT_REASSOC_STATE : {
tpSirAssocRsp assocRsp;
tpDphHashNode pStaDs;
tSirRetStatus retStatus = eSIR_SUCCESS;
tSchBeaconStruct *pBeaconStruct;
if(eHAL_STATUS_SUCCESS != palAllocateMemory(pMac->hHdd,
(void **)&pBeaconStruct, sizeof(tSchBeaconStruct)))
{
limLog(pMac, LOGE, FL("Unable to PAL allocate memory in limHandleAddBssInReAssocContext") );
mlmReassocCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE;
mlmReassocCnf.protStatusCode = eSIR_SME_RESOURCES_UNAVAILABLE;
goto Error;
}
// Get the AP entry from DPH hash table
pStaDs = dphGetHashEntry(pMac, DPH_STA_HASH_INDEX_PEER, &psessionEntry->dph.dphHashTable);
if (pStaDs == NULL )
{
PELOGE(limLog(pMac, LOGE, FL("Fail to get STA PEER entry from hash"));)
mlmReassocCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE;
mlmReassocCnf.protStatusCode = eSIR_SME_SUCCESS;
palFreeMemory(pMac->hHdd, pBeaconStruct);
goto Error;
}
/** While Processing the ReAssoc Response Frame the ReAssocRsp Frame
* is being stored to be used here for sending ADDBSS
*/
assocRsp = (tpSirAssocRsp)psessionEntry->limAssocResponseData;
limUpdateAssocStaDatas(pMac, pStaDs, assocRsp, psessionEntry);
limUpdateReAssocGlobals(pMac, assocRsp, psessionEntry);
limExtractApCapabilities( pMac,
(tANI_U8 *) psessionEntry->pLimReAssocReq->bssDescription.ieFields,
limGetIElenFromBssDescription( &psessionEntry->pLimReAssocReq->bssDescription ),
pBeaconStruct );
if(pMac->lim.gLimProtectionControl != WNI_CFG_FORCE_POLICY_PROTECTION_DISABLE)
limDecideStaProtectionOnAssoc(pMac, pBeaconStruct, psessionEntry);
if(pBeaconStruct->erpPresent)
{
if (pBeaconStruct->erpIEInfo.barkerPreambleMode)
psessionEntry->beaconParams.fShortPreamble = 0;
else
psessionEntry->beaconParams.fShortPreamble = 1;
}
if (eSIR_SUCCESS != limStaSendAddBss( pMac, assocRsp, pBeaconStruct,
&psessionEntry->pLimReAssocReq->bssDescription, true, psessionEntry)) {
limLog( pMac, LOGE, FL( "Posting ADDBSS in the ReAssocContext has Failed "));
retStatus = eSIR_FAILURE;
}
if (retStatus != eSIR_SUCCESS)
{
mlmReassocCnf.resultCode = eSIR_SME_RESOURCES_UNAVAILABLE;
mlmReassocCnf.protStatusCode = eSIR_MAC_UNSPEC_FAILURE_STATUS;
palFreeMemory(pMac->hHdd, assocRsp);
pMac->lim.gLimAssocResponseData = NULL;
palFreeMemory(pMac->hHdd, pBeaconStruct);
goto Error;
}
palFreeMemory(pMac->hHdd, assocRsp);
psessionEntry->limAssocResponseData = NULL;
palFreeMemory(pMac->hHdd, pBeaconStruct);
}
break;
case eLIM_SME_WT_REASSOC_LINK_FAIL_STATE: { /** Case wherein the DisAssoc / Deauth
* being sent as response to ReAssoc Req*/
/** Send the Reason code as the same received in Disassoc / Deauth Frame*/
mlmReassocCnf.resultCode = pStaDs->mlmStaContext.disassocReason;
mlmReassocCnf.protStatusCode = pStaDs->mlmStaContext.cleanupTrigger;
/** Set the SME State back to WT_Reassoc State*/
psessionEntry->limSmeState = eLIM_SME_WT_REASSOC_STATE;
limDeleteDphHashEntry(pMac, pStaDs->staAddr, pStaDs->assocId, psessionEntry);
if(psessionEntry->limSystemRole == eLIM_STA_ROLE)
{
psessionEntry->limMlmState = eLIM_MLM_IDLE_STATE;
MTRACE(macTrace(pMac, TRACE_CODE_MLM_STATE, psessionEntry->peSessionId, psessionEntry->limMlmState));
}
limPostSmeMessage(pMac, LIM_MLM_REASSOC_CNF, (tANI_U32 *) &mlmReassocCnf);
}
break;
default:
PELOGE(limLog(pMac, LOGE, FL("DelBss is being invoked in the wrong system Role /unhandled SME State"));)
mlmReassocCnf.resultCode = eSIR_SME_REFUSED;
mlmReassocCnf.protStatusCode = eSIR_SME_UNEXPECTED_REQ_RESULT_CODE;
goto Error;
}
return;
Error:
limPostSmeMessage(pMac, LIM_MLM_REASSOC_CNF, (tANI_U32 *) &mlmReassocCnf);
}
#if 0
static void
limProcessSmeAssocCnfNew(tpAniSirGlobal pMac, tANI_U32 msgType, tANI_U32 *pMsgBuf)
{
tSirSmeAssocCnf assocCnf;
tpDphHashNode pStaDs;
tpPESession psessionEntry;
tANI_U8 sessionId;
if(pMsgBuf == NULL)
{
limLog(pMac, LOGE, FL("pMsgBuf is NULL "));
goto end;
}
if ((limAssocCnfSerDes(pMac, &assocCnf, (tANI_U8 *) pMsgBuf) == eSIR_FAILURE) ||
!__limIsSmeAssocCnfValid(&assocCnf))
{
limLog(pMac, LOGE, FL("Received invalid SME_RE(ASSOC)_CNF message "));
goto end;
}
if((psessionEntry = peFindSessionByBssid(pMac, assocCnf.bssId, &sessionId))== NULL)
{
limLog(pMac, LOGE, FL("session does not exist for given bssId"));
goto end;
}
if ( ((psessionEntry->limSystemRole != eLIM_AP_ROLE) && (psessionEntry->limSystemRole != eLIM_BT_AMP_AP_ROLE)) ||
((psessionEntry->limSmeState != eLIM_SME_NORMAL_STATE) && (psessionEntry->limSmeState != eLIM_SME_NORMAL_CHANNEL_SCAN_STATE)))
{
limLog(pMac, LOGE, FL("Received unexpected message %X in state %X, in role %X"),
msgType, psessionEntry->limSmeState , psessionEntry->limSystemRole);
goto end;
}
pStaDs = dphGetHashEntry(pMac, assocCnf.aid, &psessionEntry->dph.dphHashTable);
if (pStaDs == NULL)
{
limLog(pMac, LOG1,
FL("Received invalid message %X due to no STA context, for aid %d, peer "),
msgType, assocCnf.aid);
limPrintMacAddr(pMac, assocCnf.peerMacAddr, LOG1);
/*
** send a DISASSOC_IND message to WSM to make sure
** the state in WSM and LIM is the same
**/
limSendSmeDisassocNtf( pMac, assocCnf.peerMacAddr, eSIR_SME_STA_NOT_ASSOCIATED,
eLIM_PEER_ENTITY_DISASSOC, assocCnf.aid,psessionEntry->smeSessionId,psessionEntry->transactionId,psessionEntry);
goto end;
}
if ((pStaDs &&
(( !palEqualMemory( pMac->hHdd,(tANI_U8 *) pStaDs->staAddr,
(tANI_U8 *) assocCnf.peerMacAddr,
sizeof(tSirMacAddr)) ) ||
(pStaDs->mlmStaContext.mlmState != eLIM_MLM_WT_ASSOC_CNF_STATE) ||
((pStaDs->mlmStaContext.subType == LIM_ASSOC) &&
(msgType != eWNI_SME_ASSOC_CNF)) ||
((pStaDs->mlmStaContext.subType == LIM_REASSOC) &&
(msgType != eWNI_SME_REASSOC_CNF)))))
{
limLog(pMac, LOG1,
FL("Received invalid message %X due to peerMacAddr mismatched or not in eLIM_MLM_WT_ASSOC_CNF_STATE state, for aid %d, peer "),
msgType, assocCnf.aid);
limPrintMacAddr(pMac, assocCnf.peerMacAddr, LOG1);
goto end;
}
/*
** Deactivate/delet CNF_WAIT timer since ASSOC_CNF
** has been received
**/
limLog(pMac, LOG1, FL("Received SME_ASSOC_CNF. Delete Timer"));
limDeactivateAndChangePerStaIdTimer(pMac, eLIM_CNF_WAIT_TIMER, pStaDs->assocId);
if (assocCnf.statusCode == eSIR_SME_SUCCESS)
{
/* In BTAMP-AP, PE already finished the WDA_ADD_STA sequence
* when it had received Assoc Request frame. Now, PE just needs to send
* Association Response frame to the requesting BTAMP-STA.
*/
pStaDs->mlmStaContext.mlmState = eLIM_MLM_LINK_ESTABLISHED_STATE;
limLog(pMac, LOG1, FL("sending Assoc Rsp frame to STA (assoc id=%d) "), pStaDs->assocId);
limSendAssocRspMgmtFrame( pMac, eSIR_SUCCESS, pStaDs->assocId, pStaDs->staAddr,
pStaDs->mlmStaContext.subType, pStaDs, psessionEntry);
goto end;
} // (assocCnf.statusCode == eSIR_SME_SUCCESS)
else
{
// SME_ASSOC_CNF status is non-success, so STA is not allowed to be associated
limRejectAssociation(pMac, pStaDs->staAddr,
pStaDs->mlmStaContext.subType,
true, pStaDs->mlmStaContext.authType,
pStaDs->assocId, true,
assocCnf.statusCode, psessionEntry);
return;
}
end:
if ( psessionEntry->parsedAssocReq[pStaDs->assocId] != NULL )
{
if ( ((tpSirAssocReq)(psessionEntry->parsedAssocReq[pStaDs->assocId]))->assocReqFrame)
{
palFreeMemory(pMac->hHdd,((tpSirAssocReq)(psessionEntry->parsedAssocReq[pStaDs->assocId]))->assocReqFrame);
((tpSirAssocReq)(psessionEntry->parsedAssocReq[pStaDs->assocId]))->assocReqFrame = NULL;
}
palFreeMemory(pMac->hHdd, psessionEntry->parsedAssocReq[pStaDs->assocId]);
psessionEntry->parsedAssocReq[pStaDs->assocId] = NULL;
}
} /*** end __limProcessSmeAssocCnfNew() ***/
#endif
void
limSendBeaconInd(tpAniSirGlobal pMac, tpPESession psessionEntry){
tBeaconGenParams *pBeaconGenParams = NULL;
tSirMsgQ limMsg;
/** Allocate the Memory for Beacon Pre Message and for Stations in PoweSave*/
if(psessionEntry == NULL ){
PELOGE( limLog( pMac, LOGE,
FL( "Error:Unable to get the PESessionEntry" ));)
return;
}
if( eHAL_STATUS_SUCCESS != palAllocateMemory( pMac->hHdd,
(void **) &pBeaconGenParams, (sizeof(*pBeaconGenParams))))
{
PELOGE( limLog( pMac, LOGP,
FL( "Unable to PAL allocate memory during sending beaconPreMessage" ));)
return;
}
palZeroMemory( pMac->hHdd, pBeaconGenParams, sizeof(*pBeaconGenParams));
palCopyMemory( pMac->hHdd, (void *) pBeaconGenParams->bssId,
(void *)psessionEntry->bssId,
SIR_MAC_ADDR_LENGTH );
limMsg.bodyptr = pBeaconGenParams;
schProcessPreBeaconInd(pMac, &limMsg);
return;
}
| gpl-2.0 |
val2k/linux | drivers/staging/vt6656/mac.c | 135 | 5338 | /*
* Copyright (c) 1996, 2003 VIA Networking Technologies, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* File: mac.c
*
* Purpose: MAC routines
*
* Author: Tevin Chen
*
* Date: May 21, 1996
*
* Functions:
*
* Revision History:
*/
#include <linux/etherdevice.h>
#include "desc.h"
#include "mac.h"
#include "usbpipe.h"
/*
* Description:
* Write MAC Multicast Address Mask
*
* Parameters:
* In:
* mc_filter (mac filter)
* Out:
* none
*
* Return Value: none
*
*/
void vnt_mac_set_filter(struct vnt_private *priv, u64 mc_filter)
{
__le64 le_mc = cpu_to_le64(mc_filter);
vnt_control_out(priv, MESSAGE_TYPE_WRITE, MAC_REG_MAR0,
MESSAGE_REQUEST_MACREG, sizeof(le_mc), (u8 *)&le_mc);
}
/*
* Description:
* Shut Down MAC
*
* Parameters:
* In:
* Out:
* none
*
*
*/
void vnt_mac_shutdown(struct vnt_private *priv)
{
vnt_control_out(priv, MESSAGE_TYPE_MACSHUTDOWN, 0, 0, 0, NULL);
}
void vnt_mac_set_bb_type(struct vnt_private *priv, u8 type)
{
u8 data[2];
data[0] = type;
data[1] = EnCFG_BBType_MASK;
vnt_control_out(priv, MESSAGE_TYPE_WRITE_MASK, MAC_REG_ENCFG0,
MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data), data);
}
/*
* Description:
* Disable the Key Entry by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void vnt_mac_disable_keyentry(struct vnt_private *priv, u8 entry_idx)
{
vnt_control_out(priv, MESSAGE_TYPE_CLRKEYENTRY, 0, 0,
sizeof(entry_idx), &entry_idx);
}
/*
* Description:
* Set the Key by MISCFIFO
*
* Parameters:
* In:
* dwIoBase - Base Address for MAC
*
* Out:
* none
*
* Return Value: none
*
*/
void vnt_mac_set_keyentry(struct vnt_private *priv, u16 key_ctl, u32 entry_idx,
u32 key_idx, u8 *addr, u8 *key)
{
struct vnt_mac_set_key set_key;
u16 offset;
offset = MISCFIFO_KEYETRY0;
offset += entry_idx * MISCFIFO_KEYENTRYSIZE;
set_key.u.write.key_ctl = cpu_to_le16(key_ctl);
ether_addr_copy(set_key.u.write.addr, addr);
/* swap over swap[0] and swap[1] to get correct write order */
swap(set_key.u.swap[0], set_key.u.swap[1]);
memcpy(set_key.key, key, WLAN_KEY_LEN_CCMP);
dev_dbg(&priv->usb->dev, "offset %d key ctl %d set key %24ph\n",
offset, key_ctl, (u8 *)&set_key);
vnt_control_out(priv, MESSAGE_TYPE_SETKEY, offset,
(u16)key_idx, sizeof(struct vnt_mac_set_key),
(u8 *)&set_key);
}
void vnt_mac_reg_bits_off(struct vnt_private *priv, u8 reg_ofs, u8 bits)
{
u8 data[2];
data[0] = 0;
data[1] = bits;
vnt_control_out(priv, MESSAGE_TYPE_WRITE_MASK,
reg_ofs, MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data),
data);
}
void vnt_mac_reg_bits_on(struct vnt_private *priv, u8 reg_ofs, u8 bits)
{
u8 data[2];
data[0] = bits;
data[1] = bits;
vnt_control_out(priv, MESSAGE_TYPE_WRITE_MASK, reg_ofs,
MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data), data);
}
void vnt_mac_write_word(struct vnt_private *priv, u8 reg_ofs, u16 word)
{
u8 data[2];
data[0] = (u8)(word & 0xff);
data[1] = (u8)(word >> 8);
vnt_control_out(priv, MESSAGE_TYPE_WRITE, reg_ofs,
MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data), data);
}
void vnt_mac_set_bssid_addr(struct vnt_private *priv, u8 *addr)
{
vnt_control_out(priv, MESSAGE_TYPE_WRITE, MAC_REG_BSSID0,
MESSAGE_REQUEST_MACREG, ETH_ALEN, addr);
}
void vnt_mac_enable_protect_mode(struct vnt_private *priv)
{
u8 data[2];
data[0] = EnCFG_ProtectMd;
data[1] = EnCFG_ProtectMd;
vnt_control_out(priv, MESSAGE_TYPE_WRITE_MASK, MAC_REG_ENCFG0,
MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data), data);
}
void vnt_mac_disable_protect_mode(struct vnt_private *priv)
{
u8 data[2];
data[0] = 0;
data[1] = EnCFG_ProtectMd;
vnt_control_out(priv, MESSAGE_TYPE_WRITE_MASK, MAC_REG_ENCFG0,
MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data), data);
}
void vnt_mac_enable_barker_preamble_mode(struct vnt_private *priv)
{
u8 data[2];
data[0] = EnCFG_BarkerPream;
data[1] = EnCFG_BarkerPream;
vnt_control_out(priv, MESSAGE_TYPE_WRITE_MASK, MAC_REG_ENCFG2,
MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data), data);
}
void vnt_mac_disable_barker_preamble_mode(struct vnt_private *priv)
{
u8 data[2];
data[0] = 0;
data[1] = EnCFG_BarkerPream;
vnt_control_out(priv, MESSAGE_TYPE_WRITE_MASK, MAC_REG_ENCFG2,
MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data), data);
}
void vnt_mac_set_beacon_interval(struct vnt_private *priv, u16 interval)
{
u8 data[2];
data[0] = (u8)(interval & 0xff);
data[1] = (u8)(interval >> 8);
vnt_control_out(priv, MESSAGE_TYPE_WRITE, MAC_REG_BI,
MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data), data);
}
void vnt_mac_set_led(struct vnt_private *priv, u8 state, u8 led)
{
u8 data[2];
data[0] = led;
data[1] = state;
vnt_control_out(priv, MESSAGE_TYPE_WRITE_MASK, MAC_REG_PAPEDELAY,
MESSAGE_REQUEST_MACREG, ARRAY_SIZE(data), data);
}
| gpl-2.0 |
Tasssadar/android_kernel_asus_grouper | drivers/staging/iio/dac/max517.c | 391 | 7401 | /*
* max517.c - Support for Maxim MAX517, MAX518 and MAX519
*
* Copyright (C) 2010, 2011 Roland Stigge <stigge@antcom.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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include "../iio.h"
#include "dac.h"
#include "max517.h"
#define MAX517_DRV_NAME "max517"
/* Commands */
#define COMMAND_CHANNEL0 0x00
#define COMMAND_CHANNEL1 0x01 /* for MAX518 and MAX519 */
#define COMMAND_PD 0x08 /* Power Down */
enum max517_device_ids {
ID_MAX517,
ID_MAX518,
ID_MAX519,
};
struct max517_data {
struct iio_dev *indio_dev;
struct i2c_client *client;
unsigned short vref_mv[2];
};
/*
* channel: bit 0: channel 1
* bit 1: channel 2
* (this way, it's possible to set both channels at once)
*/
static ssize_t max517_set_value(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count, int channel)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct max517_data *data = iio_priv(dev_info);
struct i2c_client *client = data->client;
u8 outbuf[4]; /* 1x or 2x command + value */
int outbuf_size = 0;
int res;
long val;
res = strict_strtol(buf, 10, &val);
if (res)
return res;
if (val < 0 || val > 255)
return -EINVAL;
if (channel & 1) {
outbuf[outbuf_size++] = COMMAND_CHANNEL0;
outbuf[outbuf_size++] = val;
}
if (channel & 2) {
outbuf[outbuf_size++] = COMMAND_CHANNEL1;
outbuf[outbuf_size++] = val;
}
/*
* At this point, there are always 1 or 2 two-byte commands in
* outbuf. With 2 commands, the device can set two outputs
* simultaneously, latching the values upon the end of the I2C
* transfer.
*/
res = i2c_master_send(client, outbuf, outbuf_size);
if (res < 0)
return res;
return count;
}
static ssize_t max517_set_value_1(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return max517_set_value(dev, attr, buf, count, 1);
}
static IIO_DEV_ATTR_OUT_RAW(1, max517_set_value_1, 0);
static ssize_t max517_set_value_2(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return max517_set_value(dev, attr, buf, count, 2);
}
static IIO_DEV_ATTR_OUT_RAW(2, max517_set_value_2, 1);
static ssize_t max517_set_value_both(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return max517_set_value(dev, attr, buf, count, 3);
}
static IIO_DEVICE_ATTR_NAMED(out1and2_raw, out1&2_raw, S_IWUSR, NULL,
max517_set_value_both, -1);
static ssize_t max517_show_scale(struct device *dev,
struct device_attribute *attr,
char *buf, int channel)
{
struct iio_dev *dev_info = dev_get_drvdata(dev);
struct max517_data *data = iio_priv(dev_info);
/* Corresponds to Vref / 2^(bits) */
unsigned int scale_uv = (data->vref_mv[channel - 1] * 1000) >> 8;
return sprintf(buf, "%d.%03d\n", scale_uv / 1000, scale_uv % 1000);
}
static ssize_t max517_show_scale1(struct device *dev,
struct device_attribute *attr,
char *buf)
{
return max517_show_scale(dev, attr, buf, 1);
}
static IIO_DEVICE_ATTR(out1_scale, S_IRUGO, max517_show_scale1, NULL, 0);
static ssize_t max517_show_scale2(struct device *dev,
struct device_attribute *attr,
char *buf)
{
return max517_show_scale(dev, attr, buf, 2);
}
static IIO_DEVICE_ATTR(out2_scale, S_IRUGO, max517_show_scale2, NULL, 0);
/* On MAX517 variant, we have one output */
static struct attribute *max517_attributes[] = {
&iio_dev_attr_out1_raw.dev_attr.attr,
&iio_dev_attr_out1_scale.dev_attr.attr,
NULL
};
static struct attribute_group max517_attribute_group = {
.attrs = max517_attributes,
};
/* On MAX518 and MAX519 variant, we have two outputs */
static struct attribute *max518_attributes[] = {
&iio_dev_attr_out1_raw.dev_attr.attr,
&iio_dev_attr_out1_scale.dev_attr.attr,
&iio_dev_attr_out2_raw.dev_attr.attr,
&iio_dev_attr_out2_scale.dev_attr.attr,
&iio_dev_attr_out1and2_raw.dev_attr.attr,
NULL
};
static struct attribute_group max518_attribute_group = {
.attrs = max518_attributes,
};
static int max517_suspend(struct i2c_client *client, pm_message_t mesg)
{
u8 outbuf = COMMAND_PD;
return i2c_master_send(client, &outbuf, 1);
}
static int max517_resume(struct i2c_client *client)
{
u8 outbuf = 0;
return i2c_master_send(client, &outbuf, 1);
}
static const struct iio_info max517_info = {
.attrs = &max517_attribute_group,
.driver_module = THIS_MODULE,
};
static const struct iio_info max518_info = {
.attrs = &max518_attribute_group,
.driver_module = THIS_MODULE,
};
static int max517_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct max517_data *data;
struct iio_dev *indio_dev;
struct max517_platform_data *platform_data = client->dev.platform_data;
int err;
indio_dev = iio_allocate_device(sizeof(*data));
if (indio_dev == NULL) {
err = -ENOMEM;
goto exit;
}
data = iio_priv(indio_dev);
i2c_set_clientdata(client, indio_dev);
data->client = client;
/* establish that the iio_dev is a child of the i2c device */
indio_dev->dev.parent = &client->dev;
/* reduced attribute set for MAX517 */
if (id->driver_data == ID_MAX517)
indio_dev->info = &max517_info;
else
indio_dev->info = &max518_info;
indio_dev->modes = INDIO_DIRECT_MODE;
/*
* Reference voltage on MAX518 and default is 5V, else take vref_mv
* from platform_data
*/
if (id->driver_data == ID_MAX518 || !platform_data) {
data->vref_mv[0] = data->vref_mv[1] = 5000; /* mV */
} else {
data->vref_mv[0] = platform_data->vref_mv[0];
data->vref_mv[1] = platform_data->vref_mv[1];
}
err = iio_device_register(indio_dev);
if (err)
goto exit_free_device;
dev_info(&client->dev, "DAC registered\n");
return 0;
exit_free_device:
iio_free_device(indio_dev);
exit:
return err;
}
static int max517_remove(struct i2c_client *client)
{
iio_free_device(i2c_get_clientdata(client));
return 0;
}
static const struct i2c_device_id max517_id[] = {
{ "max517", ID_MAX517 },
{ "max518", ID_MAX518 },
{ "max519", ID_MAX519 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max517_id);
static struct i2c_driver max517_driver = {
.driver = {
.name = MAX517_DRV_NAME,
},
.probe = max517_probe,
.remove = max517_remove,
.suspend = max517_suspend,
.resume = max517_resume,
.id_table = max517_id,
};
static int __init max517_init(void)
{
return i2c_add_driver(&max517_driver);
}
static void __exit max517_exit(void)
{
i2c_del_driver(&max517_driver);
}
MODULE_AUTHOR("Roland Stigge <stigge@antcom.de>");
MODULE_DESCRIPTION("MAX517/MAX518/MAX519 8-bit DAC");
MODULE_LICENSE("GPL");
module_init(max517_init);
module_exit(max517_exit);
| gpl-2.0 |
jimix/linux-poweren | drivers/staging/gma500/psb_device.c | 391 | 9378 | /**************************************************************************
* Copyright (c) 2011, Intel Corporation.
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
**************************************************************************/
#include <linux/backlight.h>
#include <drm/drmP.h>
#include <drm/drm.h>
#include "psb_drm.h"
#include "psb_drv.h"
#include "psb_reg.h"
#include "psb_intel_reg.h"
#include "intel_bios.h"
static int psb_output_init(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
psb_intel_lvds_init(dev, &dev_priv->mode_dev);
psb_intel_sdvo_init(dev, SDVOB);
return 0;
}
#ifdef CONFIG_BACKLIGHT_CLASS_DEVICE
/*
* Poulsbo Backlight Interfaces
*/
#define BLC_PWM_PRECISION_FACTOR 100 /* 10000000 */
#define BLC_PWM_FREQ_CALC_CONSTANT 32
#define MHz 1000000
#define PSB_BLC_PWM_PRECISION_FACTOR 10
#define PSB_BLC_MAX_PWM_REG_FREQ 0xFFFE
#define PSB_BLC_MIN_PWM_REG_FREQ 0x2
#define PSB_BACKLIGHT_PWM_POLARITY_BIT_CLEAR (0xFFFE)
#define PSB_BACKLIGHT_PWM_CTL_SHIFT (16)
static int psb_brightness;
static struct backlight_device *psb_backlight_device;
static int psb_get_brightness(struct backlight_device *bd)
{
/* return locally cached var instead of HW read (due to DPST etc.) */
/* FIXME: ideally return actual value in case firmware fiddled with
it */
return psb_brightness;
}
static int psb_backlight_setup(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
unsigned long core_clock;
/* u32 bl_max_freq; */
/* unsigned long value; */
u16 bl_max_freq;
uint32_t value;
uint32_t blc_pwm_precision_factor;
/* get bl_max_freq and pol from dev_priv*/
if (!dev_priv->lvds_bl) {
dev_err(dev->dev, "Has no valid LVDS backlight info\n");
return -ENOENT;
}
bl_max_freq = dev_priv->lvds_bl->freq;
blc_pwm_precision_factor = PSB_BLC_PWM_PRECISION_FACTOR;
core_clock = dev_priv->core_freq;
value = (core_clock * MHz) / BLC_PWM_FREQ_CALC_CONSTANT;
value *= blc_pwm_precision_factor;
value /= bl_max_freq;
value /= blc_pwm_precision_factor;
if (value > (unsigned long long)PSB_BLC_MAX_PWM_REG_FREQ ||
value < (unsigned long long)PSB_BLC_MIN_PWM_REG_FREQ)
return -ERANGE;
else {
value &= PSB_BACKLIGHT_PWM_POLARITY_BIT_CLEAR;
REG_WRITE(BLC_PWM_CTL,
(value << PSB_BACKLIGHT_PWM_CTL_SHIFT) | (value));
}
return 0;
}
static int psb_set_brightness(struct backlight_device *bd)
{
struct drm_device *dev = bl_get_data(psb_backlight_device);
int level = bd->props.brightness;
/* Percentage 1-100% being valid */
if (level < 1)
level = 1;
psb_intel_lvds_set_brightness(dev, level);
psb_brightness = level;
return 0;
}
static const struct backlight_ops psb_ops = {
.get_brightness = psb_get_brightness,
.update_status = psb_set_brightness,
};
static int psb_backlight_init(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
int ret;
struct backlight_properties props;
memset(&props, 0, sizeof(struct backlight_properties));
props.max_brightness = 100;
props.type = BACKLIGHT_PLATFORM;
psb_backlight_device = backlight_device_register("psb-bl",
NULL, (void *)dev, &psb_ops, &props);
if (IS_ERR(psb_backlight_device))
return PTR_ERR(psb_backlight_device);
ret = psb_backlight_setup(dev);
if (ret < 0) {
backlight_device_unregister(psb_backlight_device);
psb_backlight_device = NULL;
return ret;
}
psb_backlight_device->props.brightness = 100;
psb_backlight_device->props.max_brightness = 100;
backlight_update_status(psb_backlight_device);
dev_priv->backlight_device = psb_backlight_device;
return 0;
}
#endif
/*
* Provide the Poulsbo specific chip logic and low level methods
* for power management
*/
static void psb_init_pm(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
u32 gating = PSB_RSGX32(PSB_CR_CLKGATECTL);
gating &= ~3; /* Disable 2D clock gating */
gating |= 1;
PSB_WSGX32(gating, PSB_CR_CLKGATECTL);
PSB_RSGX32(PSB_CR_CLKGATECTL);
}
/**
* psb_save_display_registers - save registers lost on suspend
* @dev: our DRM device
*
* Save the state we need in order to be able to restore the interface
* upon resume from suspend
*/
static int psb_save_display_registers(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
struct drm_crtc *crtc;
struct drm_connector *connector;
/* Display arbitration control + watermarks */
dev_priv->saveDSPARB = PSB_RVDC32(DSPARB);
dev_priv->saveDSPFW1 = PSB_RVDC32(DSPFW1);
dev_priv->saveDSPFW2 = PSB_RVDC32(DSPFW2);
dev_priv->saveDSPFW3 = PSB_RVDC32(DSPFW3);
dev_priv->saveDSPFW4 = PSB_RVDC32(DSPFW4);
dev_priv->saveDSPFW5 = PSB_RVDC32(DSPFW5);
dev_priv->saveDSPFW6 = PSB_RVDC32(DSPFW6);
dev_priv->saveCHICKENBIT = PSB_RVDC32(DSPCHICKENBIT);
/* Save crtc and output state */
mutex_lock(&dev->mode_config.mutex);
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
if (drm_helper_crtc_in_use(crtc))
crtc->funcs->save(crtc);
}
list_for_each_entry(connector, &dev->mode_config.connector_list, head)
connector->funcs->save(connector);
mutex_unlock(&dev->mode_config.mutex);
return 0;
}
/**
* psb_restore_display_registers - restore lost register state
* @dev: our DRM device
*
* Restore register state that was lost during suspend and resume.
*/
static int psb_restore_display_registers(struct drm_device *dev)
{
struct drm_psb_private *dev_priv = dev->dev_private;
struct drm_crtc *crtc;
struct drm_connector *connector;
int pp_stat;
/* Display arbitration + watermarks */
PSB_WVDC32(dev_priv->saveDSPARB, DSPARB);
PSB_WVDC32(dev_priv->saveDSPFW1, DSPFW1);
PSB_WVDC32(dev_priv->saveDSPFW2, DSPFW2);
PSB_WVDC32(dev_priv->saveDSPFW3, DSPFW3);
PSB_WVDC32(dev_priv->saveDSPFW4, DSPFW4);
PSB_WVDC32(dev_priv->saveDSPFW5, DSPFW5);
PSB_WVDC32(dev_priv->saveDSPFW6, DSPFW6);
PSB_WVDC32(dev_priv->saveCHICKENBIT, DSPCHICKENBIT);
/*make sure VGA plane is off. it initializes to on after reset!*/
PSB_WVDC32(0x80000000, VGACNTRL);
mutex_lock(&dev->mode_config.mutex);
list_for_each_entry(crtc, &dev->mode_config.crtc_list, head)
if (drm_helper_crtc_in_use(crtc))
crtc->funcs->restore(crtc);
list_for_each_entry(connector, &dev->mode_config.connector_list, head)
connector->funcs->restore(connector);
mutex_unlock(&dev->mode_config.mutex);
if (dev_priv->iLVDS_enable) {
/*shutdown the panel*/
PSB_WVDC32(0, PP_CONTROL);
do {
pp_stat = PSB_RVDC32(PP_STATUS);
} while (pp_stat & 0x80000000);
/* Turn off the plane */
PSB_WVDC32(0x58000000, DSPACNTR);
PSB_WVDC32(0, DSPASURF);/*trigger the plane disable*/
/* Wait ~4 ticks */
msleep(4);
/* Turn off pipe */
PSB_WVDC32(0x0, PIPEACONF);
/* Wait ~8 ticks */
msleep(8);
/* Turn off PLLs */
PSB_WVDC32(0, MRST_DPLL_A);
} else {
PSB_WVDC32(DPI_SHUT_DOWN, DPI_CONTROL_REG);
PSB_WVDC32(0x0, PIPEACONF);
PSB_WVDC32(0x2faf0000, BLC_PWM_CTL);
while (REG_READ(0x70008) & 0x40000000)
cpu_relax();
while ((PSB_RVDC32(GEN_FIFO_STAT_REG) & DPI_FIFO_EMPTY)
!= DPI_FIFO_EMPTY)
cpu_relax();
PSB_WVDC32(0, DEVICE_READY_REG);
}
return 0;
}
static int psb_power_down(struct drm_device *dev)
{
return 0;
}
static int psb_power_up(struct drm_device *dev)
{
return 0;
}
static void psb_get_core_freq(struct drm_device *dev)
{
uint32_t clock;
struct pci_dev *pci_root = pci_get_bus_and_slot(0, 0);
struct drm_psb_private *dev_priv = dev->dev_private;
/*pci_write_config_dword(pci_root, 0xD4, 0x00C32004);*/
/*pci_write_config_dword(pci_root, 0xD0, 0xE0033000);*/
pci_write_config_dword(pci_root, 0xD0, 0xD0050300);
pci_read_config_dword(pci_root, 0xD4, &clock);
pci_dev_put(pci_root);
switch (clock & 0x07) {
case 0:
dev_priv->core_freq = 100;
break;
case 1:
dev_priv->core_freq = 133;
break;
case 2:
dev_priv->core_freq = 150;
break;
case 3:
dev_priv->core_freq = 178;
break;
case 4:
dev_priv->core_freq = 200;
break;
case 5:
case 6:
case 7:
dev_priv->core_freq = 266;
default:
dev_priv->core_freq = 0;
}
}
static int psb_chip_setup(struct drm_device *dev)
{
psb_get_core_freq(dev);
gma_intel_opregion_init(dev);
psb_intel_init_bios(dev);
return 0;
}
const struct psb_ops psb_chip_ops = {
.name = "Poulsbo",
.accel_2d = 1,
.pipes = 2,
.crtcs = 2,
.sgx_offset = PSB_SGX_OFFSET,
.chip_setup = psb_chip_setup,
.crtc_helper = &psb_intel_helper_funcs,
.crtc_funcs = &psb_intel_crtc_funcs,
.output_init = psb_output_init,
#ifdef CONFIG_BACKLIGHT_CLASS_DEVICE
.backlight_init = psb_backlight_init,
#endif
.init_pm = psb_init_pm,
.save_regs = psb_save_display_registers,
.restore_regs = psb_restore_display_registers,
.power_down = psb_power_down,
.power_up = psb_power_up,
};
| gpl-2.0 |
fxs007/linux | drivers/net/can/sja1000/peak_pci.c | 1159 | 20171 | /*
* Copyright (C) 2007, 2011 Wolfgang Grandegger <wg@grandegger.com>
* Copyright (C) 2012 Stephane Grosjean <s.grosjean@peak-system.com>
*
* Derived from the PCAN project file driver/src/pcan_pci.c:
*
* Copyright (C) 2001-2006 PEAK System-Technik GmbH
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the 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.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/can.h>
#include <linux/can/dev.h>
#include "sja1000.h"
MODULE_AUTHOR("Stephane Grosjean <s.grosjean@peak-system.com>");
MODULE_DESCRIPTION("Socket-CAN driver for PEAK PCAN PCI family cards");
MODULE_SUPPORTED_DEVICE("PEAK PCAN PCI/PCIe/PCIeC miniPCI CAN cards");
MODULE_SUPPORTED_DEVICE("PEAK PCAN miniPCIe/cPCI PC/104+ PCI/104e CAN Cards");
MODULE_LICENSE("GPL v2");
#define DRV_NAME "peak_pci"
struct peak_pciec_card;
struct peak_pci_chan {
void __iomem *cfg_base; /* Common for all channels */
struct net_device *prev_dev; /* Chain of network devices */
u16 icr_mask; /* Interrupt mask for fast ack */
struct peak_pciec_card *pciec_card; /* only for PCIeC LEDs */
};
#define PEAK_PCI_CAN_CLOCK (16000000 / 2)
#define PEAK_PCI_CDR (CDR_CBP | CDR_CLKOUT_MASK)
#define PEAK_PCI_OCR OCR_TX0_PUSHPULL
/*
* Important PITA registers
*/
#define PITA_ICR 0x00 /* Interrupt control register */
#define PITA_GPIOICR 0x18 /* GPIO interface control register */
#define PITA_MISC 0x1C /* Miscellaneous register */
#define PEAK_PCI_CFG_SIZE 0x1000 /* Size of the config PCI bar */
#define PEAK_PCI_CHAN_SIZE 0x0400 /* Size used by the channel */
#define PEAK_PCI_VENDOR_ID 0x001C /* The PCI device and vendor IDs */
#define PEAK_PCI_DEVICE_ID 0x0001 /* for PCI/PCIe slot cards */
#define PEAK_PCIEC_DEVICE_ID 0x0002 /* for ExpressCard slot cards */
#define PEAK_PCIE_DEVICE_ID 0x0003 /* for nextgen PCIe slot cards */
#define PEAK_CPCI_DEVICE_ID 0x0004 /* for nextgen cPCI slot cards */
#define PEAK_MPCI_DEVICE_ID 0x0005 /* for nextgen miniPCI slot cards */
#define PEAK_PC_104P_DEVICE_ID 0x0006 /* PCAN-PC/104+ cards */
#define PEAK_PCI_104E_DEVICE_ID 0x0007 /* PCAN-PCI/104 Express cards */
#define PEAK_MPCIE_DEVICE_ID 0x0008 /* The miniPCIe slot cards */
#define PEAK_PCIE_OEM_ID 0x0009 /* PCAN-PCI Express OEM */
#define PEAK_PCIEC34_DEVICE_ID 0x000A /* PCAN-PCI Express 34 (one channel) */
#define PEAK_PCI_CHAN_MAX 4
static const u16 peak_pci_icr_masks[PEAK_PCI_CHAN_MAX] = {
0x02, 0x01, 0x40, 0x80
};
static const struct pci_device_id peak_pci_tbl[] = {
{PEAK_PCI_VENDOR_ID, PEAK_PCI_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
{PEAK_PCI_VENDOR_ID, PEAK_PCIE_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
{PEAK_PCI_VENDOR_ID, PEAK_MPCI_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
{PEAK_PCI_VENDOR_ID, PEAK_MPCIE_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
{PEAK_PCI_VENDOR_ID, PEAK_PC_104P_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
{PEAK_PCI_VENDOR_ID, PEAK_PCI_104E_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
{PEAK_PCI_VENDOR_ID, PEAK_CPCI_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
#ifdef CONFIG_CAN_PEAK_PCIEC
{PEAK_PCI_VENDOR_ID, PEAK_PCIEC_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
{PEAK_PCI_VENDOR_ID, PEAK_PCIEC34_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
#endif
{0,}
};
MODULE_DEVICE_TABLE(pci, peak_pci_tbl);
#ifdef CONFIG_CAN_PEAK_PCIEC
/*
* PCAN-ExpressCard needs I2C bit-banging configuration option.
*/
/* GPIOICR byte access offsets */
#define PITA_GPOUT 0x18 /* GPx output value */
#define PITA_GPIN 0x19 /* GPx input value */
#define PITA_GPOEN 0x1A /* configure GPx as ouput pin */
/* I2C GP bits */
#define PITA_GPIN_SCL 0x01 /* Serial Clock Line */
#define PITA_GPIN_SDA 0x04 /* Serial DAta line */
#define PCA9553_1_SLAVEADDR (0xC4 >> 1)
/* PCA9553 LS0 fields values */
enum {
PCA9553_LOW,
PCA9553_HIGHZ,
PCA9553_PWM0,
PCA9553_PWM1
};
/* LEDs control */
#define PCA9553_ON PCA9553_LOW
#define PCA9553_OFF PCA9553_HIGHZ
#define PCA9553_SLOW PCA9553_PWM0
#define PCA9553_FAST PCA9553_PWM1
#define PCA9553_LED(c) (1 << (c))
#define PCA9553_LED_STATE(s, c) ((s) << ((c) << 1))
#define PCA9553_LED_ON(c) PCA9553_LED_STATE(PCA9553_ON, c)
#define PCA9553_LED_OFF(c) PCA9553_LED_STATE(PCA9553_OFF, c)
#define PCA9553_LED_SLOW(c) PCA9553_LED_STATE(PCA9553_SLOW, c)
#define PCA9553_LED_FAST(c) PCA9553_LED_STATE(PCA9553_FAST, c)
#define PCA9553_LED_MASK(c) PCA9553_LED_STATE(0x03, c)
#define PCA9553_LED_OFF_ALL (PCA9553_LED_OFF(0) | PCA9553_LED_OFF(1))
#define PCA9553_LS0_INIT 0x40 /* initial value (!= from 0x00) */
struct peak_pciec_chan {
struct net_device *netdev;
unsigned long prev_rx_bytes;
unsigned long prev_tx_bytes;
};
struct peak_pciec_card {
void __iomem *cfg_base; /* Common for all channels */
void __iomem *reg_base; /* first channel base address */
u8 led_cache; /* leds state cache */
/* PCIExpressCard i2c data */
struct i2c_algo_bit_data i2c_bit;
struct i2c_adapter led_chip;
struct delayed_work led_work; /* led delayed work */
int chan_count;
struct peak_pciec_chan channel[PEAK_PCI_CHAN_MAX];
};
/* "normal" pci register write callback is overloaded for leds control */
static void peak_pci_write_reg(const struct sja1000_priv *priv,
int port, u8 val);
static inline void pita_set_scl_highz(struct peak_pciec_card *card)
{
u8 gp_outen = readb(card->cfg_base + PITA_GPOEN) & ~PITA_GPIN_SCL;
writeb(gp_outen, card->cfg_base + PITA_GPOEN);
}
static inline void pita_set_sda_highz(struct peak_pciec_card *card)
{
u8 gp_outen = readb(card->cfg_base + PITA_GPOEN) & ~PITA_GPIN_SDA;
writeb(gp_outen, card->cfg_base + PITA_GPOEN);
}
static void peak_pciec_init_pita_gpio(struct peak_pciec_card *card)
{
/* raise SCL & SDA GPIOs to high-Z */
pita_set_scl_highz(card);
pita_set_sda_highz(card);
}
static void pita_setsda(void *data, int state)
{
struct peak_pciec_card *card = (struct peak_pciec_card *)data;
u8 gp_out, gp_outen;
/* set output sda always to 0 */
gp_out = readb(card->cfg_base + PITA_GPOUT) & ~PITA_GPIN_SDA;
writeb(gp_out, card->cfg_base + PITA_GPOUT);
/* control output sda with GPOEN */
gp_outen = readb(card->cfg_base + PITA_GPOEN);
if (state)
gp_outen &= ~PITA_GPIN_SDA;
else
gp_outen |= PITA_GPIN_SDA;
writeb(gp_outen, card->cfg_base + PITA_GPOEN);
}
static void pita_setscl(void *data, int state)
{
struct peak_pciec_card *card = (struct peak_pciec_card *)data;
u8 gp_out, gp_outen;
/* set output scl always to 0 */
gp_out = readb(card->cfg_base + PITA_GPOUT) & ~PITA_GPIN_SCL;
writeb(gp_out, card->cfg_base + PITA_GPOUT);
/* control output scl with GPOEN */
gp_outen = readb(card->cfg_base + PITA_GPOEN);
if (state)
gp_outen &= ~PITA_GPIN_SCL;
else
gp_outen |= PITA_GPIN_SCL;
writeb(gp_outen, card->cfg_base + PITA_GPOEN);
}
static int pita_getsda(void *data)
{
struct peak_pciec_card *card = (struct peak_pciec_card *)data;
/* set tristate */
pita_set_sda_highz(card);
return (readb(card->cfg_base + PITA_GPIN) & PITA_GPIN_SDA) ? 1 : 0;
}
static int pita_getscl(void *data)
{
struct peak_pciec_card *card = (struct peak_pciec_card *)data;
/* set tristate */
pita_set_scl_highz(card);
return (readb(card->cfg_base + PITA_GPIN) & PITA_GPIN_SCL) ? 1 : 0;
}
/*
* write commands to the LED chip though the I2C-bus of the PCAN-PCIeC
*/
static int peak_pciec_write_pca9553(struct peak_pciec_card *card,
u8 offset, u8 data)
{
u8 buffer[2] = {
offset,
data
};
struct i2c_msg msg = {
.addr = PCA9553_1_SLAVEADDR,
.len = 2,
.buf = buffer,
};
int ret;
/* cache led mask */
if ((offset == 5) && (data == card->led_cache))
return 0;
ret = i2c_transfer(&card->led_chip, &msg, 1);
if (ret < 0)
return ret;
if (offset == 5)
card->led_cache = data;
return 0;
}
/*
* delayed work callback used to control the LEDs
*/
static void peak_pciec_led_work(struct work_struct *work)
{
struct peak_pciec_card *card =
container_of(work, struct peak_pciec_card, led_work.work);
struct net_device *netdev;
u8 new_led = card->led_cache;
int i, up_count = 0;
/* first check what is to do */
for (i = 0; i < card->chan_count; i++) {
/* default is: not configured */
new_led &= ~PCA9553_LED_MASK(i);
new_led |= PCA9553_LED_ON(i);
netdev = card->channel[i].netdev;
if (!netdev || !(netdev->flags & IFF_UP))
continue;
up_count++;
/* no activity (but configured) */
new_led &= ~PCA9553_LED_MASK(i);
new_led |= PCA9553_LED_SLOW(i);
/* if bytes counters changed, set fast blinking led */
if (netdev->stats.rx_bytes != card->channel[i].prev_rx_bytes) {
card->channel[i].prev_rx_bytes = netdev->stats.rx_bytes;
new_led &= ~PCA9553_LED_MASK(i);
new_led |= PCA9553_LED_FAST(i);
}
if (netdev->stats.tx_bytes != card->channel[i].prev_tx_bytes) {
card->channel[i].prev_tx_bytes = netdev->stats.tx_bytes;
new_led &= ~PCA9553_LED_MASK(i);
new_led |= PCA9553_LED_FAST(i);
}
}
/* check if LS0 settings changed, only update i2c if so */
peak_pciec_write_pca9553(card, 5, new_led);
/* restart timer (except if no more configured channels) */
if (up_count)
schedule_delayed_work(&card->led_work, HZ);
}
/*
* set LEDs blinking state
*/
static void peak_pciec_set_leds(struct peak_pciec_card *card, u8 led_mask, u8 s)
{
u8 new_led = card->led_cache;
int i;
/* first check what is to do */
for (i = 0; i < card->chan_count; i++)
if (led_mask & PCA9553_LED(i)) {
new_led &= ~PCA9553_LED_MASK(i);
new_led |= PCA9553_LED_STATE(s, i);
}
/* check if LS0 settings changed, only update i2c if so */
peak_pciec_write_pca9553(card, 5, new_led);
}
/*
* start one second delayed work to control LEDs
*/
static void peak_pciec_start_led_work(struct peak_pciec_card *card)
{
schedule_delayed_work(&card->led_work, HZ);
}
/*
* stop LEDs delayed work
*/
static void peak_pciec_stop_led_work(struct peak_pciec_card *card)
{
cancel_delayed_work_sync(&card->led_work);
}
/*
* initialize the PCA9553 4-bit I2C-bus LED chip
*/
static int peak_pciec_init_leds(struct peak_pciec_card *card)
{
int err;
/* prescaler for frequency 0: "SLOW" = 1 Hz = "44" */
err = peak_pciec_write_pca9553(card, 1, 44 / 1);
if (err)
return err;
/* duty cycle 0: 50% */
err = peak_pciec_write_pca9553(card, 2, 0x80);
if (err)
return err;
/* prescaler for frequency 1: "FAST" = 5 Hz */
err = peak_pciec_write_pca9553(card, 3, 44 / 5);
if (err)
return err;
/* duty cycle 1: 50% */
err = peak_pciec_write_pca9553(card, 4, 0x80);
if (err)
return err;
/* switch LEDs to initial state */
return peak_pciec_write_pca9553(card, 5, PCA9553_LS0_INIT);
}
/*
* restore LEDs state to off peak_pciec_leds_exit
*/
static void peak_pciec_leds_exit(struct peak_pciec_card *card)
{
/* switch LEDs to off */
peak_pciec_write_pca9553(card, 5, PCA9553_LED_OFF_ALL);
}
/*
* normal write sja1000 register method overloaded to catch when controller
* is started or stopped, to control leds
*/
static void peak_pciec_write_reg(const struct sja1000_priv *priv,
int port, u8 val)
{
struct peak_pci_chan *chan = priv->priv;
struct peak_pciec_card *card = chan->pciec_card;
int c = (priv->reg_base - card->reg_base) / PEAK_PCI_CHAN_SIZE;
/* sja1000 register changes control the leds state */
if (port == SJA1000_MOD)
switch (val) {
case MOD_RM:
/* Reset Mode: set led on */
peak_pciec_set_leds(card, PCA9553_LED(c), PCA9553_ON);
break;
case 0x00:
/* Normal Mode: led slow blinking and start led timer */
peak_pciec_set_leds(card, PCA9553_LED(c), PCA9553_SLOW);
peak_pciec_start_led_work(card);
break;
default:
break;
}
/* call base function */
peak_pci_write_reg(priv, port, val);
}
static struct i2c_algo_bit_data peak_pciec_i2c_bit_ops = {
.setsda = pita_setsda,
.setscl = pita_setscl,
.getsda = pita_getsda,
.getscl = pita_getscl,
.udelay = 10,
.timeout = HZ,
};
static int peak_pciec_probe(struct pci_dev *pdev, struct net_device *dev)
{
struct sja1000_priv *priv = netdev_priv(dev);
struct peak_pci_chan *chan = priv->priv;
struct peak_pciec_card *card;
int err;
/* copy i2c object address from 1st channel */
if (chan->prev_dev) {
struct sja1000_priv *prev_priv = netdev_priv(chan->prev_dev);
struct peak_pci_chan *prev_chan = prev_priv->priv;
card = prev_chan->pciec_card;
if (!card)
return -ENODEV;
/* channel is the first one: do the init part */
} else {
/* create the bit banging I2C adapter structure */
card = kzalloc(sizeof(struct peak_pciec_card), GFP_KERNEL);
if (!card)
return -ENOMEM;
card->cfg_base = chan->cfg_base;
card->reg_base = priv->reg_base;
card->led_chip.owner = THIS_MODULE;
card->led_chip.dev.parent = &pdev->dev;
card->led_chip.algo_data = &card->i2c_bit;
strncpy(card->led_chip.name, "peak_i2c",
sizeof(card->led_chip.name));
card->i2c_bit = peak_pciec_i2c_bit_ops;
card->i2c_bit.udelay = 10;
card->i2c_bit.timeout = HZ;
card->i2c_bit.data = card;
peak_pciec_init_pita_gpio(card);
err = i2c_bit_add_bus(&card->led_chip);
if (err) {
dev_err(&pdev->dev, "i2c init failed\n");
goto pciec_init_err_1;
}
err = peak_pciec_init_leds(card);
if (err) {
dev_err(&pdev->dev, "leds hardware init failed\n");
goto pciec_init_err_2;
}
INIT_DELAYED_WORK(&card->led_work, peak_pciec_led_work);
/* PCAN-ExpressCard needs its own callback for leds */
priv->write_reg = peak_pciec_write_reg;
}
chan->pciec_card = card;
card->channel[card->chan_count++].netdev = dev;
return 0;
pciec_init_err_2:
i2c_del_adapter(&card->led_chip);
pciec_init_err_1:
peak_pciec_init_pita_gpio(card);
kfree(card);
return err;
}
static void peak_pciec_remove(struct peak_pciec_card *card)
{
peak_pciec_stop_led_work(card);
peak_pciec_leds_exit(card);
i2c_del_adapter(&card->led_chip);
peak_pciec_init_pita_gpio(card);
kfree(card);
}
#else /* CONFIG_CAN_PEAK_PCIEC */
/*
* Placebo functions when PCAN-ExpressCard support is not selected
*/
static inline int peak_pciec_probe(struct pci_dev *pdev, struct net_device *dev)
{
return -ENODEV;
}
static inline void peak_pciec_remove(struct peak_pciec_card *card)
{
}
#endif /* CONFIG_CAN_PEAK_PCIEC */
static u8 peak_pci_read_reg(const struct sja1000_priv *priv, int port)
{
return readb(priv->reg_base + (port << 2));
}
static void peak_pci_write_reg(const struct sja1000_priv *priv,
int port, u8 val)
{
writeb(val, priv->reg_base + (port << 2));
}
static void peak_pci_post_irq(const struct sja1000_priv *priv)
{
struct peak_pci_chan *chan = priv->priv;
u16 icr;
/* Select and clear in PITA stored interrupt */
icr = readw(chan->cfg_base + PITA_ICR);
if (icr & chan->icr_mask)
writew(chan->icr_mask, chan->cfg_base + PITA_ICR);
}
static int peak_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct sja1000_priv *priv;
struct peak_pci_chan *chan;
struct net_device *dev, *prev_dev;
void __iomem *cfg_base, *reg_base;
u16 sub_sys_id, icr;
int i, err, channels;
err = pci_enable_device(pdev);
if (err)
return err;
err = pci_request_regions(pdev, DRV_NAME);
if (err)
goto failure_disable_pci;
err = pci_read_config_word(pdev, 0x2e, &sub_sys_id);
if (err)
goto failure_release_regions;
dev_dbg(&pdev->dev, "probing device %04x:%04x:%04x\n",
pdev->vendor, pdev->device, sub_sys_id);
err = pci_write_config_word(pdev, 0x44, 0);
if (err)
goto failure_release_regions;
if (sub_sys_id >= 12)
channels = 4;
else if (sub_sys_id >= 10)
channels = 3;
else if (sub_sys_id >= 4)
channels = 2;
else
channels = 1;
cfg_base = pci_iomap(pdev, 0, PEAK_PCI_CFG_SIZE);
if (!cfg_base) {
dev_err(&pdev->dev, "failed to map PCI resource #0\n");
err = -ENOMEM;
goto failure_release_regions;
}
reg_base = pci_iomap(pdev, 1, PEAK_PCI_CHAN_SIZE * channels);
if (!reg_base) {
dev_err(&pdev->dev, "failed to map PCI resource #1\n");
err = -ENOMEM;
goto failure_unmap_cfg_base;
}
/* Set GPIO control register */
writew(0x0005, cfg_base + PITA_GPIOICR + 2);
/* Enable all channels of this card */
writeb(0x00, cfg_base + PITA_GPIOICR);
/* Toggle reset */
writeb(0x05, cfg_base + PITA_MISC + 3);
mdelay(5);
/* Leave parport mux mode */
writeb(0x04, cfg_base + PITA_MISC + 3);
icr = readw(cfg_base + PITA_ICR + 2);
for (i = 0; i < channels; i++) {
dev = alloc_sja1000dev(sizeof(struct peak_pci_chan));
if (!dev) {
err = -ENOMEM;
goto failure_remove_channels;
}
priv = netdev_priv(dev);
chan = priv->priv;
chan->cfg_base = cfg_base;
priv->reg_base = reg_base + i * PEAK_PCI_CHAN_SIZE;
priv->read_reg = peak_pci_read_reg;
priv->write_reg = peak_pci_write_reg;
priv->post_irq = peak_pci_post_irq;
priv->can.clock.freq = PEAK_PCI_CAN_CLOCK;
priv->ocr = PEAK_PCI_OCR;
priv->cdr = PEAK_PCI_CDR;
/* Neither a slave nor a single device distributes the clock */
if (channels == 1 || i > 0)
priv->cdr |= CDR_CLK_OFF;
/* Setup interrupt handling */
priv->irq_flags = IRQF_SHARED;
dev->irq = pdev->irq;
chan->icr_mask = peak_pci_icr_masks[i];
icr |= chan->icr_mask;
SET_NETDEV_DEV(dev, &pdev->dev);
dev->dev_id = i;
/* Create chain of SJA1000 devices */
chan->prev_dev = pci_get_drvdata(pdev);
pci_set_drvdata(pdev, dev);
/*
* PCAN-ExpressCard needs some additional i2c init.
* This must be done *before* register_sja1000dev() but
* *after* devices linkage
*/
if (pdev->device == PEAK_PCIEC_DEVICE_ID ||
pdev->device == PEAK_PCIEC34_DEVICE_ID) {
err = peak_pciec_probe(pdev, dev);
if (err) {
dev_err(&pdev->dev,
"failed to probe device (err %d)\n",
err);
goto failure_free_dev;
}
}
err = register_sja1000dev(dev);
if (err) {
dev_err(&pdev->dev, "failed to register device\n");
goto failure_free_dev;
}
dev_info(&pdev->dev,
"%s at reg_base=0x%p cfg_base=0x%p irq=%d\n",
dev->name, priv->reg_base, chan->cfg_base, dev->irq);
}
/* Enable interrupts */
writew(icr, cfg_base + PITA_ICR + 2);
return 0;
failure_free_dev:
pci_set_drvdata(pdev, chan->prev_dev);
free_sja1000dev(dev);
failure_remove_channels:
/* Disable interrupts */
writew(0x0, cfg_base + PITA_ICR + 2);
chan = NULL;
for (dev = pci_get_drvdata(pdev); dev; dev = prev_dev) {
priv = netdev_priv(dev);
chan = priv->priv;
prev_dev = chan->prev_dev;
unregister_sja1000dev(dev);
free_sja1000dev(dev);
}
/* free any PCIeC resources too */
if (chan && chan->pciec_card)
peak_pciec_remove(chan->pciec_card);
pci_iounmap(pdev, reg_base);
failure_unmap_cfg_base:
pci_iounmap(pdev, cfg_base);
failure_release_regions:
pci_release_regions(pdev);
failure_disable_pci:
pci_disable_device(pdev);
return err;
}
static void peak_pci_remove(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev); /* Last device */
struct sja1000_priv *priv = netdev_priv(dev);
struct peak_pci_chan *chan = priv->priv;
void __iomem *cfg_base = chan->cfg_base;
void __iomem *reg_base = priv->reg_base;
/* Disable interrupts */
writew(0x0, cfg_base + PITA_ICR + 2);
/* Loop over all registered devices */
while (1) {
struct net_device *prev_dev = chan->prev_dev;
dev_info(&pdev->dev, "removing device %s\n", dev->name);
unregister_sja1000dev(dev);
free_sja1000dev(dev);
dev = prev_dev;
if (!dev) {
/* do that only for first channel */
if (chan->pciec_card)
peak_pciec_remove(chan->pciec_card);
break;
}
priv = netdev_priv(dev);
chan = priv->priv;
}
pci_iounmap(pdev, reg_base);
pci_iounmap(pdev, cfg_base);
pci_release_regions(pdev);
pci_disable_device(pdev);
}
static struct pci_driver peak_pci_driver = {
.name = DRV_NAME,
.id_table = peak_pci_tbl,
.probe = peak_pci_probe,
.remove = peak_pci_remove,
};
module_pci_driver(peak_pci_driver);
| gpl-2.0 |
talnoah/m8 | drivers/iommu/intr_remapping.c | 3719 | 18273 | #include <linux/interrupt.h>
#include <linux/dmar.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/hpet.h>
#include <linux/pci.h>
#include <linux/irq.h>
#include <asm/io_apic.h>
#include <asm/smp.h>
#include <asm/cpu.h>
#include <linux/intel-iommu.h>
#include "intr_remapping.h"
#include <acpi/acpi.h>
#include <asm/pci-direct.h>
static struct ioapic_scope ir_ioapic[MAX_IO_APICS];
static struct hpet_scope ir_hpet[MAX_HPET_TBS];
static int ir_ioapic_num, ir_hpet_num;
int intr_remapping_enabled;
static int disable_intremap;
static int disable_sourceid_checking;
static int no_x2apic_optout;
static __init int setup_nointremap(char *str)
{
disable_intremap = 1;
return 0;
}
early_param("nointremap", setup_nointremap);
static __init int setup_intremap(char *str)
{
if (!str)
return -EINVAL;
while (*str) {
if (!strncmp(str, "on", 2))
disable_intremap = 0;
else if (!strncmp(str, "off", 3))
disable_intremap = 1;
else if (!strncmp(str, "nosid", 5))
disable_sourceid_checking = 1;
else if (!strncmp(str, "no_x2apic_optout", 16))
no_x2apic_optout = 1;
str += strcspn(str, ",");
while (*str == ',')
str++;
}
return 0;
}
early_param("intremap", setup_intremap);
static DEFINE_RAW_SPINLOCK(irq_2_ir_lock);
static struct irq_2_iommu *irq_2_iommu(unsigned int irq)
{
struct irq_cfg *cfg = irq_get_chip_data(irq);
return cfg ? &cfg->irq_2_iommu : NULL;
}
int get_irte(int irq, struct irte *entry)
{
struct irq_2_iommu *irq_iommu = irq_2_iommu(irq);
unsigned long flags;
int index;
if (!entry || !irq_iommu)
return -1;
raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
index = irq_iommu->irte_index + irq_iommu->sub_handle;
*entry = *(irq_iommu->iommu->ir_table->base + index);
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
return 0;
}
int alloc_irte(struct intel_iommu *iommu, int irq, u16 count)
{
struct ir_table *table = iommu->ir_table;
struct irq_2_iommu *irq_iommu = irq_2_iommu(irq);
u16 index, start_index;
unsigned int mask = 0;
unsigned long flags;
int i;
if (!count || !irq_iommu)
return -1;
/*
* start the IRTE search from index 0.
*/
index = start_index = 0;
if (count > 1) {
count = __roundup_pow_of_two(count);
mask = ilog2(count);
}
if (mask > ecap_max_handle_mask(iommu->ecap)) {
printk(KERN_ERR
"Requested mask %x exceeds the max invalidation handle"
" mask value %Lx\n", mask,
ecap_max_handle_mask(iommu->ecap));
return -1;
}
raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
do {
for (i = index; i < index + count; i++)
if (table->base[i].present)
break;
/* empty index found */
if (i == index + count)
break;
index = (index + count) % INTR_REMAP_TABLE_ENTRIES;
if (index == start_index) {
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
printk(KERN_ERR "can't allocate an IRTE\n");
return -1;
}
} while (1);
for (i = index; i < index + count; i++)
table->base[i].present = 1;
irq_iommu->iommu = iommu;
irq_iommu->irte_index = index;
irq_iommu->sub_handle = 0;
irq_iommu->irte_mask = mask;
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
return index;
}
static int qi_flush_iec(struct intel_iommu *iommu, int index, int mask)
{
struct qi_desc desc;
desc.low = QI_IEC_IIDEX(index) | QI_IEC_TYPE | QI_IEC_IM(mask)
| QI_IEC_SELECTIVE;
desc.high = 0;
return qi_submit_sync(&desc, iommu);
}
int map_irq_to_irte_handle(int irq, u16 *sub_handle)
{
struct irq_2_iommu *irq_iommu = irq_2_iommu(irq);
unsigned long flags;
int index;
if (!irq_iommu)
return -1;
raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
*sub_handle = irq_iommu->sub_handle;
index = irq_iommu->irte_index;
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
return index;
}
int set_irte_irq(int irq, struct intel_iommu *iommu, u16 index, u16 subhandle)
{
struct irq_2_iommu *irq_iommu = irq_2_iommu(irq);
unsigned long flags;
if (!irq_iommu)
return -1;
raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
irq_iommu->iommu = iommu;
irq_iommu->irte_index = index;
irq_iommu->sub_handle = subhandle;
irq_iommu->irte_mask = 0;
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
return 0;
}
int modify_irte(int irq, struct irte *irte_modified)
{
struct irq_2_iommu *irq_iommu = irq_2_iommu(irq);
struct intel_iommu *iommu;
unsigned long flags;
struct irte *irte;
int rc, index;
if (!irq_iommu)
return -1;
raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
iommu = irq_iommu->iommu;
index = irq_iommu->irte_index + irq_iommu->sub_handle;
irte = &iommu->ir_table->base[index];
set_64bit(&irte->low, irte_modified->low);
set_64bit(&irte->high, irte_modified->high);
__iommu_flush_cache(iommu, irte, sizeof(*irte));
rc = qi_flush_iec(iommu, index, 0);
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
return rc;
}
struct intel_iommu *map_hpet_to_ir(u8 hpet_id)
{
int i;
for (i = 0; i < MAX_HPET_TBS; i++)
if (ir_hpet[i].id == hpet_id)
return ir_hpet[i].iommu;
return NULL;
}
struct intel_iommu *map_ioapic_to_ir(int apic)
{
int i;
for (i = 0; i < MAX_IO_APICS; i++)
if (ir_ioapic[i].id == apic)
return ir_ioapic[i].iommu;
return NULL;
}
struct intel_iommu *map_dev_to_ir(struct pci_dev *dev)
{
struct dmar_drhd_unit *drhd;
drhd = dmar_find_matched_drhd_unit(dev);
if (!drhd)
return NULL;
return drhd->iommu;
}
static int clear_entries(struct irq_2_iommu *irq_iommu)
{
struct irte *start, *entry, *end;
struct intel_iommu *iommu;
int index;
if (irq_iommu->sub_handle)
return 0;
iommu = irq_iommu->iommu;
index = irq_iommu->irte_index + irq_iommu->sub_handle;
start = iommu->ir_table->base + index;
end = start + (1 << irq_iommu->irte_mask);
for (entry = start; entry < end; entry++) {
set_64bit(&entry->low, 0);
set_64bit(&entry->high, 0);
}
return qi_flush_iec(iommu, index, irq_iommu->irte_mask);
}
int free_irte(int irq)
{
struct irq_2_iommu *irq_iommu = irq_2_iommu(irq);
unsigned long flags;
int rc;
if (!irq_iommu)
return -1;
raw_spin_lock_irqsave(&irq_2_ir_lock, flags);
rc = clear_entries(irq_iommu);
irq_iommu->iommu = NULL;
irq_iommu->irte_index = 0;
irq_iommu->sub_handle = 0;
irq_iommu->irte_mask = 0;
raw_spin_unlock_irqrestore(&irq_2_ir_lock, flags);
return rc;
}
/*
* source validation type
*/
#define SVT_NO_VERIFY 0x0 /* no verification is required */
#define SVT_VERIFY_SID_SQ 0x1 /* verify using SID and SQ fields */
#define SVT_VERIFY_BUS 0x2 /* verify bus of request-id */
/*
* source-id qualifier
*/
#define SQ_ALL_16 0x0 /* verify all 16 bits of request-id */
#define SQ_13_IGNORE_1 0x1 /* verify most significant 13 bits, ignore
* the third least significant bit
*/
#define SQ_13_IGNORE_2 0x2 /* verify most significant 13 bits, ignore
* the second and third least significant bits
*/
#define SQ_13_IGNORE_3 0x3 /* verify most significant 13 bits, ignore
* the least three significant bits
*/
/*
* set SVT, SQ and SID fields of irte to verify
* source ids of interrupt requests
*/
static void set_irte_sid(struct irte *irte, unsigned int svt,
unsigned int sq, unsigned int sid)
{
if (disable_sourceid_checking)
svt = SVT_NO_VERIFY;
irte->svt = svt;
irte->sq = sq;
irte->sid = sid;
}
int set_ioapic_sid(struct irte *irte, int apic)
{
int i;
u16 sid = 0;
if (!irte)
return -1;
for (i = 0; i < MAX_IO_APICS; i++) {
if (ir_ioapic[i].id == apic) {
sid = (ir_ioapic[i].bus << 8) | ir_ioapic[i].devfn;
break;
}
}
if (sid == 0) {
pr_warning("Failed to set source-id of IOAPIC (%d)\n", apic);
return -1;
}
set_irte_sid(irte, 1, 0, sid);
return 0;
}
int set_hpet_sid(struct irte *irte, u8 id)
{
int i;
u16 sid = 0;
if (!irte)
return -1;
for (i = 0; i < MAX_HPET_TBS; i++) {
if (ir_hpet[i].id == id) {
sid = (ir_hpet[i].bus << 8) | ir_hpet[i].devfn;
break;
}
}
if (sid == 0) {
pr_warning("Failed to set source-id of HPET block (%d)\n", id);
return -1;
}
/*
* Should really use SQ_ALL_16. Some platforms are broken.
* While we figure out the right quirks for these broken platforms, use
* SQ_13_IGNORE_3 for now.
*/
set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_13_IGNORE_3, sid);
return 0;
}
int set_msi_sid(struct irte *irte, struct pci_dev *dev)
{
struct pci_dev *bridge;
if (!irte || !dev)
return -1;
/* PCIe device or Root Complex integrated PCI device */
if (pci_is_pcie(dev) || !dev->bus->parent) {
set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_ALL_16,
(dev->bus->number << 8) | dev->devfn);
return 0;
}
bridge = pci_find_upstream_pcie_bridge(dev);
if (bridge) {
if (pci_is_pcie(bridge))/* this is a PCIe-to-PCI/PCIX bridge */
set_irte_sid(irte, SVT_VERIFY_BUS, SQ_ALL_16,
(bridge->bus->number << 8) | dev->bus->number);
else /* this is a legacy PCI bridge */
set_irte_sid(irte, SVT_VERIFY_SID_SQ, SQ_ALL_16,
(bridge->bus->number << 8) | bridge->devfn);
}
return 0;
}
static void iommu_set_intr_remapping(struct intel_iommu *iommu, int mode)
{
u64 addr;
u32 sts;
unsigned long flags;
addr = virt_to_phys((void *)iommu->ir_table->base);
raw_spin_lock_irqsave(&iommu->register_lock, flags);
dmar_writeq(iommu->reg + DMAR_IRTA_REG,
(addr) | IR_X2APIC_MODE(mode) | INTR_REMAP_TABLE_REG_SIZE);
/* Set interrupt-remapping table pointer */
iommu->gcmd |= DMA_GCMD_SIRTP;
writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, (sts & DMA_GSTS_IRTPS), sts);
raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
/*
* global invalidation of interrupt entry cache before enabling
* interrupt-remapping.
*/
qi_global_iec(iommu);
raw_spin_lock_irqsave(&iommu->register_lock, flags);
/* Enable interrupt-remapping */
iommu->gcmd |= DMA_GCMD_IRE;
writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, (sts & DMA_GSTS_IRES), sts);
raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
}
static int setup_intr_remapping(struct intel_iommu *iommu, int mode)
{
struct ir_table *ir_table;
struct page *pages;
ir_table = iommu->ir_table = kzalloc(sizeof(struct ir_table),
GFP_ATOMIC);
if (!iommu->ir_table)
return -ENOMEM;
pages = alloc_pages_node(iommu->node, GFP_ATOMIC | __GFP_ZERO,
INTR_REMAP_PAGE_ORDER);
if (!pages) {
printk(KERN_ERR "failed to allocate pages of order %d\n",
INTR_REMAP_PAGE_ORDER);
kfree(iommu->ir_table);
return -ENOMEM;
}
ir_table->base = page_address(pages);
iommu_set_intr_remapping(iommu, mode);
return 0;
}
/*
* Disable Interrupt Remapping.
*/
static void iommu_disable_intr_remapping(struct intel_iommu *iommu)
{
unsigned long flags;
u32 sts;
if (!ecap_ir_support(iommu->ecap))
return;
/*
* global invalidation of interrupt entry cache before disabling
* interrupt-remapping.
*/
qi_global_iec(iommu);
raw_spin_lock_irqsave(&iommu->register_lock, flags);
sts = dmar_readq(iommu->reg + DMAR_GSTS_REG);
if (!(sts & DMA_GSTS_IRES))
goto end;
iommu->gcmd &= ~DMA_GCMD_IRE;
writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
readl, !(sts & DMA_GSTS_IRES), sts);
end:
raw_spin_unlock_irqrestore(&iommu->register_lock, flags);
}
static int __init dmar_x2apic_optout(void)
{
struct acpi_table_dmar *dmar;
dmar = (struct acpi_table_dmar *)dmar_tbl;
if (!dmar || no_x2apic_optout)
return 0;
return dmar->flags & DMAR_X2APIC_OPT_OUT;
}
int __init intr_remapping_supported(void)
{
struct dmar_drhd_unit *drhd;
if (disable_intremap)
return 0;
if (!dmar_ir_support())
return 0;
for_each_drhd_unit(drhd) {
struct intel_iommu *iommu = drhd->iommu;
if (!ecap_ir_support(iommu->ecap))
return 0;
}
return 1;
}
int __init enable_intr_remapping(void)
{
struct dmar_drhd_unit *drhd;
int setup = 0;
int eim = 0;
if (parse_ioapics_under_ir() != 1) {
printk(KERN_INFO "Not enable interrupt remapping\n");
return -1;
}
if (x2apic_supported()) {
eim = !dmar_x2apic_optout();
WARN(!eim, KERN_WARNING
"Your BIOS is broken and requested that x2apic be disabled\n"
"This will leave your machine vulnerable to irq-injection attacks\n"
"Use 'intremap=no_x2apic_optout' to override BIOS request\n");
}
for_each_drhd_unit(drhd) {
struct intel_iommu *iommu = drhd->iommu;
/*
* If the queued invalidation is already initialized,
* shouldn't disable it.
*/
if (iommu->qi)
continue;
/*
* Clear previous faults.
*/
dmar_fault(-1, iommu);
/*
* Disable intr remapping and queued invalidation, if already
* enabled prior to OS handover.
*/
iommu_disable_intr_remapping(iommu);
dmar_disable_qi(iommu);
}
/*
* check for the Interrupt-remapping support
*/
for_each_drhd_unit(drhd) {
struct intel_iommu *iommu = drhd->iommu;
if (!ecap_ir_support(iommu->ecap))
continue;
if (eim && !ecap_eim_support(iommu->ecap)) {
printk(KERN_INFO "DRHD %Lx: EIM not supported by DRHD, "
" ecap %Lx\n", drhd->reg_base_addr, iommu->ecap);
return -1;
}
}
/*
* Enable queued invalidation for all the DRHD's.
*/
for_each_drhd_unit(drhd) {
int ret;
struct intel_iommu *iommu = drhd->iommu;
ret = dmar_enable_qi(iommu);
if (ret) {
printk(KERN_ERR "DRHD %Lx: failed to enable queued, "
" invalidation, ecap %Lx, ret %d\n",
drhd->reg_base_addr, iommu->ecap, ret);
return -1;
}
}
/*
* Setup Interrupt-remapping for all the DRHD's now.
*/
for_each_drhd_unit(drhd) {
struct intel_iommu *iommu = drhd->iommu;
if (!ecap_ir_support(iommu->ecap))
continue;
if (setup_intr_remapping(iommu, eim))
goto error;
setup = 1;
}
if (!setup)
goto error;
intr_remapping_enabled = 1;
pr_info("Enabled IRQ remapping in %s mode\n", eim ? "x2apic" : "xapic");
return eim ? IRQ_REMAP_X2APIC_MODE : IRQ_REMAP_XAPIC_MODE;
error:
/*
* handle error condition gracefully here!
*/
return -1;
}
static void ir_parse_one_hpet_scope(struct acpi_dmar_device_scope *scope,
struct intel_iommu *iommu)
{
struct acpi_dmar_pci_path *path;
u8 bus;
int count;
bus = scope->bus;
path = (struct acpi_dmar_pci_path *)(scope + 1);
count = (scope->length - sizeof(struct acpi_dmar_device_scope))
/ sizeof(struct acpi_dmar_pci_path);
while (--count > 0) {
/*
* Access PCI directly due to the PCI
* subsystem isn't initialized yet.
*/
bus = read_pci_config_byte(bus, path->dev, path->fn,
PCI_SECONDARY_BUS);
path++;
}
ir_hpet[ir_hpet_num].bus = bus;
ir_hpet[ir_hpet_num].devfn = PCI_DEVFN(path->dev, path->fn);
ir_hpet[ir_hpet_num].iommu = iommu;
ir_hpet[ir_hpet_num].id = scope->enumeration_id;
ir_hpet_num++;
}
static void ir_parse_one_ioapic_scope(struct acpi_dmar_device_scope *scope,
struct intel_iommu *iommu)
{
struct acpi_dmar_pci_path *path;
u8 bus;
int count;
bus = scope->bus;
path = (struct acpi_dmar_pci_path *)(scope + 1);
count = (scope->length - sizeof(struct acpi_dmar_device_scope))
/ sizeof(struct acpi_dmar_pci_path);
while (--count > 0) {
/*
* Access PCI directly due to the PCI
* subsystem isn't initialized yet.
*/
bus = read_pci_config_byte(bus, path->dev, path->fn,
PCI_SECONDARY_BUS);
path++;
}
ir_ioapic[ir_ioapic_num].bus = bus;
ir_ioapic[ir_ioapic_num].devfn = PCI_DEVFN(path->dev, path->fn);
ir_ioapic[ir_ioapic_num].iommu = iommu;
ir_ioapic[ir_ioapic_num].id = scope->enumeration_id;
ir_ioapic_num++;
}
static int ir_parse_ioapic_hpet_scope(struct acpi_dmar_header *header,
struct intel_iommu *iommu)
{
struct acpi_dmar_hardware_unit *drhd;
struct acpi_dmar_device_scope *scope;
void *start, *end;
drhd = (struct acpi_dmar_hardware_unit *)header;
start = (void *)(drhd + 1);
end = ((void *)drhd) + header->length;
while (start < end) {
scope = start;
if (scope->entry_type == ACPI_DMAR_SCOPE_TYPE_IOAPIC) {
if (ir_ioapic_num == MAX_IO_APICS) {
printk(KERN_WARNING "Exceeded Max IO APICS\n");
return -1;
}
printk(KERN_INFO "IOAPIC id %d under DRHD base "
" 0x%Lx IOMMU %d\n", scope->enumeration_id,
drhd->address, iommu->seq_id);
ir_parse_one_ioapic_scope(scope, iommu);
} else if (scope->entry_type == ACPI_DMAR_SCOPE_TYPE_HPET) {
if (ir_hpet_num == MAX_HPET_TBS) {
printk(KERN_WARNING "Exceeded Max HPET blocks\n");
return -1;
}
printk(KERN_INFO "HPET id %d under DRHD base"
" 0x%Lx\n", scope->enumeration_id,
drhd->address);
ir_parse_one_hpet_scope(scope, iommu);
}
start += scope->length;
}
return 0;
}
/*
* Finds the assocaition between IOAPIC's and its Interrupt-remapping
* hardware unit.
*/
int __init parse_ioapics_under_ir(void)
{
struct dmar_drhd_unit *drhd;
int ir_supported = 0;
for_each_drhd_unit(drhd) {
struct intel_iommu *iommu = drhd->iommu;
if (ecap_ir_support(iommu->ecap)) {
if (ir_parse_ioapic_hpet_scope(drhd->hdr, iommu))
return -1;
ir_supported = 1;
}
}
if (ir_supported && ir_ioapic_num != nr_ioapics) {
printk(KERN_WARNING
"Not all IO-APIC's listed under remapping hardware\n");
return -1;
}
return ir_supported;
}
int __init ir_dev_scope_init(void)
{
if (!intr_remapping_enabled)
return 0;
return dmar_dev_scope_init();
}
rootfs_initcall(ir_dev_scope_init);
void disable_intr_remapping(void)
{
struct dmar_drhd_unit *drhd;
struct intel_iommu *iommu = NULL;
/*
* Disable Interrupt-remapping for all the DRHD's now.
*/
for_each_iommu(iommu, drhd) {
if (!ecap_ir_support(iommu->ecap))
continue;
iommu_disable_intr_remapping(iommu);
}
}
int reenable_intr_remapping(int eim)
{
struct dmar_drhd_unit *drhd;
int setup = 0;
struct intel_iommu *iommu = NULL;
for_each_iommu(iommu, drhd)
if (iommu->qi)
dmar_reenable_qi(iommu);
/*
* Setup Interrupt-remapping for all the DRHD's now.
*/
for_each_iommu(iommu, drhd) {
if (!ecap_ir_support(iommu->ecap))
continue;
/* Set up interrupt remapping for iommu.*/
iommu_set_intr_remapping(iommu, eim);
setup = 1;
}
if (!setup)
goto error;
return 0;
error:
/*
* handle error condition gracefully here!
*/
return -1;
}
| gpl-2.0 |
TheStrix/android_kernel_xiaomi_armani_OLD | drivers/net/wireless/rtlwifi/core.c | 3975 | 34237 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "wifi.h"
#include "core.h"
#include "cam.h"
#include "base.h"
#include "pci.h"
#include "ps.h"
#include <linux/export.h>
void rtl_fw_cb(const struct firmware *firmware, void *context)
{
struct ieee80211_hw *hw = context;
struct rtl_priv *rtlpriv = rtl_priv(hw);
int err;
RT_TRACE(rtlpriv, COMP_ERR, DBG_LOUD,
"Firmware callback routine entered!\n");
complete(&rtlpriv->firmware_loading_complete);
if (!firmware) {
pr_err("Firmware %s not available\n", rtlpriv->cfg->fw_name);
rtlpriv->max_fw_size = 0;
return;
}
if (firmware->size > rtlpriv->max_fw_size) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Firmware is too big!\n");
release_firmware(firmware);
return;
}
memcpy(rtlpriv->rtlhal.pfirmware, firmware->data, firmware->size);
rtlpriv->rtlhal.fwsize = firmware->size;
release_firmware(firmware);
err = ieee80211_register_hw(hw);
if (err) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Can't register mac80211 hw\n");
return;
} else {
rtlpriv->mac80211.mac80211_registered = 1;
}
set_bit(RTL_STATUS_INTERFACE_START, &rtlpriv->status);
/*init rfkill */
rtl_init_rfkill(hw);
}
EXPORT_SYMBOL(rtl_fw_cb);
/*mutex for start & stop is must here. */
static int rtl_op_start(struct ieee80211_hw *hw)
{
int err;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
if (!is_hal_stop(rtlhal))
return 0;
if (!test_bit(RTL_STATUS_INTERFACE_START, &rtlpriv->status))
return 0;
mutex_lock(&rtlpriv->locks.conf_mutex);
err = rtlpriv->intf_ops->adapter_start(hw);
if (!err)
rtl_watch_dog_timer_callback((unsigned long)hw);
mutex_unlock(&rtlpriv->locks.conf_mutex);
return err;
}
static void rtl_op_stop(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
if (is_hal_stop(rtlhal))
return;
if (unlikely(ppsc->rfpwr_state == ERFOFF)) {
rtl_ips_nic_on(hw);
mdelay(1);
}
mutex_lock(&rtlpriv->locks.conf_mutex);
mac->link_state = MAC80211_NOLINK;
memset(mac->bssid, 0, 6);
mac->vendor = PEER_UNKNOWN;
/*reset sec info */
rtl_cam_reset_sec_info(hw);
rtl_deinit_deferred_work(hw);
rtlpriv->intf_ops->adapter_stop(hw);
mutex_unlock(&rtlpriv->locks.conf_mutex);
}
static void rtl_op_tx(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_tcb_desc tcb_desc;
memset(&tcb_desc, 0, sizeof(struct rtl_tcb_desc));
if (unlikely(is_hal_stop(rtlhal) || ppsc->rfpwr_state != ERFON))
goto err_free;
if (!test_bit(RTL_STATUS_INTERFACE_START, &rtlpriv->status))
goto err_free;
if (!rtlpriv->intf_ops->waitq_insert(hw, skb))
rtlpriv->intf_ops->adapter_tx(hw, skb, &tcb_desc);
return;
err_free:
dev_kfree_skb_any(skb);
}
static int rtl_op_add_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
int err = 0;
vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER;
if (mac->vif) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"vif has been set!! mac->vif = 0x%p\n", mac->vif);
return -EOPNOTSUPP;
}
rtl_ips_nic_on(hw);
mutex_lock(&rtlpriv->locks.conf_mutex);
switch (vif->type) {
case NL80211_IFTYPE_STATION:
if (mac->beacon_enabled == 1) {
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"NL80211_IFTYPE_STATION\n");
mac->beacon_enabled = 0;
rtlpriv->cfg->ops->update_interrupt_mask(hw, 0,
rtlpriv->cfg->maps
[RTL_IBSS_INT_MASKS]);
}
break;
case NL80211_IFTYPE_ADHOC:
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"NL80211_IFTYPE_ADHOC\n");
mac->link_state = MAC80211_LINKED;
rtlpriv->cfg->ops->set_bcn_reg(hw);
if (rtlpriv->rtlhal.current_bandtype == BAND_ON_2_4G)
mac->basic_rates = 0xfff;
else
mac->basic_rates = 0xff0;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BASIC_RATE,
(u8 *) (&mac->basic_rates));
break;
case NL80211_IFTYPE_AP:
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"NL80211_IFTYPE_AP\n");
mac->link_state = MAC80211_LINKED;
rtlpriv->cfg->ops->set_bcn_reg(hw);
if (rtlpriv->rtlhal.current_bandtype == BAND_ON_2_4G)
mac->basic_rates = 0xfff;
else
mac->basic_rates = 0xff0;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BASIC_RATE,
(u8 *) (&mac->basic_rates));
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"operation mode %d is not supported!\n", vif->type);
err = -EOPNOTSUPP;
goto out;
}
mac->vif = vif;
mac->opmode = vif->type;
rtlpriv->cfg->ops->set_network_type(hw, vif->type);
memcpy(mac->mac_addr, vif->addr, ETH_ALEN);
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_ETHER_ADDR, mac->mac_addr);
out:
mutex_unlock(&rtlpriv->locks.conf_mutex);
return err;
}
static void rtl_op_remove_interface(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
mutex_lock(&rtlpriv->locks.conf_mutex);
/* Free beacon resources */
if ((mac->opmode == NL80211_IFTYPE_AP) ||
(mac->opmode == NL80211_IFTYPE_ADHOC) ||
(mac->opmode == NL80211_IFTYPE_MESH_POINT)) {
if (mac->beacon_enabled == 1) {
mac->beacon_enabled = 0;
rtlpriv->cfg->ops->update_interrupt_mask(hw, 0,
rtlpriv->cfg->maps
[RTL_IBSS_INT_MASKS]);
}
}
/*
*Note: We assume NL80211_IFTYPE_UNSPECIFIED as
*NO LINK for our hardware.
*/
mac->vif = NULL;
mac->link_state = MAC80211_NOLINK;
memset(mac->bssid, 0, 6);
mac->vendor = PEER_UNKNOWN;
mac->opmode = NL80211_IFTYPE_UNSPECIFIED;
rtlpriv->cfg->ops->set_network_type(hw, mac->opmode);
mutex_unlock(&rtlpriv->locks.conf_mutex);
}
static int rtl_op_config(struct ieee80211_hw *hw, u32 changed)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_phy *rtlphy = &(rtlpriv->phy);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct ieee80211_conf *conf = &hw->conf;
mutex_lock(&rtlpriv->locks.conf_mutex);
if (changed & IEEE80211_CONF_CHANGE_LISTEN_INTERVAL) { /*BIT(2)*/
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"IEEE80211_CONF_CHANGE_LISTEN_INTERVAL\n");
}
/*For IPS */
if (changed & IEEE80211_CONF_CHANGE_IDLE) {
if (hw->conf.flags & IEEE80211_CONF_IDLE)
rtl_ips_nic_off(hw);
else
rtl_ips_nic_on(hw);
} else {
/*
*although rfoff may not cause by ips, but we will
*check the reason in set_rf_power_state function
*/
if (unlikely(ppsc->rfpwr_state == ERFOFF))
rtl_ips_nic_on(hw);
}
/*For LPS */
if (changed & IEEE80211_CONF_CHANGE_PS) {
cancel_delayed_work(&rtlpriv->works.ps_work);
cancel_delayed_work(&rtlpriv->works.ps_rfon_wq);
if (conf->flags & IEEE80211_CONF_PS) {
rtlpriv->psc.sw_ps_enabled = true;
/* sleep here is must, or we may recv the beacon and
* cause mac80211 into wrong ps state, this will cause
* power save nullfunc send fail, and further cause
* pkt loss, So sleep must quickly but not immediatly
* because that will cause nullfunc send by mac80211
* fail, and cause pkt loss, we have tested that 5mA
* is worked very well */
if (!rtlpriv->psc.multi_buffered)
queue_delayed_work(rtlpriv->works.rtl_wq,
&rtlpriv->works.ps_work,
MSECS(5));
} else {
rtl_swlps_rf_awake(hw);
rtlpriv->psc.sw_ps_enabled = false;
}
}
if (changed & IEEE80211_CONF_CHANGE_RETRY_LIMITS) {
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"IEEE80211_CONF_CHANGE_RETRY_LIMITS %x\n",
hw->conf.long_frame_max_tx_count);
mac->retry_long = hw->conf.long_frame_max_tx_count;
mac->retry_short = hw->conf.long_frame_max_tx_count;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_RETRY_LIMIT,
(u8 *) (&hw->conf.
long_frame_max_tx_count));
}
if (changed & IEEE80211_CONF_CHANGE_CHANNEL) {
struct ieee80211_channel *channel = hw->conf.channel;
u8 wide_chan = (u8) channel->hw_value;
/*
*because we should back channel to
*current_network.chan in in scanning,
*So if set_chan == current_network.chan
*we should set it.
*because mac80211 tell us wrong bw40
*info for cisco1253 bw20, so we modify
*it here based on UPPER & LOWER
*/
switch (hw->conf.channel_type) {
case NL80211_CHAN_HT20:
case NL80211_CHAN_NO_HT:
/* SC */
mac->cur_40_prime_sc =
PRIME_CHNL_OFFSET_DONT_CARE;
rtlphy->current_chan_bw = HT_CHANNEL_WIDTH_20;
mac->bw_40 = false;
break;
case NL80211_CHAN_HT40MINUS:
/* SC */
mac->cur_40_prime_sc = PRIME_CHNL_OFFSET_UPPER;
rtlphy->current_chan_bw =
HT_CHANNEL_WIDTH_20_40;
mac->bw_40 = true;
/*wide channel */
wide_chan -= 2;
break;
case NL80211_CHAN_HT40PLUS:
/* SC */
mac->cur_40_prime_sc = PRIME_CHNL_OFFSET_LOWER;
rtlphy->current_chan_bw =
HT_CHANNEL_WIDTH_20_40;
mac->bw_40 = true;
/*wide channel */
wide_chan += 2;
break;
default:
mac->bw_40 = false;
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
if (wide_chan <= 0)
wide_chan = 1;
/* In scanning, before we go offchannel we may send a ps=1 null
* to AP, and then we may send a ps = 0 null to AP quickly, but
* first null may have caused AP to put lots of packet to hw tx
* buffer. These packets must be tx'd before we go off channel
* so we must delay more time to let AP flush these packets
* before going offchannel, or dis-association or delete BA will
* happen by AP
*/
if (rtlpriv->mac80211.offchan_delay) {
rtlpriv->mac80211.offchan_delay = false;
mdelay(50);
}
rtlphy->current_channel = wide_chan;
rtlpriv->cfg->ops->switch_channel(hw);
rtlpriv->cfg->ops->set_channel_access(hw);
rtlpriv->cfg->ops->set_bw_mode(hw,
hw->conf.channel_type);
}
mutex_unlock(&rtlpriv->locks.conf_mutex);
return 0;
}
static void rtl_op_configure_filter(struct ieee80211_hw *hw,
unsigned int changed_flags,
unsigned int *new_flags, u64 multicast)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
*new_flags &= RTL_SUPPORTED_FILTERS;
if (!changed_flags)
return;
/*TODO: we disable broadcase now, so enable here */
if (changed_flags & FIF_ALLMULTI) {
if (*new_flags & FIF_ALLMULTI) {
mac->rx_conf |= rtlpriv->cfg->maps[MAC_RCR_AM] |
rtlpriv->cfg->maps[MAC_RCR_AB];
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"Enable receive multicast frame\n");
} else {
mac->rx_conf &= ~(rtlpriv->cfg->maps[MAC_RCR_AM] |
rtlpriv->cfg->maps[MAC_RCR_AB]);
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"Disable receive multicast frame\n");
}
}
if (changed_flags & FIF_FCSFAIL) {
if (*new_flags & FIF_FCSFAIL) {
mac->rx_conf |= rtlpriv->cfg->maps[MAC_RCR_ACRC32];
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"Enable receive FCS error frame\n");
} else {
mac->rx_conf &= ~rtlpriv->cfg->maps[MAC_RCR_ACRC32];
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"Disable receive FCS error frame\n");
}
}
/* if ssid not set to hw don't check bssid
* here just used for linked scanning, & linked
* and nolink check bssid is set in set network_type */
if ((changed_flags & FIF_BCN_PRBRESP_PROMISC) &&
(mac->link_state >= MAC80211_LINKED)) {
if (mac->opmode != NL80211_IFTYPE_AP) {
if (*new_flags & FIF_BCN_PRBRESP_PROMISC) {
rtlpriv->cfg->ops->set_chk_bssid(hw, false);
} else {
rtlpriv->cfg->ops->set_chk_bssid(hw, true);
}
}
}
if (changed_flags & FIF_CONTROL) {
if (*new_flags & FIF_CONTROL) {
mac->rx_conf |= rtlpriv->cfg->maps[MAC_RCR_ACF];
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"Enable receive control frame\n");
} else {
mac->rx_conf &= ~rtlpriv->cfg->maps[MAC_RCR_ACF];
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"Disable receive control frame\n");
}
}
if (changed_flags & FIF_OTHER_BSS) {
if (*new_flags & FIF_OTHER_BSS) {
mac->rx_conf |= rtlpriv->cfg->maps[MAC_RCR_AAP];
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"Enable receive other BSS's frame\n");
} else {
mac->rx_conf &= ~rtlpriv->cfg->maps[MAC_RCR_AAP];
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"Disable receive other BSS's frame\n");
}
}
}
static int rtl_op_sta_add(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_sta_info *sta_entry;
if (sta) {
sta_entry = (struct rtl_sta_info *) sta->drv_priv;
if (rtlhal->current_bandtype == BAND_ON_2_4G) {
sta_entry->wireless_mode = WIRELESS_MODE_G;
if (sta->supp_rates[0] <= 0xf)
sta_entry->wireless_mode = WIRELESS_MODE_B;
if (sta->ht_cap.ht_supported)
sta_entry->wireless_mode = WIRELESS_MODE_N_24G;
} else if (rtlhal->current_bandtype == BAND_ON_5G) {
sta_entry->wireless_mode = WIRELESS_MODE_A;
if (sta->ht_cap.ht_supported)
sta_entry->wireless_mode = WIRELESS_MODE_N_24G;
}
/* I found some times mac80211 give wrong supp_rates for adhoc*/
if (rtlpriv->mac80211.opmode == NL80211_IFTYPE_ADHOC)
sta_entry->wireless_mode = WIRELESS_MODE_G;
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_DMESG,
"Add sta addr is %pM\n", sta->addr);
rtlpriv->cfg->ops->update_rate_tbl(hw, sta, 0);
}
return 0;
}
static int rtl_op_sta_remove(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_sta *sta)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_sta_info *sta_entry;
if (sta) {
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_DMESG,
"Remove sta addr is %pM\n", sta->addr);
sta_entry = (struct rtl_sta_info *) sta->drv_priv;
sta_entry->wireless_mode = 0;
sta_entry->ratr_index = 0;
}
return 0;
}
static int _rtl_get_hal_qnum(u16 queue)
{
int qnum;
switch (queue) {
case 0:
qnum = AC3_VO;
break;
case 1:
qnum = AC2_VI;
break;
case 2:
qnum = AC0_BE;
break;
case 3:
qnum = AC1_BK;
break;
default:
qnum = AC0_BE;
break;
}
return qnum;
}
/*
*for mac80211 VO=0, VI=1, BE=2, BK=3
*for rtl819x BE=0, BK=1, VI=2, VO=3
*/
static int rtl_op_conf_tx(struct ieee80211_hw *hw,
struct ieee80211_vif *vif, u16 queue,
const struct ieee80211_tx_queue_params *param)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
int aci;
if (queue >= AC_MAX) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"queue number %d is incorrect!\n", queue);
return -EINVAL;
}
aci = _rtl_get_hal_qnum(queue);
mac->ac[aci].aifs = param->aifs;
mac->ac[aci].cw_min = cpu_to_le16(param->cw_min);
mac->ac[aci].cw_max = cpu_to_le16(param->cw_max);
mac->ac[aci].tx_op = cpu_to_le16(param->txop);
memcpy(&mac->edca_param[aci], param, sizeof(*param));
rtlpriv->cfg->ops->set_qos(hw, aci);
return 0;
}
static void rtl_op_bss_info_changed(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
struct ieee80211_bss_conf *bss_conf, u32 changed)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtlpriv);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct ieee80211_sta *sta = NULL;
mutex_lock(&rtlpriv->locks.conf_mutex);
if ((vif->type == NL80211_IFTYPE_ADHOC) ||
(vif->type == NL80211_IFTYPE_AP) ||
(vif->type == NL80211_IFTYPE_MESH_POINT)) {
if ((changed & BSS_CHANGED_BEACON) ||
(changed & BSS_CHANGED_BEACON_ENABLED &&
bss_conf->enable_beacon)) {
if (mac->beacon_enabled == 0) {
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_DMESG,
"BSS_CHANGED_BEACON_ENABLED\n");
/*start hw beacon interrupt. */
/*rtlpriv->cfg->ops->set_bcn_reg(hw); */
mac->beacon_enabled = 1;
rtlpriv->cfg->ops->update_interrupt_mask(hw,
rtlpriv->cfg->maps
[RTL_IBSS_INT_MASKS],
0);
if (rtlpriv->cfg->ops->linked_set_reg)
rtlpriv->cfg->ops->linked_set_reg(hw);
}
}
if ((changed & BSS_CHANGED_BEACON_ENABLED &&
!bss_conf->enable_beacon)) {
if (mac->beacon_enabled == 1) {
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_DMESG,
"ADHOC DISABLE BEACON\n");
mac->beacon_enabled = 0;
rtlpriv->cfg->ops->update_interrupt_mask(hw, 0,
rtlpriv->cfg->maps
[RTL_IBSS_INT_MASKS]);
}
}
if (changed & BSS_CHANGED_BEACON_INT) {
RT_TRACE(rtlpriv, COMP_BEACON, DBG_TRACE,
"BSS_CHANGED_BEACON_INT\n");
mac->beacon_interval = bss_conf->beacon_int;
rtlpriv->cfg->ops->set_bcn_intv(hw);
}
}
/*TODO: reference to enum ieee80211_bss_change */
if (changed & BSS_CHANGED_ASSOC) {
if (bss_conf->assoc) {
/* we should reset all sec info & cam
* before set cam after linked, we should not
* reset in disassoc, that will cause tkip->wep
* fail because some flag will be wrong */
/* reset sec info */
rtl_cam_reset_sec_info(hw);
/* reset cam to fix wep fail issue
* when change from wpa to wep */
rtl_cam_reset_all_entry(hw);
mac->link_state = MAC80211_LINKED;
mac->cnt_after_linked = 0;
mac->assoc_id = bss_conf->aid;
memcpy(mac->bssid, bss_conf->bssid, 6);
if (rtlpriv->cfg->ops->linked_set_reg)
rtlpriv->cfg->ops->linked_set_reg(hw);
if (mac->opmode == NL80211_IFTYPE_STATION && sta)
rtlpriv->cfg->ops->update_rate_tbl(hw, sta, 0);
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_DMESG,
"BSS_CHANGED_ASSOC\n");
} else {
if (mac->link_state == MAC80211_LINKED)
rtl_lps_leave(hw);
mac->link_state = MAC80211_NOLINK;
memset(mac->bssid, 0, 6);
/* reset sec info */
rtl_cam_reset_sec_info(hw);
rtl_cam_reset_all_entry(hw);
mac->vendor = PEER_UNKNOWN;
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_DMESG,
"BSS_CHANGED_UN_ASSOC\n");
}
}
if (changed & BSS_CHANGED_ERP_CTS_PROT) {
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_TRACE,
"BSS_CHANGED_ERP_CTS_PROT\n");
mac->use_cts_protect = bss_conf->use_cts_prot;
}
if (changed & BSS_CHANGED_ERP_PREAMBLE) {
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD,
"BSS_CHANGED_ERP_PREAMBLE use short preamble:%x\n",
bss_conf->use_short_preamble);
mac->short_preamble = bss_conf->use_short_preamble;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_ACK_PREAMBLE,
(u8 *) (&mac->short_preamble));
}
if (changed & BSS_CHANGED_ERP_SLOT) {
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_TRACE,
"BSS_CHANGED_ERP_SLOT\n");
if (bss_conf->use_short_slot)
mac->slot_time = RTL_SLOT_TIME_9;
else
mac->slot_time = RTL_SLOT_TIME_20;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_SLOT_TIME,
(u8 *) (&mac->slot_time));
}
if (changed & BSS_CHANGED_HT) {
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_TRACE, "BSS_CHANGED_HT\n");
rcu_read_lock();
sta = get_sta(hw, vif, bss_conf->bssid);
if (sta) {
if (sta->ht_cap.ampdu_density >
mac->current_ampdu_density)
mac->current_ampdu_density =
sta->ht_cap.ampdu_density;
if (sta->ht_cap.ampdu_factor <
mac->current_ampdu_factor)
mac->current_ampdu_factor =
sta->ht_cap.ampdu_factor;
}
rcu_read_unlock();
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_SHORTGI_DENSITY,
(u8 *) (&mac->max_mss_density));
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_AMPDU_FACTOR,
&mac->current_ampdu_factor);
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_AMPDU_MIN_SPACE,
&mac->current_ampdu_density);
}
if (changed & BSS_CHANGED_BSSID) {
u32 basic_rates;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BSSID,
(u8 *) bss_conf->bssid);
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_DMESG, "%pM\n",
bss_conf->bssid);
mac->vendor = PEER_UNKNOWN;
memcpy(mac->bssid, bss_conf->bssid, 6);
rtlpriv->cfg->ops->set_network_type(hw, vif->type);
rcu_read_lock();
sta = get_sta(hw, vif, bss_conf->bssid);
if (!sta) {
rcu_read_unlock();
goto out;
}
if (rtlhal->current_bandtype == BAND_ON_5G) {
mac->mode = WIRELESS_MODE_A;
} else {
if (sta->supp_rates[0] <= 0xf)
mac->mode = WIRELESS_MODE_B;
else
mac->mode = WIRELESS_MODE_G;
}
if (sta->ht_cap.ht_supported) {
if (rtlhal->current_bandtype == BAND_ON_2_4G)
mac->mode = WIRELESS_MODE_N_24G;
else
mac->mode = WIRELESS_MODE_N_5G;
}
/* just station need it, because ibss & ap mode will
* set in sta_add, and will be NULL here */
if (mac->opmode == NL80211_IFTYPE_STATION) {
struct rtl_sta_info *sta_entry;
sta_entry = (struct rtl_sta_info *) sta->drv_priv;
sta_entry->wireless_mode = mac->mode;
}
if (sta->ht_cap.ht_supported) {
mac->ht_enable = true;
/*
* for cisco 1252 bw20 it's wrong
* if (ht_cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40) {
* mac->bw_40 = true;
* }
* */
}
if (changed & BSS_CHANGED_BASIC_RATES) {
/* for 5G must << RATE_6M_INDEX=4,
* because 5G have no cck rate*/
if (rtlhal->current_bandtype == BAND_ON_5G)
basic_rates = sta->supp_rates[1] << 4;
else
basic_rates = sta->supp_rates[0];
mac->basic_rates = basic_rates;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_BASIC_RATE,
(u8 *) (&basic_rates));
}
rcu_read_unlock();
}
/*
* For FW LPS:
* To tell firmware we have connected
* to an AP. For 92SE/CE power save v2.
*/
if (changed & BSS_CHANGED_ASSOC) {
if (bss_conf->assoc) {
if (ppsc->fwctrl_lps) {
u8 mstatus = RT_MEDIA_CONNECT;
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_H2C_FW_JOINBSSRPT,
(u8 *) (&mstatus));
ppsc->report_linked = true;
}
} else {
if (ppsc->fwctrl_lps) {
u8 mstatus = RT_MEDIA_DISCONNECT;
rtlpriv->cfg->ops->set_hw_reg(hw,
HW_VAR_H2C_FW_JOINBSSRPT,
(u8 *)(&mstatus));
ppsc->report_linked = false;
}
}
}
out:
mutex_unlock(&rtlpriv->locks.conf_mutex);
}
static u64 rtl_op_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u64 tsf;
rtlpriv->cfg->ops->get_hw_reg(hw, HW_VAR_CORRECT_TSF, (u8 *) (&tsf));
return tsf;
}
static void rtl_op_set_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
u64 tsf)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u8 bibss = (mac->opmode == NL80211_IFTYPE_ADHOC) ? 1 : 0;
mac->tsf = tsf;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_CORRECT_TSF, (u8 *) (&bibss));
}
static void rtl_op_reset_tsf(struct ieee80211_hw *hw,
struct ieee80211_vif *vif)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 tmp = 0;
rtlpriv->cfg->ops->set_hw_reg(hw, HW_VAR_DUAL_TSF_RST, (u8 *) (&tmp));
}
static void rtl_op_sta_notify(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum sta_notify_cmd cmd,
struct ieee80211_sta *sta)
{
switch (cmd) {
case STA_NOTIFY_SLEEP:
break;
case STA_NOTIFY_AWAKE:
break;
default:
break;
}
}
static int rtl_op_ampdu_action(struct ieee80211_hw *hw,
struct ieee80211_vif *vif,
enum ieee80211_ampdu_mlme_action action,
struct ieee80211_sta *sta, u16 tid, u16 *ssn,
u8 buf_size)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
switch (action) {
case IEEE80211_AMPDU_TX_START:
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_TRACE,
"IEEE80211_AMPDU_TX_START: TID:%d\n", tid);
return rtl_tx_agg_start(hw, sta, tid, ssn);
break;
case IEEE80211_AMPDU_TX_STOP:
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_TRACE,
"IEEE80211_AMPDU_TX_STOP: TID:%d\n", tid);
return rtl_tx_agg_stop(hw, sta, tid);
break;
case IEEE80211_AMPDU_TX_OPERATIONAL:
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_TRACE,
"IEEE80211_AMPDU_TX_OPERATIONAL:TID:%d\n", tid);
rtl_tx_agg_oper(hw, sta, tid);
break;
case IEEE80211_AMPDU_RX_START:
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_TRACE,
"IEEE80211_AMPDU_RX_START:TID:%d\n", tid);
break;
case IEEE80211_AMPDU_RX_STOP:
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_TRACE,
"IEEE80211_AMPDU_RX_STOP:TID:%d\n", tid);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"IEEE80211_AMPDU_ERR!!!!:\n");
return -EOPNOTSUPP;
}
return 0;
}
static void rtl_op_sw_scan_start(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
mac->act_scanning = true;
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD, "\n");
if (mac->link_state == MAC80211_LINKED) {
rtl_lps_leave(hw);
mac->link_state = MAC80211_LINKED_SCANNING;
} else {
rtl_ips_nic_on(hw);
}
/* Dual mac */
rtlpriv->rtlhal.load_imrandiqk_setting_for2g = false;
rtlpriv->cfg->ops->led_control(hw, LED_CTL_SITE_SURVEY);
rtlpriv->cfg->ops->scan_operation_backup(hw, SCAN_OPT_BACKUP);
}
static void rtl_op_sw_scan_complete(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
RT_TRACE(rtlpriv, COMP_MAC80211, DBG_LOUD, "\n");
mac->act_scanning = false;
/* Dual mac */
rtlpriv->rtlhal.load_imrandiqk_setting_for2g = false;
if (mac->link_state == MAC80211_LINKED_SCANNING) {
mac->link_state = MAC80211_LINKED;
if (mac->opmode == NL80211_IFTYPE_STATION) {
/* fix fwlps issue */
rtlpriv->cfg->ops->set_network_type(hw, mac->opmode);
}
}
rtlpriv->cfg->ops->scan_operation_backup(hw, SCAN_OPT_RESTORE);
}
static int rtl_op_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
struct ieee80211_vif *vif, struct ieee80211_sta *sta,
struct ieee80211_key_conf *key)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
u8 key_type = NO_ENCRYPTION;
u8 key_idx;
bool group_key = false;
bool wep_only = false;
int err = 0;
u8 mac_addr[ETH_ALEN];
u8 bcast_addr[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
u8 zero_addr[ETH_ALEN] = { 0 };
if (rtlpriv->cfg->mod_params->sw_crypto || rtlpriv->sec.use_sw_sec) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_WARNING,
"not open hw encryption\n");
return -ENOSPC; /*User disabled HW-crypto */
}
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"%s hardware based encryption for keyidx: %d, mac: %pM\n",
cmd == SET_KEY ? "Using" : "Disabling", key->keyidx,
sta ? sta->addr : bcast_addr);
rtlpriv->sec.being_setkey = true;
rtl_ips_nic_on(hw);
mutex_lock(&rtlpriv->locks.conf_mutex);
/* <1> get encryption alg */
switch (key->cipher) {
case WLAN_CIPHER_SUITE_WEP40:
key_type = WEP40_ENCRYPTION;
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "alg:WEP40\n");
break;
case WLAN_CIPHER_SUITE_WEP104:
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "alg:WEP104\n");
key_type = WEP104_ENCRYPTION;
break;
case WLAN_CIPHER_SUITE_TKIP:
key_type = TKIP_ENCRYPTION;
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "alg:TKIP\n");
break;
case WLAN_CIPHER_SUITE_CCMP:
key_type = AESCCMP_ENCRYPTION;
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG, "alg:CCMP\n");
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, "alg_err:%x!!!!\n",
key->cipher);
goto out_unlock;
}
if (key_type == WEP40_ENCRYPTION ||
key_type == WEP104_ENCRYPTION ||
mac->opmode == NL80211_IFTYPE_ADHOC)
rtlpriv->sec.use_defaultkey = true;
/* <2> get key_idx */
key_idx = (u8) (key->keyidx);
if (key_idx > 3)
goto out_unlock;
/* <3> if pairwise key enable_hw_sec */
group_key = !(key->flags & IEEE80211_KEY_FLAG_PAIRWISE);
/* wep always be group key, but there are two conditions:
* 1) wep only: is just for wep enc, in this condition
* rtlpriv->sec.pairwise_enc_algorithm == NO_ENCRYPTION
* will be true & enable_hw_sec will be set when wep
* ke setting.
* 2) wep(group) + AES(pairwise): some AP like cisco
* may use it, in this condition enable_hw_sec will not
* be set when wep key setting */
/* we must reset sec_info after lingked before set key,
* or some flag will be wrong*/
if (mac->opmode == NL80211_IFTYPE_AP) {
if (!group_key || key_type == WEP40_ENCRYPTION ||
key_type == WEP104_ENCRYPTION) {
if (group_key)
wep_only = true;
rtlpriv->cfg->ops->enable_hw_sec(hw);
}
} else {
if ((!group_key) || (mac->opmode == NL80211_IFTYPE_ADHOC) ||
rtlpriv->sec.pairwise_enc_algorithm == NO_ENCRYPTION) {
if (rtlpriv->sec.pairwise_enc_algorithm ==
NO_ENCRYPTION &&
(key_type == WEP40_ENCRYPTION ||
key_type == WEP104_ENCRYPTION))
wep_only = true;
rtlpriv->sec.pairwise_enc_algorithm = key_type;
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"set enable_hw_sec, key_type:%x(OPEN:0 WEP40:1 TKIP:2 AES:4 WEP104:5)\n",
key_type);
rtlpriv->cfg->ops->enable_hw_sec(hw);
}
}
/* <4> set key based on cmd */
switch (cmd) {
case SET_KEY:
if (wep_only) {
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"set WEP(group/pairwise) key\n");
/* Pairwise key with an assigned MAC address. */
rtlpriv->sec.pairwise_enc_algorithm = key_type;
rtlpriv->sec.group_enc_algorithm = key_type;
/*set local buf about wep key. */
memcpy(rtlpriv->sec.key_buf[key_idx],
key->key, key->keylen);
rtlpriv->sec.key_len[key_idx] = key->keylen;
memcpy(mac_addr, zero_addr, ETH_ALEN);
} else if (group_key) { /* group key */
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"set group key\n");
/* group key */
rtlpriv->sec.group_enc_algorithm = key_type;
/*set local buf about group key. */
memcpy(rtlpriv->sec.key_buf[key_idx],
key->key, key->keylen);
rtlpriv->sec.key_len[key_idx] = key->keylen;
memcpy(mac_addr, bcast_addr, ETH_ALEN);
} else { /* pairwise key */
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"set pairwise key\n");
if (!sta) {
RT_ASSERT(false,
"pairwise key without mac_addr\n");
err = -EOPNOTSUPP;
goto out_unlock;
}
/* Pairwise key with an assigned MAC address. */
rtlpriv->sec.pairwise_enc_algorithm = key_type;
/*set local buf about pairwise key. */
memcpy(rtlpriv->sec.key_buf[PAIRWISE_KEYIDX],
key->key, key->keylen);
rtlpriv->sec.key_len[PAIRWISE_KEYIDX] = key->keylen;
rtlpriv->sec.pairwise_key =
rtlpriv->sec.key_buf[PAIRWISE_KEYIDX];
memcpy(mac_addr, sta->addr, ETH_ALEN);
}
rtlpriv->cfg->ops->set_key(hw, key_idx, mac_addr,
group_key, key_type, wep_only,
false);
/* <5> tell mac80211 do something: */
/*must use sw generate IV, or can not work !!!!. */
key->flags |= IEEE80211_KEY_FLAG_GENERATE_IV;
key->hw_key_idx = key_idx;
if (key_type == TKIP_ENCRYPTION)
key->flags |= IEEE80211_KEY_FLAG_GENERATE_MMIC;
break;
case DISABLE_KEY:
RT_TRACE(rtlpriv, COMP_SEC, DBG_DMESG,
"disable key delete one entry\n");
/*set local buf about wep key. */
if (mac->opmode == NL80211_IFTYPE_AP) {
if (sta)
rtl_cam_del_entry(hw, sta->addr);
}
memset(rtlpriv->sec.key_buf[key_idx], 0, key->keylen);
rtlpriv->sec.key_len[key_idx] = 0;
memcpy(mac_addr, zero_addr, ETH_ALEN);
/*
*mac80211 will delete entrys one by one,
*so don't use rtl_cam_reset_all_entry
*or clear all entry here.
*/
rtl_cam_delete_one_entry(hw, mac_addr, key_idx);
rtl_cam_reset_sec_info(hw);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"cmd_err:%x!!!!\n", cmd);
}
out_unlock:
mutex_unlock(&rtlpriv->locks.conf_mutex);
rtlpriv->sec.being_setkey = false;
return err;
}
static void rtl_op_rfkill_poll(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
bool radio_state;
bool blocked;
u8 valid = 0;
if (!test_bit(RTL_STATUS_INTERFACE_START, &rtlpriv->status))
return;
mutex_lock(&rtlpriv->locks.conf_mutex);
/*if Radio On return true here */
radio_state = rtlpriv->cfg->ops->radio_onoff_checking(hw, &valid);
if (valid) {
if (unlikely(radio_state != rtlpriv->rfkill.rfkill_state)) {
rtlpriv->rfkill.rfkill_state = radio_state;
RT_TRACE(rtlpriv, COMP_RF, DBG_DMESG,
"wireless radio switch turned %s\n",
radio_state ? "on" : "off");
blocked = (rtlpriv->rfkill.rfkill_state == 1) ? 0 : 1;
wiphy_rfkill_set_hw_state(hw->wiphy, blocked);
}
}
mutex_unlock(&rtlpriv->locks.conf_mutex);
}
/* this function is called by mac80211 to flush tx buffer
* before switch channle or power save, or tx buffer packet
* maybe send after offchannel or rf sleep, this may cause
* dis-association by AP */
static void rtl_op_flush(struct ieee80211_hw *hw, bool drop)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
if (rtlpriv->intf_ops->flush)
rtlpriv->intf_ops->flush(hw, drop);
}
const struct ieee80211_ops rtl_ops = {
.start = rtl_op_start,
.stop = rtl_op_stop,
.tx = rtl_op_tx,
.add_interface = rtl_op_add_interface,
.remove_interface = rtl_op_remove_interface,
.config = rtl_op_config,
.configure_filter = rtl_op_configure_filter,
.sta_add = rtl_op_sta_add,
.sta_remove = rtl_op_sta_remove,
.set_key = rtl_op_set_key,
.conf_tx = rtl_op_conf_tx,
.bss_info_changed = rtl_op_bss_info_changed,
.get_tsf = rtl_op_get_tsf,
.set_tsf = rtl_op_set_tsf,
.reset_tsf = rtl_op_reset_tsf,
.sta_notify = rtl_op_sta_notify,
.ampdu_action = rtl_op_ampdu_action,
.sw_scan_start = rtl_op_sw_scan_start,
.sw_scan_complete = rtl_op_sw_scan_complete,
.rfkill_poll = rtl_op_rfkill_poll,
.flush = rtl_op_flush,
};
| gpl-2.0 |
virtuous/kernel-7x30-gingerbread-v3 | drivers/net/wireless/bcm4329/dhd_linux_sched.c | 4487 | 1593 | /*
* Expose some of the kernel scheduler routines
*
* Copyright (C) 1999-2010, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: dhd_linux_sched.c,v 1.1.34.1.6.1 2009/01/16 01:17:40 Exp $
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linuxver.h>
int setScheduler(struct task_struct *p, int policy, struct sched_param *param)
{
int rc = 0;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 0))
rc = sched_setscheduler(p, policy, param);
#endif /* LinuxVer */
return rc;
}
| gpl-2.0 |
chenxiaolong/Note4Kernel | fs/hfs/bitmap.c | 5255 | 5963 | /*
* linux/fs/hfs/bitmap.c
*
* Copyright (C) 1996-1997 Paul H. Hargrove
* (C) 2003 Ardis Technologies <roman@ardistech.com>
* This file may be distributed under the terms of the GNU General Public License.
*
* Based on GPLed code Copyright (C) 1995 Michael Dreher
*
* This file contains the code to modify the volume bitmap:
* search/set/clear bits.
*/
#include "hfs_fs.h"
/*
* hfs_find_zero_bit()
*
* Description:
* Given a block of memory, its length in bits, and a starting bit number,
* determine the number of the first zero bits (in left-to-right ordering)
* in that range.
*
* Returns >= 'size' if no zero bits are found in the range.
*
* Accesses memory in 32-bit aligned chunks of 32-bits and thus
* may read beyond the 'size'th bit.
*/
static u32 hfs_find_set_zero_bits(__be32 *bitmap, u32 size, u32 offset, u32 *max)
{
__be32 *curr, *end;
u32 mask, start, len, n;
__be32 val;
int i;
len = *max;
if (!len)
return size;
curr = bitmap + (offset / 32);
end = bitmap + ((size + 31) / 32);
/* scan the first partial u32 for zero bits */
val = *curr;
if (~val) {
n = be32_to_cpu(val);
i = offset % 32;
mask = (1U << 31) >> i;
for (; i < 32; mask >>= 1, i++) {
if (!(n & mask))
goto found;
}
}
/* scan complete u32s for the first zero bit */
while (++curr < end) {
val = *curr;
if (~val) {
n = be32_to_cpu(val);
mask = 1 << 31;
for (i = 0; i < 32; mask >>= 1, i++) {
if (!(n & mask))
goto found;
}
}
}
return size;
found:
start = (curr - bitmap) * 32 + i;
if (start >= size)
return start;
/* do any partial u32 at the start */
len = min(size - start, len);
while (1) {
n |= mask;
if (++i >= 32)
break;
mask >>= 1;
if (!--len || n & mask)
goto done;
}
if (!--len)
goto done;
*curr++ = cpu_to_be32(n);
/* do full u32s */
while (1) {
n = be32_to_cpu(*curr);
if (len < 32)
break;
if (n) {
len = 32;
break;
}
*curr++ = cpu_to_be32(0xffffffff);
len -= 32;
}
/* do any partial u32 at end */
mask = 1U << 31;
for (i = 0; i < len; i++) {
if (n & mask)
break;
n |= mask;
mask >>= 1;
}
done:
*curr = cpu_to_be32(n);
*max = (curr - bitmap) * 32 + i - start;
return start;
}
/*
* hfs_vbm_search_free()
*
* Description:
* Search for 'num_bits' consecutive cleared bits in the bitmap blocks of
* the hfs MDB. 'mdb' had better be locked or the returned range
* may be no longer free, when this functions returns!
* XXX Currently the search starts from bit 0, but it should start with
* the bit number stored in 's_alloc_ptr' of the MDB.
* Input Variable(s):
* struct hfs_mdb *mdb: Pointer to the hfs MDB
* u16 *num_bits: Pointer to the number of cleared bits
* to search for
* Output Variable(s):
* u16 *num_bits: The number of consecutive clear bits of the
* returned range. If the bitmap is fragmented, this will be less than
* requested and it will be zero, when the disk is full.
* Returns:
* The number of the first bit of the range of cleared bits which has been
* found. When 'num_bits' is zero, this is invalid!
* Preconditions:
* 'mdb' points to a "valid" (struct hfs_mdb).
* 'num_bits' points to a variable of type (u16), which contains
* the number of cleared bits to find.
* Postconditions:
* 'num_bits' is set to the length of the found sequence.
*/
u32 hfs_vbm_search_free(struct super_block *sb, u32 goal, u32 *num_bits)
{
void *bitmap;
u32 pos;
/* make sure we have actual work to perform */
if (!*num_bits)
return 0;
mutex_lock(&HFS_SB(sb)->bitmap_lock);
bitmap = HFS_SB(sb)->bitmap;
pos = hfs_find_set_zero_bits(bitmap, HFS_SB(sb)->fs_ablocks, goal, num_bits);
if (pos >= HFS_SB(sb)->fs_ablocks) {
if (goal)
pos = hfs_find_set_zero_bits(bitmap, goal, 0, num_bits);
if (pos >= HFS_SB(sb)->fs_ablocks) {
*num_bits = pos = 0;
goto out;
}
}
hfs_dbg(BITMAP, "alloc_bits: %u,%u\n", pos, *num_bits);
HFS_SB(sb)->free_ablocks -= *num_bits;
hfs_bitmap_dirty(sb);
out:
mutex_unlock(&HFS_SB(sb)->bitmap_lock);
return pos;
}
/*
* hfs_clear_vbm_bits()
*
* Description:
* Clear the requested bits in the volume bitmap of the hfs filesystem
* Input Variable(s):
* struct hfs_mdb *mdb: Pointer to the hfs MDB
* u16 start: The offset of the first bit
* u16 count: The number of bits
* Output Variable(s):
* None
* Returns:
* 0: no error
* -1: One of the bits was already clear. This is a strange
* error and when it happens, the filesystem must be repaired!
* -2: One or more of the bits are out of range of the bitmap.
* Preconditions:
* 'mdb' points to a "valid" (struct hfs_mdb).
* Postconditions:
* Starting with bit number 'start', 'count' bits in the volume bitmap
* are cleared. The affected bitmap blocks are marked "dirty", the free
* block count of the MDB is updated and the MDB is marked dirty.
*/
int hfs_clear_vbm_bits(struct super_block *sb, u16 start, u16 count)
{
__be32 *curr;
u32 mask;
int i, len;
/* is there any actual work to be done? */
if (!count)
return 0;
hfs_dbg(BITMAP, "clear_bits: %u,%u\n", start, count);
/* are all of the bits in range? */
if ((start + count) > HFS_SB(sb)->fs_ablocks)
return -2;
mutex_lock(&HFS_SB(sb)->bitmap_lock);
/* bitmap is always on a 32-bit boundary */
curr = HFS_SB(sb)->bitmap + (start / 32);
len = count;
/* do any partial u32 at the start */
i = start % 32;
if (i) {
int j = 32 - i;
mask = 0xffffffffU << j;
if (j > count) {
mask |= 0xffffffffU >> (i + count);
*curr &= cpu_to_be32(mask);
goto out;
}
*curr++ &= cpu_to_be32(mask);
count -= j;
}
/* do full u32s */
while (count >= 32) {
*curr++ = 0;
count -= 32;
}
/* do any partial u32 at end */
if (count) {
mask = 0xffffffffU >> count;
*curr &= cpu_to_be32(mask);
}
out:
HFS_SB(sb)->free_ablocks += len;
mutex_unlock(&HFS_SB(sb)->bitmap_lock);
hfs_bitmap_dirty(sb);
return 0;
}
| gpl-2.0 |
N3uTr0nRom/N3uTr0n_kernel | fs/reiserfs/prints.c | 7303 | 21190 | /*
* Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README
*/
#include <linux/time.h>
#include <linux/fs.h>
#include "reiserfs.h"
#include <linux/string.h>
#include <linux/buffer_head.h>
#include <stdarg.h>
static char error_buf[1024];
static char fmt_buf[1024];
static char off_buf[80];
static char *reiserfs_cpu_offset(struct cpu_key *key)
{
if (cpu_key_k_type(key) == TYPE_DIRENTRY)
sprintf(off_buf, "%Lu(%Lu)",
(unsigned long long)
GET_HASH_VALUE(cpu_key_k_offset(key)),
(unsigned long long)
GET_GENERATION_NUMBER(cpu_key_k_offset(key)));
else
sprintf(off_buf, "0x%Lx",
(unsigned long long)cpu_key_k_offset(key));
return off_buf;
}
static char *le_offset(struct reiserfs_key *key)
{
int version;
version = le_key_version(key);
if (le_key_k_type(version, key) == TYPE_DIRENTRY)
sprintf(off_buf, "%Lu(%Lu)",
(unsigned long long)
GET_HASH_VALUE(le_key_k_offset(version, key)),
(unsigned long long)
GET_GENERATION_NUMBER(le_key_k_offset(version, key)));
else
sprintf(off_buf, "0x%Lx",
(unsigned long long)le_key_k_offset(version, key));
return off_buf;
}
static char *cpu_type(struct cpu_key *key)
{
if (cpu_key_k_type(key) == TYPE_STAT_DATA)
return "SD";
if (cpu_key_k_type(key) == TYPE_DIRENTRY)
return "DIR";
if (cpu_key_k_type(key) == TYPE_DIRECT)
return "DIRECT";
if (cpu_key_k_type(key) == TYPE_INDIRECT)
return "IND";
return "UNKNOWN";
}
static char *le_type(struct reiserfs_key *key)
{
int version;
version = le_key_version(key);
if (le_key_k_type(version, key) == TYPE_STAT_DATA)
return "SD";
if (le_key_k_type(version, key) == TYPE_DIRENTRY)
return "DIR";
if (le_key_k_type(version, key) == TYPE_DIRECT)
return "DIRECT";
if (le_key_k_type(version, key) == TYPE_INDIRECT)
return "IND";
return "UNKNOWN";
}
/* %k */
static void sprintf_le_key(char *buf, struct reiserfs_key *key)
{
if (key)
sprintf(buf, "[%d %d %s %s]", le32_to_cpu(key->k_dir_id),
le32_to_cpu(key->k_objectid), le_offset(key),
le_type(key));
else
sprintf(buf, "[NULL]");
}
/* %K */
static void sprintf_cpu_key(char *buf, struct cpu_key *key)
{
if (key)
sprintf(buf, "[%d %d %s %s]", key->on_disk_key.k_dir_id,
key->on_disk_key.k_objectid, reiserfs_cpu_offset(key),
cpu_type(key));
else
sprintf(buf, "[NULL]");
}
static void sprintf_de_head(char *buf, struct reiserfs_de_head *deh)
{
if (deh)
sprintf(buf,
"[offset=%d dir_id=%d objectid=%d location=%d state=%04x]",
deh_offset(deh), deh_dir_id(deh), deh_objectid(deh),
deh_location(deh), deh_state(deh));
else
sprintf(buf, "[NULL]");
}
static void sprintf_item_head(char *buf, struct item_head *ih)
{
if (ih) {
strcpy(buf,
(ih_version(ih) == KEY_FORMAT_3_6) ? "*3.6* " : "*3.5*");
sprintf_le_key(buf + strlen(buf), &(ih->ih_key));
sprintf(buf + strlen(buf), ", item_len %d, item_location %d, "
"free_space(entry_count) %d",
ih_item_len(ih), ih_location(ih), ih_free_space(ih));
} else
sprintf(buf, "[NULL]");
}
static void sprintf_direntry(char *buf, struct reiserfs_dir_entry *de)
{
char name[20];
memcpy(name, de->de_name, de->de_namelen > 19 ? 19 : de->de_namelen);
name[de->de_namelen > 19 ? 19 : de->de_namelen] = 0;
sprintf(buf, "\"%s\"==>[%d %d]", name, de->de_dir_id, de->de_objectid);
}
static void sprintf_block_head(char *buf, struct buffer_head *bh)
{
sprintf(buf, "level=%d, nr_items=%d, free_space=%d rdkey ",
B_LEVEL(bh), B_NR_ITEMS(bh), B_FREE_SPACE(bh));
}
static void sprintf_buffer_head(char *buf, struct buffer_head *bh)
{
char b[BDEVNAME_SIZE];
sprintf(buf,
"dev %s, size %zd, blocknr %llu, count %d, state 0x%lx, page %p, (%s, %s, %s)",
bdevname(bh->b_bdev, b), bh->b_size,
(unsigned long long)bh->b_blocknr, atomic_read(&(bh->b_count)),
bh->b_state, bh->b_page,
buffer_uptodate(bh) ? "UPTODATE" : "!UPTODATE",
buffer_dirty(bh) ? "DIRTY" : "CLEAN",
buffer_locked(bh) ? "LOCKED" : "UNLOCKED");
}
static void sprintf_disk_child(char *buf, struct disk_child *dc)
{
sprintf(buf, "[dc_number=%d, dc_size=%u]", dc_block_number(dc),
dc_size(dc));
}
static char *is_there_reiserfs_struct(char *fmt, int *what)
{
char *k = fmt;
while ((k = strchr(k, '%')) != NULL) {
if (k[1] == 'k' || k[1] == 'K' || k[1] == 'h' || k[1] == 't' ||
k[1] == 'z' || k[1] == 'b' || k[1] == 'y' || k[1] == 'a') {
*what = k[1];
break;
}
k++;
}
return k;
}
/* debugging reiserfs we used to print out a lot of different
variables, like keys, item headers, buffer heads etc. Values of
most fields matter. So it took a long time just to write
appropriative printk. With this reiserfs_warning you can use format
specification for complex structures like you used to do with
printfs for integers, doubles and pointers. For instance, to print
out key structure you have to write just:
reiserfs_warning ("bad key %k", key);
instead of
printk ("bad key %lu %lu %lu %lu", key->k_dir_id, key->k_objectid,
key->k_offset, key->k_uniqueness);
*/
static DEFINE_SPINLOCK(error_lock);
static void prepare_error_buf(const char *fmt, va_list args)
{
char *fmt1 = fmt_buf;
char *k;
char *p = error_buf;
int what;
spin_lock(&error_lock);
strcpy(fmt1, fmt);
while ((k = is_there_reiserfs_struct(fmt1, &what)) != NULL) {
*k = 0;
p += vsprintf(p, fmt1, args);
switch (what) {
case 'k':
sprintf_le_key(p, va_arg(args, struct reiserfs_key *));
break;
case 'K':
sprintf_cpu_key(p, va_arg(args, struct cpu_key *));
break;
case 'h':
sprintf_item_head(p, va_arg(args, struct item_head *));
break;
case 't':
sprintf_direntry(p,
va_arg(args,
struct reiserfs_dir_entry *));
break;
case 'y':
sprintf_disk_child(p,
va_arg(args, struct disk_child *));
break;
case 'z':
sprintf_block_head(p,
va_arg(args, struct buffer_head *));
break;
case 'b':
sprintf_buffer_head(p,
va_arg(args, struct buffer_head *));
break;
case 'a':
sprintf_de_head(p,
va_arg(args,
struct reiserfs_de_head *));
break;
}
p += strlen(p);
fmt1 = k + 2;
}
vsprintf(p, fmt1, args);
spin_unlock(&error_lock);
}
/* in addition to usual conversion specifiers this accepts reiserfs
specific conversion specifiers:
%k to print little endian key,
%K to print cpu key,
%h to print item_head,
%t to print directory entry
%z to print block head (arg must be struct buffer_head *
%b to print buffer_head
*/
#define do_reiserfs_warning(fmt)\
{\
va_list args;\
va_start( args, fmt );\
prepare_error_buf( fmt, args );\
va_end( args );\
}
void __reiserfs_warning(struct super_block *sb, const char *id,
const char *function, const char *fmt, ...)
{
do_reiserfs_warning(fmt);
if (sb)
printk(KERN_WARNING "REISERFS warning (device %s): %s%s%s: "
"%s\n", sb->s_id, id ? id : "", id ? " " : "",
function, error_buf);
else
printk(KERN_WARNING "REISERFS warning: %s%s%s: %s\n",
id ? id : "", id ? " " : "", function, error_buf);
}
/* No newline.. reiserfs_info calls can be followed by printk's */
void reiserfs_info(struct super_block *sb, const char *fmt, ...)
{
do_reiserfs_warning(fmt);
if (sb)
printk(KERN_NOTICE "REISERFS (device %s): %s",
sb->s_id, error_buf);
else
printk(KERN_NOTICE "REISERFS %s:", error_buf);
}
/* No newline.. reiserfs_printk calls can be followed by printk's */
static void reiserfs_printk(const char *fmt, ...)
{
do_reiserfs_warning(fmt);
printk(error_buf);
}
void reiserfs_debug(struct super_block *s, int level, const char *fmt, ...)
{
#ifdef CONFIG_REISERFS_CHECK
do_reiserfs_warning(fmt);
if (s)
printk(KERN_DEBUG "REISERFS debug (device %s): %s\n",
s->s_id, error_buf);
else
printk(KERN_DEBUG "REISERFS debug: %s\n", error_buf);
#endif
}
/* The format:
maintainer-errorid: [function-name:] message
where errorid is unique to the maintainer and function-name is
optional, is recommended, so that anyone can easily find the bug
with a simple grep for the short to type string
maintainer-errorid. Don't bother with reusing errorids, there are
lots of numbers out there.
Example:
reiserfs_panic(
p_sb, "reiser-29: reiserfs_new_blocknrs: "
"one of search_start or rn(%d) is equal to MAX_B_NUM,"
"which means that we are optimizing location based on the bogus location of a temp buffer (%p).",
rn, bh
);
Regular panic()s sometimes clear the screen before the message can
be read, thus the need for the while loop.
Numbering scheme for panic used by Vladimir and Anatoly( Hans completely ignores this scheme, and considers it
pointless complexity):
panics in reiserfs.h have numbers from 1000 to 1999
super.c 2000 to 2999
preserve.c (unused) 3000 to 3999
bitmap.c 4000 to 4999
stree.c 5000 to 5999
prints.c 6000 to 6999
namei.c 7000 to 7999
fix_nodes.c 8000 to 8999
dir.c 9000 to 9999
lbalance.c 10000 to 10999
ibalance.c 11000 to 11999 not ready
do_balan.c 12000 to 12999
inode.c 13000 to 13999
file.c 14000 to 14999
objectid.c 15000 - 15999
buffer.c 16000 - 16999
symlink.c 17000 - 17999
. */
void __reiserfs_panic(struct super_block *sb, const char *id,
const char *function, const char *fmt, ...)
{
do_reiserfs_warning(fmt);
#ifdef CONFIG_REISERFS_CHECK
dump_stack();
#endif
if (sb)
panic(KERN_WARNING "REISERFS panic (device %s): %s%s%s: %s\n",
sb->s_id, id ? id : "", id ? " " : "",
function, error_buf);
else
panic(KERN_WARNING "REISERFS panic: %s%s%s: %s\n",
id ? id : "", id ? " " : "", function, error_buf);
}
void __reiserfs_error(struct super_block *sb, const char *id,
const char *function, const char *fmt, ...)
{
do_reiserfs_warning(fmt);
BUG_ON(sb == NULL);
if (reiserfs_error_panic(sb))
__reiserfs_panic(sb, id, function, error_buf);
if (id && id[0])
printk(KERN_CRIT "REISERFS error (device %s): %s %s: %s\n",
sb->s_id, id, function, error_buf);
else
printk(KERN_CRIT "REISERFS error (device %s): %s: %s\n",
sb->s_id, function, error_buf);
if (sb->s_flags & MS_RDONLY)
return;
reiserfs_info(sb, "Remounting filesystem read-only\n");
sb->s_flags |= MS_RDONLY;
reiserfs_abort_journal(sb, -EIO);
}
void reiserfs_abort(struct super_block *sb, int errno, const char *fmt, ...)
{
do_reiserfs_warning(fmt);
if (reiserfs_error_panic(sb)) {
panic(KERN_CRIT "REISERFS panic (device %s): %s\n", sb->s_id,
error_buf);
}
if (reiserfs_is_journal_aborted(SB_JOURNAL(sb)))
return;
printk(KERN_CRIT "REISERFS abort (device %s): %s\n", sb->s_id,
error_buf);
sb->s_flags |= MS_RDONLY;
reiserfs_abort_journal(sb, errno);
}
/* this prints internal nodes (4 keys/items in line) (dc_number,
dc_size)[k_dirid, k_objectid, k_offset, k_uniqueness](dc_number,
dc_size)...*/
static int print_internal(struct buffer_head *bh, int first, int last)
{
struct reiserfs_key *key;
struct disk_child *dc;
int i;
int from, to;
if (!B_IS_KEYS_LEVEL(bh))
return 1;
check_internal(bh);
if (first == -1) {
from = 0;
to = B_NR_ITEMS(bh);
} else {
from = first;
to = last < B_NR_ITEMS(bh) ? last : B_NR_ITEMS(bh);
}
reiserfs_printk("INTERNAL NODE (%ld) contains %z\n", bh->b_blocknr, bh);
dc = B_N_CHILD(bh, from);
reiserfs_printk("PTR %d: %y ", from, dc);
for (i = from, key = B_N_PDELIM_KEY(bh, from), dc++; i < to;
i++, key++, dc++) {
reiserfs_printk("KEY %d: %k PTR %d: %y ", i, key, i + 1, dc);
if (i && i % 4 == 0)
printk("\n");
}
printk("\n");
return 0;
}
static int print_leaf(struct buffer_head *bh, int print_mode, int first,
int last)
{
struct block_head *blkh;
struct item_head *ih;
int i, nr;
int from, to;
if (!B_IS_ITEMS_LEVEL(bh))
return 1;
check_leaf(bh);
blkh = B_BLK_HEAD(bh);
ih = B_N_PITEM_HEAD(bh, 0);
nr = blkh_nr_item(blkh);
printk
("\n===================================================================\n");
reiserfs_printk("LEAF NODE (%ld) contains %z\n", bh->b_blocknr, bh);
if (!(print_mode & PRINT_LEAF_ITEMS)) {
reiserfs_printk("FIRST ITEM_KEY: %k, LAST ITEM KEY: %k\n",
&(ih->ih_key), &((ih + nr - 1)->ih_key));
return 0;
}
if (first < 0 || first > nr - 1)
from = 0;
else
from = first;
if (last < 0 || last > nr)
to = nr;
else
to = last;
ih += from;
printk
("-------------------------------------------------------------------------------\n");
printk
("|##| type | key | ilen | free_space | version | loc |\n");
for (i = from; i < to; i++, ih++) {
printk
("-------------------------------------------------------------------------------\n");
reiserfs_printk("|%2d| %h |\n", i, ih);
if (print_mode & PRINT_LEAF_ITEMS)
op_print_item(ih, B_I_PITEM(bh, ih));
}
printk
("===================================================================\n");
return 0;
}
char *reiserfs_hashname(int code)
{
if (code == YURA_HASH)
return "rupasov";
if (code == TEA_HASH)
return "tea";
if (code == R5_HASH)
return "r5";
return "unknown";
}
/* return 1 if this is not super block */
static int print_super_block(struct buffer_head *bh)
{
struct reiserfs_super_block *rs =
(struct reiserfs_super_block *)(bh->b_data);
int skipped, data_blocks;
char *version;
char b[BDEVNAME_SIZE];
if (is_reiserfs_3_5(rs)) {
version = "3.5";
} else if (is_reiserfs_3_6(rs)) {
version = "3.6";
} else if (is_reiserfs_jr(rs)) {
version = ((sb_version(rs) == REISERFS_VERSION_2) ?
"3.6" : "3.5");
} else {
return 1;
}
printk("%s\'s super block is in block %llu\n", bdevname(bh->b_bdev, b),
(unsigned long long)bh->b_blocknr);
printk("Reiserfs version %s\n", version);
printk("Block count %u\n", sb_block_count(rs));
printk("Blocksize %d\n", sb_blocksize(rs));
printk("Free blocks %u\n", sb_free_blocks(rs));
// FIXME: this would be confusing if
// someone stores reiserfs super block in some data block ;)
// skipped = (bh->b_blocknr * bh->b_size) / sb_blocksize(rs);
skipped = bh->b_blocknr;
data_blocks = sb_block_count(rs) - skipped - 1 - sb_bmap_nr(rs) -
(!is_reiserfs_jr(rs) ? sb_jp_journal_size(rs) +
1 : sb_reserved_for_journal(rs)) - sb_free_blocks(rs);
printk
("Busy blocks (skipped %d, bitmaps - %d, journal (or reserved) blocks - %d\n"
"1 super block, %d data blocks\n", skipped, sb_bmap_nr(rs),
(!is_reiserfs_jr(rs) ? (sb_jp_journal_size(rs) + 1) :
sb_reserved_for_journal(rs)), data_blocks);
printk("Root block %u\n", sb_root_block(rs));
printk("Journal block (first) %d\n", sb_jp_journal_1st_block(rs));
printk("Journal dev %d\n", sb_jp_journal_dev(rs));
printk("Journal orig size %d\n", sb_jp_journal_size(rs));
printk("FS state %d\n", sb_fs_state(rs));
printk("Hash function \"%s\"\n",
reiserfs_hashname(sb_hash_function_code(rs)));
printk("Tree height %d\n", sb_tree_height(rs));
return 0;
}
static int print_desc_block(struct buffer_head *bh)
{
struct reiserfs_journal_desc *desc;
if (memcmp(get_journal_desc_magic(bh), JOURNAL_DESC_MAGIC, 8))
return 1;
desc = (struct reiserfs_journal_desc *)(bh->b_data);
printk("Desc block %llu (j_trans_id %d, j_mount_id %d, j_len %d)",
(unsigned long long)bh->b_blocknr, get_desc_trans_id(desc),
get_desc_mount_id(desc), get_desc_trans_len(desc));
return 0;
}
void print_block(struct buffer_head *bh, ...) //int print_mode, int first, int last)
{
va_list args;
int mode, first, last;
if (!bh) {
printk("print_block: buffer is NULL\n");
return;
}
va_start(args, bh);
mode = va_arg(args, int);
first = va_arg(args, int);
last = va_arg(args, int);
if (print_leaf(bh, mode, first, last))
if (print_internal(bh, first, last))
if (print_super_block(bh))
if (print_desc_block(bh))
printk
("Block %llu contains unformatted data\n",
(unsigned long long)bh->b_blocknr);
va_end(args);
}
static char print_tb_buf[2048];
/* this stores initial state of tree balance in the print_tb_buf */
void store_print_tb(struct tree_balance *tb)
{
int h = 0;
int i;
struct buffer_head *tbSh, *tbFh;
if (!tb)
return;
sprintf(print_tb_buf, "\n"
"BALANCING %d\n"
"MODE=%c, ITEM_POS=%d POS_IN_ITEM=%d\n"
"=====================================================================\n"
"* h * S * L * R * F * FL * FR * CFL * CFR *\n",
REISERFS_SB(tb->tb_sb)->s_do_balance,
tb->tb_mode, PATH_LAST_POSITION(tb->tb_path),
tb->tb_path->pos_in_item);
for (h = 0; h < ARRAY_SIZE(tb->insert_size); h++) {
if (PATH_H_PATH_OFFSET(tb->tb_path, h) <=
tb->tb_path->path_length
&& PATH_H_PATH_OFFSET(tb->tb_path,
h) > ILLEGAL_PATH_ELEMENT_OFFSET) {
tbSh = PATH_H_PBUFFER(tb->tb_path, h);
tbFh = PATH_H_PPARENT(tb->tb_path, h);
} else {
tbSh = NULL;
tbFh = NULL;
}
sprintf(print_tb_buf + strlen(print_tb_buf),
"* %d * %3lld(%2d) * %3lld(%2d) * %3lld(%2d) * %5lld * %5lld * %5lld * %5lld * %5lld *\n",
h,
(tbSh) ? (long long)(tbSh->b_blocknr) : (-1LL),
(tbSh) ? atomic_read(&(tbSh->b_count)) : -1,
(tb->L[h]) ? (long long)(tb->L[h]->b_blocknr) : (-1LL),
(tb->L[h]) ? atomic_read(&(tb->L[h]->b_count)) : -1,
(tb->R[h]) ? (long long)(tb->R[h]->b_blocknr) : (-1LL),
(tb->R[h]) ? atomic_read(&(tb->R[h]->b_count)) : -1,
(tbFh) ? (long long)(tbFh->b_blocknr) : (-1LL),
(tb->FL[h]) ? (long long)(tb->FL[h]->
b_blocknr) : (-1LL),
(tb->FR[h]) ? (long long)(tb->FR[h]->
b_blocknr) : (-1LL),
(tb->CFL[h]) ? (long long)(tb->CFL[h]->
b_blocknr) : (-1LL),
(tb->CFR[h]) ? (long long)(tb->CFR[h]->
b_blocknr) : (-1LL));
}
sprintf(print_tb_buf + strlen(print_tb_buf),
"=====================================================================\n"
"* h * size * ln * lb * rn * rb * blkn * s0 * s1 * s1b * s2 * s2b * curb * lk * rk *\n"
"* 0 * %4d * %2d * %2d * %2d * %2d * %4d * %2d * %2d * %3d * %2d * %3d * %4d * %2d * %2d *\n",
tb->insert_size[0], tb->lnum[0], tb->lbytes, tb->rnum[0],
tb->rbytes, tb->blknum[0], tb->s0num, tb->s1num, tb->s1bytes,
tb->s2num, tb->s2bytes, tb->cur_blknum, tb->lkey[0],
tb->rkey[0]);
/* this prints balance parameters for non-leaf levels */
h = 0;
do {
h++;
sprintf(print_tb_buf + strlen(print_tb_buf),
"* %d * %4d * %2d * * %2d * * %2d *\n",
h, tb->insert_size[h], tb->lnum[h], tb->rnum[h],
tb->blknum[h]);
} while (tb->insert_size[h]);
sprintf(print_tb_buf + strlen(print_tb_buf),
"=====================================================================\n"
"FEB list: ");
/* print FEB list (list of buffers in form (bh (b_blocknr, b_count), that will be used for new nodes) */
h = 0;
for (i = 0; i < ARRAY_SIZE(tb->FEB); i++)
sprintf(print_tb_buf + strlen(print_tb_buf),
"%p (%llu %d)%s", tb->FEB[i],
tb->FEB[i] ? (unsigned long long)tb->FEB[i]->
b_blocknr : 0ULL,
tb->FEB[i] ? atomic_read(&(tb->FEB[i]->b_count)) : 0,
(i == ARRAY_SIZE(tb->FEB) - 1) ? "\n" : ", ");
sprintf(print_tb_buf + strlen(print_tb_buf),
"======================== the end ====================================\n");
}
void print_cur_tb(char *mes)
{
printk("%s\n%s", mes, print_tb_buf);
}
static void check_leaf_block_head(struct buffer_head *bh)
{
struct block_head *blkh;
int nr;
blkh = B_BLK_HEAD(bh);
nr = blkh_nr_item(blkh);
if (nr > (bh->b_size - BLKH_SIZE) / IH_SIZE)
reiserfs_panic(NULL, "vs-6010", "invalid item number %z",
bh);
if (blkh_free_space(blkh) > bh->b_size - BLKH_SIZE - IH_SIZE * nr)
reiserfs_panic(NULL, "vs-6020", "invalid free space %z",
bh);
}
static void check_internal_block_head(struct buffer_head *bh)
{
struct block_head *blkh;
blkh = B_BLK_HEAD(bh);
if (!(B_LEVEL(bh) > DISK_LEAF_NODE_LEVEL && B_LEVEL(bh) <= MAX_HEIGHT))
reiserfs_panic(NULL, "vs-6025", "invalid level %z", bh);
if (B_NR_ITEMS(bh) > (bh->b_size - BLKH_SIZE) / IH_SIZE)
reiserfs_panic(NULL, "vs-6030", "invalid item number %z", bh);
if (B_FREE_SPACE(bh) !=
bh->b_size - BLKH_SIZE - KEY_SIZE * B_NR_ITEMS(bh) -
DC_SIZE * (B_NR_ITEMS(bh) + 1))
reiserfs_panic(NULL, "vs-6040", "invalid free space %z", bh);
}
void check_leaf(struct buffer_head *bh)
{
int i;
struct item_head *ih;
if (!bh)
return;
check_leaf_block_head(bh);
for (i = 0, ih = B_N_PITEM_HEAD(bh, 0); i < B_NR_ITEMS(bh); i++, ih++)
op_check_item(ih, B_I_PITEM(bh, ih));
}
void check_internal(struct buffer_head *bh)
{
if (!bh)
return;
check_internal_block_head(bh);
}
void print_statistics(struct super_block *s)
{
/*
printk ("reiserfs_put_super: session statistics: balances %d, fix_nodes %d, \
bmap with search %d, without %d, dir2ind %d, ind2dir %d\n",
REISERFS_SB(s)->s_do_balance, REISERFS_SB(s)->s_fix_nodes,
REISERFS_SB(s)->s_bmaps, REISERFS_SB(s)->s_bmaps_without_search,
REISERFS_SB(s)->s_direct2indirect, REISERFS_SB(s)->s_indirect2direct);
*/
}
| gpl-2.0 |
shark147/m7-kernel | arch/arm/mach-ixp4xx/ixp4xx_qmgr.c | 8071 | 9351 | /*
* Intel IXP4xx Queue Manager driver for Linux
*
* Copyright (C) 2007 Krzysztof Halasa <khc@pm.waw.pl>
*
* 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.
*/
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <mach/qmgr.h>
struct qmgr_regs __iomem *qmgr_regs;
static struct resource *mem_res;
static spinlock_t qmgr_lock;
static u32 used_sram_bitmap[4]; /* 128 16-dword pages */
static void (*irq_handlers[QUEUES])(void *pdev);
static void *irq_pdevs[QUEUES];
#if DEBUG_QMGR
char qmgr_queue_descs[QUEUES][32];
#endif
void qmgr_set_irq(unsigned int queue, int src,
void (*handler)(void *pdev), void *pdev)
{
unsigned long flags;
spin_lock_irqsave(&qmgr_lock, flags);
if (queue < HALF_QUEUES) {
u32 __iomem *reg;
int bit;
BUG_ON(src > QUEUE_IRQ_SRC_NOT_FULL);
reg = &qmgr_regs->irqsrc[queue >> 3]; /* 8 queues per u32 */
bit = (queue % 8) * 4; /* 3 bits + 1 reserved bit per queue */
__raw_writel((__raw_readl(reg) & ~(7 << bit)) | (src << bit),
reg);
} else
/* IRQ source for queues 32-63 is fixed */
BUG_ON(src != QUEUE_IRQ_SRC_NOT_NEARLY_EMPTY);
irq_handlers[queue] = handler;
irq_pdevs[queue] = pdev;
spin_unlock_irqrestore(&qmgr_lock, flags);
}
static irqreturn_t qmgr_irq1_a0(int irq, void *pdev)
{
int i, ret = 0;
u32 en_bitmap, src, stat;
/* ACK - it may clear any bits so don't rely on it */
__raw_writel(0xFFFFFFFF, &qmgr_regs->irqstat[0]);
en_bitmap = qmgr_regs->irqen[0];
while (en_bitmap) {
i = __fls(en_bitmap); /* number of the last "low" queue */
en_bitmap &= ~BIT(i);
src = qmgr_regs->irqsrc[i >> 3];
stat = qmgr_regs->stat1[i >> 3];
if (src & 4) /* the IRQ condition is inverted */
stat = ~stat;
if (stat & BIT(src & 3)) {
irq_handlers[i](irq_pdevs[i]);
ret = IRQ_HANDLED;
}
}
return ret;
}
static irqreturn_t qmgr_irq2_a0(int irq, void *pdev)
{
int i, ret = 0;
u32 req_bitmap;
/* ACK - it may clear any bits so don't rely on it */
__raw_writel(0xFFFFFFFF, &qmgr_regs->irqstat[1]);
req_bitmap = qmgr_regs->irqen[1] & qmgr_regs->statne_h;
while (req_bitmap) {
i = __fls(req_bitmap); /* number of the last "high" queue */
req_bitmap &= ~BIT(i);
irq_handlers[HALF_QUEUES + i](irq_pdevs[HALF_QUEUES + i]);
ret = IRQ_HANDLED;
}
return ret;
}
static irqreturn_t qmgr_irq(int irq, void *pdev)
{
int i, half = (irq == IRQ_IXP4XX_QM1 ? 0 : 1);
u32 req_bitmap = __raw_readl(&qmgr_regs->irqstat[half]);
if (!req_bitmap)
return 0;
__raw_writel(req_bitmap, &qmgr_regs->irqstat[half]); /* ACK */
while (req_bitmap) {
i = __fls(req_bitmap); /* number of the last queue */
req_bitmap &= ~BIT(i);
i += half * HALF_QUEUES;
irq_handlers[i](irq_pdevs[i]);
}
return IRQ_HANDLED;
}
void qmgr_enable_irq(unsigned int queue)
{
unsigned long flags;
int half = queue / 32;
u32 mask = 1 << (queue & (HALF_QUEUES - 1));
spin_lock_irqsave(&qmgr_lock, flags);
__raw_writel(__raw_readl(&qmgr_regs->irqen[half]) | mask,
&qmgr_regs->irqen[half]);
spin_unlock_irqrestore(&qmgr_lock, flags);
}
void qmgr_disable_irq(unsigned int queue)
{
unsigned long flags;
int half = queue / 32;
u32 mask = 1 << (queue & (HALF_QUEUES - 1));
spin_lock_irqsave(&qmgr_lock, flags);
__raw_writel(__raw_readl(&qmgr_regs->irqen[half]) & ~mask,
&qmgr_regs->irqen[half]);
__raw_writel(mask, &qmgr_regs->irqstat[half]); /* clear */
spin_unlock_irqrestore(&qmgr_lock, flags);
}
static inline void shift_mask(u32 *mask)
{
mask[3] = mask[3] << 1 | mask[2] >> 31;
mask[2] = mask[2] << 1 | mask[1] >> 31;
mask[1] = mask[1] << 1 | mask[0] >> 31;
mask[0] <<= 1;
}
#if DEBUG_QMGR
int qmgr_request_queue(unsigned int queue, unsigned int len /* dwords */,
unsigned int nearly_empty_watermark,
unsigned int nearly_full_watermark,
const char *desc_format, const char* name)
#else
int __qmgr_request_queue(unsigned int queue, unsigned int len /* dwords */,
unsigned int nearly_empty_watermark,
unsigned int nearly_full_watermark)
#endif
{
u32 cfg, addr = 0, mask[4]; /* in 16-dwords */
int err;
BUG_ON(queue >= QUEUES);
if ((nearly_empty_watermark | nearly_full_watermark) & ~7)
return -EINVAL;
switch (len) {
case 16:
cfg = 0 << 24;
mask[0] = 0x1;
break;
case 32:
cfg = 1 << 24;
mask[0] = 0x3;
break;
case 64:
cfg = 2 << 24;
mask[0] = 0xF;
break;
case 128:
cfg = 3 << 24;
mask[0] = 0xFF;
break;
default:
return -EINVAL;
}
cfg |= nearly_empty_watermark << 26;
cfg |= nearly_full_watermark << 29;
len /= 16; /* in 16-dwords: 1, 2, 4 or 8 */
mask[1] = mask[2] = mask[3] = 0;
if (!try_module_get(THIS_MODULE))
return -ENODEV;
spin_lock_irq(&qmgr_lock);
if (__raw_readl(&qmgr_regs->sram[queue])) {
err = -EBUSY;
goto err;
}
while (1) {
if (!(used_sram_bitmap[0] & mask[0]) &&
!(used_sram_bitmap[1] & mask[1]) &&
!(used_sram_bitmap[2] & mask[2]) &&
!(used_sram_bitmap[3] & mask[3]))
break; /* found free space */
addr++;
shift_mask(mask);
if (addr + len > ARRAY_SIZE(qmgr_regs->sram)) {
printk(KERN_ERR "qmgr: no free SRAM space for"
" queue %i\n", queue);
err = -ENOMEM;
goto err;
}
}
used_sram_bitmap[0] |= mask[0];
used_sram_bitmap[1] |= mask[1];
used_sram_bitmap[2] |= mask[2];
used_sram_bitmap[3] |= mask[3];
__raw_writel(cfg | (addr << 14), &qmgr_regs->sram[queue]);
#if DEBUG_QMGR
snprintf(qmgr_queue_descs[queue], sizeof(qmgr_queue_descs[0]),
desc_format, name);
printk(KERN_DEBUG "qmgr: requested queue %s(%i) addr = 0x%02X\n",
qmgr_queue_descs[queue], queue, addr);
#endif
spin_unlock_irq(&qmgr_lock);
return 0;
err:
spin_unlock_irq(&qmgr_lock);
module_put(THIS_MODULE);
return err;
}
void qmgr_release_queue(unsigned int queue)
{
u32 cfg, addr, mask[4];
BUG_ON(queue >= QUEUES); /* not in valid range */
spin_lock_irq(&qmgr_lock);
cfg = __raw_readl(&qmgr_regs->sram[queue]);
addr = (cfg >> 14) & 0xFF;
BUG_ON(!addr); /* not requested */
switch ((cfg >> 24) & 3) {
case 0: mask[0] = 0x1; break;
case 1: mask[0] = 0x3; break;
case 2: mask[0] = 0xF; break;
case 3: mask[0] = 0xFF; break;
}
mask[1] = mask[2] = mask[3] = 0;
while (addr--)
shift_mask(mask);
#if DEBUG_QMGR
printk(KERN_DEBUG "qmgr: releasing queue %s(%i)\n",
qmgr_queue_descs[queue], queue);
qmgr_queue_descs[queue][0] = '\x0';
#endif
while ((addr = qmgr_get_entry(queue)))
printk(KERN_ERR "qmgr: released queue %i not empty: 0x%08X\n",
queue, addr);
__raw_writel(0, &qmgr_regs->sram[queue]);
used_sram_bitmap[0] &= ~mask[0];
used_sram_bitmap[1] &= ~mask[1];
used_sram_bitmap[2] &= ~mask[2];
used_sram_bitmap[3] &= ~mask[3];
irq_handlers[queue] = NULL; /* catch IRQ bugs */
spin_unlock_irq(&qmgr_lock);
module_put(THIS_MODULE);
}
static int qmgr_init(void)
{
int i, err;
irq_handler_t handler1, handler2;
mem_res = request_mem_region(IXP4XX_QMGR_BASE_PHYS,
IXP4XX_QMGR_REGION_SIZE,
"IXP4xx Queue Manager");
if (mem_res == NULL)
return -EBUSY;
qmgr_regs = ioremap(IXP4XX_QMGR_BASE_PHYS, IXP4XX_QMGR_REGION_SIZE);
if (qmgr_regs == NULL) {
err = -ENOMEM;
goto error_map;
}
/* reset qmgr registers */
for (i = 0; i < 4; i++) {
__raw_writel(0x33333333, &qmgr_regs->stat1[i]);
__raw_writel(0, &qmgr_regs->irqsrc[i]);
}
for (i = 0; i < 2; i++) {
__raw_writel(0, &qmgr_regs->stat2[i]);
__raw_writel(0xFFFFFFFF, &qmgr_regs->irqstat[i]); /* clear */
__raw_writel(0, &qmgr_regs->irqen[i]);
}
__raw_writel(0xFFFFFFFF, &qmgr_regs->statne_h);
__raw_writel(0, &qmgr_regs->statf_h);
for (i = 0; i < QUEUES; i++)
__raw_writel(0, &qmgr_regs->sram[i]);
if (cpu_is_ixp42x_rev_a0()) {
handler1 = qmgr_irq1_a0;
handler2 = qmgr_irq2_a0;
} else
handler1 = handler2 = qmgr_irq;
err = request_irq(IRQ_IXP4XX_QM1, handler1, 0, "IXP4xx Queue Manager",
NULL);
if (err) {
printk(KERN_ERR "qmgr: failed to request IRQ%i (%i)\n",
IRQ_IXP4XX_QM1, err);
goto error_irq;
}
err = request_irq(IRQ_IXP4XX_QM2, handler2, 0, "IXP4xx Queue Manager",
NULL);
if (err) {
printk(KERN_ERR "qmgr: failed to request IRQ%i (%i)\n",
IRQ_IXP4XX_QM2, err);
goto error_irq2;
}
used_sram_bitmap[0] = 0xF; /* 4 first pages reserved for config */
spin_lock_init(&qmgr_lock);
printk(KERN_INFO "IXP4xx Queue Manager initialized.\n");
return 0;
error_irq2:
free_irq(IRQ_IXP4XX_QM1, NULL);
error_irq:
iounmap(qmgr_regs);
error_map:
release_mem_region(IXP4XX_QMGR_BASE_PHYS, IXP4XX_QMGR_REGION_SIZE);
return err;
}
static void qmgr_remove(void)
{
free_irq(IRQ_IXP4XX_QM1, NULL);
free_irq(IRQ_IXP4XX_QM2, NULL);
synchronize_irq(IRQ_IXP4XX_QM1);
synchronize_irq(IRQ_IXP4XX_QM2);
iounmap(qmgr_regs);
release_mem_region(IXP4XX_QMGR_BASE_PHYS, IXP4XX_QMGR_REGION_SIZE);
}
module_init(qmgr_init);
module_exit(qmgr_remove);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Krzysztof Halasa");
EXPORT_SYMBOL(qmgr_regs);
EXPORT_SYMBOL(qmgr_set_irq);
EXPORT_SYMBOL(qmgr_enable_irq);
EXPORT_SYMBOL(qmgr_disable_irq);
#if DEBUG_QMGR
EXPORT_SYMBOL(qmgr_queue_descs);
EXPORT_SYMBOL(qmgr_request_queue);
#else
EXPORT_SYMBOL(__qmgr_request_queue);
#endif
EXPORT_SYMBOL(qmgr_release_queue);
| gpl-2.0 |
AndroidGX/SimpleGX-JB-4.3 | drivers/net/wimax/i2400m/sdio-tx.c | 9095 | 5653 | /*
* Intel Wireless WiMAX Connection 2400m
* SDIO TX transaction backends
*
*
* Copyright (C) 2007-2008 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Intel Corporation <linux-wimax@intel.com>
* Dirk Brandewie <dirk.j.brandewie@intel.com>
* - Initial implementation
*
*
* Takes the TX messages in the i2400m's driver TX FIFO and sends them
* to the device until there are no more.
*
* If we fail sending the message, we just drop it. There isn't much
* we can do at this point. Most of the traffic is network, which has
* recovery methods for dropped packets.
*
* The SDIO functions are not atomic, so we can't run from the context
* where i2400m->bus_tx_kick() [i2400ms_bus_tx_kick()] is being called
* (some times atomic). Thus, the actual TX work is deferred to a
* workqueue.
*
* ROADMAP
*
* i2400ms_bus_tx_kick()
* i2400ms_tx_submit() [through workqueue]
*
* i2400m_tx_setup()
*
* i2400m_tx_release()
*/
#include <linux/mmc/sdio_func.h>
#include "i2400m-sdio.h"
#define D_SUBMODULE tx
#include "sdio-debug-levels.h"
/*
* Pull TX transations from the TX FIFO and send them to the device
* until there are no more.
*/
static
void i2400ms_tx_submit(struct work_struct *ws)
{
int result;
struct i2400ms *i2400ms = container_of(ws, struct i2400ms, tx_worker);
struct i2400m *i2400m = &i2400ms->i2400m;
struct sdio_func *func = i2400ms->func;
struct device *dev = &func->dev;
struct i2400m_msg_hdr *tx_msg;
size_t tx_msg_size;
d_fnstart(4, dev, "(i2400ms %p, i2400m %p)\n", i2400ms, i2400ms);
while (NULL != (tx_msg = i2400m_tx_msg_get(i2400m, &tx_msg_size))) {
d_printf(2, dev, "TX: submitting %zu bytes\n", tx_msg_size);
d_dump(5, dev, tx_msg, tx_msg_size);
sdio_claim_host(func);
result = sdio_memcpy_toio(func, 0, tx_msg, tx_msg_size);
sdio_release_host(func);
i2400m_tx_msg_sent(i2400m);
if (result < 0) {
dev_err(dev, "TX: cannot submit TX; tx_msg @%zu %zu B:"
" %d\n", (void *) tx_msg - i2400m->tx_buf,
tx_msg_size, result);
}
if (result == -ETIMEDOUT) {
i2400m_error_recovery(i2400m);
break;
}
d_printf(2, dev, "TX: %zub submitted\n", tx_msg_size);
}
d_fnend(4, dev, "(i2400ms %p) = void\n", i2400ms);
}
/*
* The generic driver notifies us that there is data ready for TX
*
* Schedule a run of i2400ms_tx_submit() to handle it.
*/
void i2400ms_bus_tx_kick(struct i2400m *i2400m)
{
struct i2400ms *i2400ms = container_of(i2400m, struct i2400ms, i2400m);
struct device *dev = &i2400ms->func->dev;
unsigned long flags;
d_fnstart(3, dev, "(i2400m %p) = void\n", i2400m);
/* schedule tx work, this is because tx may block, therefore
* it has to run in a thread context.
*/
spin_lock_irqsave(&i2400m->tx_lock, flags);
if (i2400ms->tx_workqueue != NULL)
queue_work(i2400ms->tx_workqueue, &i2400ms->tx_worker);
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
d_fnend(3, dev, "(i2400m %p) = void\n", i2400m);
}
int i2400ms_tx_setup(struct i2400ms *i2400ms)
{
int result;
struct device *dev = &i2400ms->func->dev;
struct i2400m *i2400m = &i2400ms->i2400m;
struct workqueue_struct *tx_workqueue;
unsigned long flags;
d_fnstart(5, dev, "(i2400ms %p)\n", i2400ms);
INIT_WORK(&i2400ms->tx_worker, i2400ms_tx_submit);
snprintf(i2400ms->tx_wq_name, sizeof(i2400ms->tx_wq_name),
"%s-tx", i2400m->wimax_dev.name);
tx_workqueue =
create_singlethread_workqueue(i2400ms->tx_wq_name);
if (tx_workqueue == NULL) {
dev_err(dev, "TX: failed to create workqueue\n");
result = -ENOMEM;
} else
result = 0;
spin_lock_irqsave(&i2400m->tx_lock, flags);
i2400ms->tx_workqueue = tx_workqueue;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
d_fnend(5, dev, "(i2400ms %p) = %d\n", i2400ms, result);
return result;
}
void i2400ms_tx_release(struct i2400ms *i2400ms)
{
struct i2400m *i2400m = &i2400ms->i2400m;
struct workqueue_struct *tx_workqueue;
unsigned long flags;
tx_workqueue = i2400ms->tx_workqueue;
spin_lock_irqsave(&i2400m->tx_lock, flags);
i2400ms->tx_workqueue = NULL;
spin_unlock_irqrestore(&i2400m->tx_lock, flags);
if (tx_workqueue)
destroy_workqueue(tx_workqueue);
}
| gpl-2.0 |
Kwiboo/kernel_samsung_crespo | drivers/video/sysimgblt.c | 12167 | 6937 | /*
* Generic 1-bit or 8-bit source to 1-32 bit destination expansion
* for frame buffer located in system RAM with packed pixels of any depth.
*
* Based almost entirely on cfbimgblt.c
*
* Copyright (C) April 2007 Antonino Daplas <adaplas@pol.net>
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fb.h>
#include <asm/types.h>
#define DEBUG
#ifdef DEBUG
#define DPRINTK(fmt, args...) printk(KERN_DEBUG "%s: " fmt,__func__,## args)
#else
#define DPRINTK(fmt, args...)
#endif
static const u32 cfb_tab8_be[] = {
0x00000000,0x000000ff,0x0000ff00,0x0000ffff,
0x00ff0000,0x00ff00ff,0x00ffff00,0x00ffffff,
0xff000000,0xff0000ff,0xff00ff00,0xff00ffff,
0xffff0000,0xffff00ff,0xffffff00,0xffffffff
};
static const u32 cfb_tab8_le[] = {
0x00000000,0xff000000,0x00ff0000,0xffff0000,
0x0000ff00,0xff00ff00,0x00ffff00,0xffffff00,
0x000000ff,0xff0000ff,0x00ff00ff,0xffff00ff,
0x0000ffff,0xff00ffff,0x00ffffff,0xffffffff
};
static const u32 cfb_tab16_be[] = {
0x00000000, 0x0000ffff, 0xffff0000, 0xffffffff
};
static const u32 cfb_tab16_le[] = {
0x00000000, 0xffff0000, 0x0000ffff, 0xffffffff
};
static const u32 cfb_tab32[] = {
0x00000000, 0xffffffff
};
static void color_imageblit(const struct fb_image *image, struct fb_info *p,
void *dst1, u32 start_index, u32 pitch_index)
{
/* Draw the penguin */
u32 *dst, *dst2;
u32 color = 0, val, shift;
int i, n, bpp = p->var.bits_per_pixel;
u32 null_bits = 32 - bpp;
u32 *palette = (u32 *) p->pseudo_palette;
const u8 *src = image->data;
dst2 = dst1;
for (i = image->height; i--; ) {
n = image->width;
dst = dst1;
shift = 0;
val = 0;
if (start_index) {
u32 start_mask = ~(FB_SHIFT_HIGH(p, ~(u32)0,
start_index));
val = *dst & start_mask;
shift = start_index;
}
while (n--) {
if (p->fix.visual == FB_VISUAL_TRUECOLOR ||
p->fix.visual == FB_VISUAL_DIRECTCOLOR )
color = palette[*src];
else
color = *src;
color <<= FB_LEFT_POS(p, bpp);
val |= FB_SHIFT_HIGH(p, color, shift);
if (shift >= null_bits) {
*dst++ = val;
val = (shift == null_bits) ? 0 :
FB_SHIFT_LOW(p, color, 32 - shift);
}
shift += bpp;
shift &= (32 - 1);
src++;
}
if (shift) {
u32 end_mask = FB_SHIFT_HIGH(p, ~(u32)0, shift);
*dst &= end_mask;
*dst |= val;
}
dst1 += p->fix.line_length;
if (pitch_index) {
dst2 += p->fix.line_length;
dst1 = (u8 *)((long)dst2 & ~(sizeof(u32) - 1));
start_index += pitch_index;
start_index &= 32 - 1;
}
}
}
static void slow_imageblit(const struct fb_image *image, struct fb_info *p,
void *dst1, u32 fgcolor, u32 bgcolor,
u32 start_index, u32 pitch_index)
{
u32 shift, color = 0, bpp = p->var.bits_per_pixel;
u32 *dst, *dst2;
u32 val, pitch = p->fix.line_length;
u32 null_bits = 32 - bpp;
u32 spitch = (image->width+7)/8;
const u8 *src = image->data, *s;
u32 i, j, l;
dst2 = dst1;
fgcolor <<= FB_LEFT_POS(p, bpp);
bgcolor <<= FB_LEFT_POS(p, bpp);
for (i = image->height; i--; ) {
shift = val = 0;
l = 8;
j = image->width;
dst = dst1;
s = src;
/* write leading bits */
if (start_index) {
u32 start_mask = ~(FB_SHIFT_HIGH(p, ~(u32)0,
start_index));
val = *dst & start_mask;
shift = start_index;
}
while (j--) {
l--;
color = (*s & (1 << l)) ? fgcolor : bgcolor;
val |= FB_SHIFT_HIGH(p, color, shift);
/* Did the bitshift spill bits to the next long? */
if (shift >= null_bits) {
*dst++ = val;
val = (shift == null_bits) ? 0 :
FB_SHIFT_LOW(p, color, 32 - shift);
}
shift += bpp;
shift &= (32 - 1);
if (!l) { l = 8; s++; };
}
/* write trailing bits */
if (shift) {
u32 end_mask = FB_SHIFT_HIGH(p, ~(u32)0, shift);
*dst &= end_mask;
*dst |= val;
}
dst1 += pitch;
src += spitch;
if (pitch_index) {
dst2 += pitch;
dst1 = (u8 *)((long)dst2 & ~(sizeof(u32) - 1));
start_index += pitch_index;
start_index &= 32 - 1;
}
}
}
/*
* fast_imageblit - optimized monochrome color expansion
*
* Only if: bits_per_pixel == 8, 16, or 32
* image->width is divisible by pixel/dword (ppw);
* fix->line_legth is divisible by 4;
* beginning and end of a scanline is dword aligned
*/
static void fast_imageblit(const struct fb_image *image, struct fb_info *p,
void *dst1, u32 fgcolor, u32 bgcolor)
{
u32 fgx = fgcolor, bgx = bgcolor, bpp = p->var.bits_per_pixel;
u32 ppw = 32/bpp, spitch = (image->width + 7)/8;
u32 bit_mask, end_mask, eorx, shift;
const char *s = image->data, *src;
u32 *dst;
const u32 *tab = NULL;
int i, j, k;
switch (bpp) {
case 8:
tab = fb_be_math(p) ? cfb_tab8_be : cfb_tab8_le;
break;
case 16:
tab = fb_be_math(p) ? cfb_tab16_be : cfb_tab16_le;
break;
case 32:
default:
tab = cfb_tab32;
break;
}
for (i = ppw-1; i--; ) {
fgx <<= bpp;
bgx <<= bpp;
fgx |= fgcolor;
bgx |= bgcolor;
}
bit_mask = (1 << ppw) - 1;
eorx = fgx ^ bgx;
k = image->width/ppw;
for (i = image->height; i--; ) {
dst = dst1;
shift = 8;
src = s;
for (j = k; j--; ) {
shift -= ppw;
end_mask = tab[(*src >> shift) & bit_mask];
*dst++ = (end_mask & eorx) ^ bgx;
if (!shift) {
shift = 8;
src++;
}
}
dst1 += p->fix.line_length;
s += spitch;
}
}
void sys_imageblit(struct fb_info *p, const struct fb_image *image)
{
u32 fgcolor, bgcolor, start_index, bitstart, pitch_index = 0;
u32 bpl = sizeof(u32), bpp = p->var.bits_per_pixel;
u32 width = image->width;
u32 dx = image->dx, dy = image->dy;
void *dst1;
if (p->state != FBINFO_STATE_RUNNING)
return;
bitstart = (dy * p->fix.line_length * 8) + (dx * bpp);
start_index = bitstart & (32 - 1);
pitch_index = (p->fix.line_length & (bpl - 1)) * 8;
bitstart /= 8;
bitstart &= ~(bpl - 1);
dst1 = (void __force *)p->screen_base + bitstart;
if (p->fbops->fb_sync)
p->fbops->fb_sync(p);
if (image->depth == 1) {
if (p->fix.visual == FB_VISUAL_TRUECOLOR ||
p->fix.visual == FB_VISUAL_DIRECTCOLOR) {
fgcolor = ((u32*)(p->pseudo_palette))[image->fg_color];
bgcolor = ((u32*)(p->pseudo_palette))[image->bg_color];
} else {
fgcolor = image->fg_color;
bgcolor = image->bg_color;
}
if (32 % bpp == 0 && !start_index && !pitch_index &&
((width & (32/bpp-1)) == 0) &&
bpp >= 8 && bpp <= 32)
fast_imageblit(image, p, dst1, fgcolor, bgcolor);
else
slow_imageblit(image, p, dst1, fgcolor, bgcolor,
start_index, pitch_index);
} else
color_imageblit(image, p, dst1, start_index, pitch_index);
}
EXPORT_SYMBOL(sys_imageblit);
MODULE_AUTHOR("Antonino Daplas <adaplas@pol.net>");
MODULE_DESCRIPTION("1-bit/8-bit to 1-32 bit color expansion (sys-to-sys)");
MODULE_LICENSE("GPL");
| gpl-2.0 |
faux123/mainline-crack | arch/arm/mach-pxa/idp.c | 136 | 6240 | /*
* linux/arch/arm/mach-pxa/idp.c
*
* 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.
*
* Copyright (c) 2001 Cliff Brake, Accelent Systems Inc.
*
* 2001-09-13: Cliff Brake <cbrake@accelent.com>
* Initial code
*
* 2005-02-15: Cliff Brake <cliff.brake@gmail.com>
* <http://www.vibren.com> <http://bec-systems.com>
* Updated for 2.6 kernel
*
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/platform_device.h>
#include <linux/fb.h>
#include <asm/setup.h>
#include <asm/memory.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include "pxa25x.h"
#include "idp.h"
#include <linux/platform_data/video-pxafb.h>
#include <mach/bitfield.h>
#include <linux/platform_data/mmc-pxamci.h>
#include <linux/smc91x.h>
#include "generic.h"
#include "devices.h"
/* TODO:
* - add pxa2xx_audio_ops_t device structure
* - Ethernet interrupt
*/
static unsigned long idp_pin_config[] __initdata = {
/* LCD */
GPIOxx_LCD_DSTN_16BPP,
/* BTUART */
GPIO42_BTUART_RXD,
GPIO43_BTUART_TXD,
GPIO44_BTUART_CTS,
GPIO45_BTUART_RTS,
/* STUART */
GPIO46_STUART_RXD,
GPIO47_STUART_TXD,
/* MMC */
GPIO6_MMC_CLK,
GPIO8_MMC_CS0,
/* Ethernet */
GPIO33_nCS_5, /* Ethernet CS */
GPIO4_GPIO, /* Ethernet IRQ */
};
static struct resource smc91x_resources[] = {
[0] = {
.start = (IDP_ETH_PHYS + 0x300),
.end = (IDP_ETH_PHYS + 0xfffff),
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PXA_GPIO_TO_IRQ(4),
.end = PXA_GPIO_TO_IRQ(4),
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE,
}
};
static struct smc91x_platdata smc91x_platdata = {
.flags = SMC91X_USE_32BIT | SMC91X_USE_DMA | SMC91X_NOWAIT,
};
static struct platform_device smc91x_device = {
.name = "smc91x",
.id = 0,
.num_resources = ARRAY_SIZE(smc91x_resources),
.resource = smc91x_resources,
.dev.platform_data = &smc91x_platdata,
};
static void idp_backlight_power(int on)
{
if (on) {
IDP_CPLD_LCD |= (1<<1);
} else {
IDP_CPLD_LCD &= ~(1<<1);
}
}
static void idp_vlcd(int on)
{
if (on) {
IDP_CPLD_LCD |= (1<<2);
} else {
IDP_CPLD_LCD &= ~(1<<2);
}
}
static void idp_lcd_power(int on, struct fb_var_screeninfo *var)
{
if (on) {
IDP_CPLD_LCD |= (1<<0);
} else {
IDP_CPLD_LCD &= ~(1<<0);
}
/* call idp_vlcd for now as core driver does not support
* both power and vlcd hooks. Note, this is not technically
* the correct sequence, but seems to work. Disclaimer:
* this may eventually damage the display.
*/
idp_vlcd(on);
}
static struct pxafb_mode_info sharp_lm8v31_mode = {
.pixclock = 270000,
.xres = 640,
.yres = 480,
.bpp = 16,
.hsync_len = 1,
.left_margin = 3,
.right_margin = 3,
.vsync_len = 1,
.upper_margin = 0,
.lower_margin = 0,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
.cmap_greyscale = 0,
};
static struct pxafb_mach_info sharp_lm8v31 = {
.modes = &sharp_lm8v31_mode,
.num_modes = 1,
.cmap_inverse = 0,
.cmap_static = 0,
.lcd_conn = LCD_COLOR_DSTN_16BPP | LCD_PCLK_EDGE_FALL |
LCD_AC_BIAS_FREQ(255),
.pxafb_backlight_power = &idp_backlight_power,
.pxafb_lcd_power = &idp_lcd_power
};
static struct pxamci_platform_data idp_mci_platform_data = {
.ocr_mask = MMC_VDD_32_33|MMC_VDD_33_34,
.gpio_card_detect = -1,
.gpio_card_ro = -1,
.gpio_power = -1,
};
static void __init idp_init(void)
{
printk("idp_init()\n");
pxa2xx_mfp_config(ARRAY_AND_SIZE(idp_pin_config));
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
platform_device_register(&smc91x_device);
//platform_device_register(&mst_audio_device);
pxa_set_fb_info(NULL, &sharp_lm8v31);
pxa_set_mci_info(&idp_mci_platform_data);
}
static struct map_desc idp_io_desc[] __initdata = {
{
.virtual = IDP_COREVOLT_VIRT,
.pfn = __phys_to_pfn(IDP_COREVOLT_PHYS),
.length = IDP_COREVOLT_SIZE,
.type = MT_DEVICE
}, {
.virtual = IDP_CPLD_VIRT,
.pfn = __phys_to_pfn(IDP_CPLD_PHYS),
.length = IDP_CPLD_SIZE,
.type = MT_DEVICE
}
};
static void __init idp_map_io(void)
{
pxa25x_map_io();
iotable_init(idp_io_desc, ARRAY_SIZE(idp_io_desc));
}
/* LEDs */
#if defined(CONFIG_NEW_LEDS) && defined(CONFIG_LEDS_CLASS)
struct idp_led {
struct led_classdev cdev;
u8 mask;
};
/*
* The triggers lines up below will only be used if the
* LED triggers are compiled in.
*/
static const struct {
const char *name;
const char *trigger;
} idp_leds[] = {
{ "idp:green", "heartbeat", },
{ "idp:red", "cpu0", },
};
static void idp_led_set(struct led_classdev *cdev,
enum led_brightness b)
{
struct idp_led *led = container_of(cdev,
struct idp_led, cdev);
u32 reg = IDP_CPLD_LED_CONTROL;
if (b != LED_OFF)
reg &= ~led->mask;
else
reg |= led->mask;
IDP_CPLD_LED_CONTROL = reg;
}
static enum led_brightness idp_led_get(struct led_classdev *cdev)
{
struct idp_led *led = container_of(cdev,
struct idp_led, cdev);
return (IDP_CPLD_LED_CONTROL & led->mask) ? LED_OFF : LED_FULL;
}
static int __init idp_leds_init(void)
{
int i;
if (!machine_is_pxa_idp())
return -ENODEV;
for (i = 0; i < ARRAY_SIZE(idp_leds); i++) {
struct idp_led *led;
led = kzalloc(sizeof(*led), GFP_KERNEL);
if (!led)
break;
led->cdev.name = idp_leds[i].name;
led->cdev.brightness_set = idp_led_set;
led->cdev.brightness_get = idp_led_get;
led->cdev.default_trigger = idp_leds[i].trigger;
if (i == 0)
led->mask = IDP_HB_LED;
else
led->mask = IDP_BUSY_LED;
if (led_classdev_register(NULL, &led->cdev) < 0) {
kfree(led);
break;
}
}
return 0;
}
/*
* Since we may have triggers on any subsystem, defer registration
* until after subsystem_init.
*/
fs_initcall(idp_leds_init);
#endif
MACHINE_START(PXA_IDP, "Vibren PXA255 IDP")
/* Maintainer: Vibren Technologies */
.map_io = idp_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa25x_init_irq,
.handle_irq = pxa25x_handle_irq,
.init_time = pxa_timer_init,
.init_machine = idp_init,
.restart = pxa_restart,
MACHINE_END
| gpl-2.0 |
igou/gcc | gcc/testsuite/gfortran.dg/forall_4.f90 | 136 | 1703 | ! { dg-do run }
! Tests the fix for PR25072, in which mask expressions
! that start with an internal or intrinsic function
! reference would give a syntax error.
!
! The fix for PR28119 is tested as well; here, the forall
! statement could not be followed by another statement on
! the same line.
!
! Contributed by Paul Thomas <pault@gcc.gnu.org>
!
module foo
integer, parameter :: n = 4
contains
pure logical function foot (i)
integer, intent(in) :: i
foot = (i == 2) .or. (i == 3)
end function foot
end module foo
use foo
integer :: i, a(n)
logical :: s(n)
s = (/(foot (i), i=1, n)/)
! Check that non-mask case is still OK and the fix for PR28119
a = 0
forall (i=1:n) a(i) = i ; if (any (a .ne. (/1,2,3,4/))) call abort ()
! Now a mask using a function with an explicit interface
! via use association.
a = 0
forall (i=1:n, foot (i)) a(i) = i
if (any (a .ne. (/0,2,3,0/))) call abort ()
! Now an array variable mask
a = 0
forall (i=1:n, .not. s(i)) a(i) = i
if (any (a .ne. (/1,0,0,4/))) call abort ()
! This was the PR - an internal function mask
a = 0
forall (i=1:n, t (i)) a(i) = i
if (any (a .ne. (/0,2,0,4/))) call abort ()
! Check that an expression is OK - this also gave a syntax
! error
a = 0
forall (i=1:n, mod (i, 2) == 0) a(i) = i
if (any (a .ne. (/0,2,0,4/))) call abort ()
! And that an expression that used to work is OK
a = 0
forall (i=1:n, s (i) .or. t(i)) a(i) = w (i)
if (any (a .ne. (/0,3,2,1/))) call abort ()
contains
pure logical function t(i)
integer, intent(in) :: i
t = (mod (i, 2) == 0)
end function t
pure integer function w(i)
integer, intent(in) :: i
w = 5 - i
end function w
end
| gpl-2.0 |
bradfa/linux | mm/page_ext.c | 136 | 11711 | #include <linux/mm.h>
#include <linux/mmzone.h>
#include <linux/bootmem.h>
#include <linux/page_ext.h>
#include <linux/memory.h>
#include <linux/vmalloc.h>
#include <linux/kmemleak.h>
#include <linux/page_owner.h>
#include <linux/page_idle.h>
/*
* struct page extension
*
* This is the feature to manage memory for extended data per page.
*
* Until now, we must modify struct page itself to store extra data per page.
* This requires rebuilding the kernel and it is really time consuming process.
* And, sometimes, rebuild is impossible due to third party module dependency.
* At last, enlarging struct page could cause un-wanted system behaviour change.
*
* This feature is intended to overcome above mentioned problems. This feature
* allocates memory for extended data per page in certain place rather than
* the struct page itself. This memory can be accessed by the accessor
* functions provided by this code. During the boot process, it checks whether
* allocation of huge chunk of memory is needed or not. If not, it avoids
* allocating memory at all. With this advantage, we can include this feature
* into the kernel in default and can avoid rebuild and solve related problems.
*
* To help these things to work well, there are two callbacks for clients. One
* is the need callback which is mandatory if user wants to avoid useless
* memory allocation at boot-time. The other is optional, init callback, which
* is used to do proper initialization after memory is allocated.
*
* The need callback is used to decide whether extended memory allocation is
* needed or not. Sometimes users want to deactivate some features in this
* boot and extra memory would be unneccessary. In this case, to avoid
* allocating huge chunk of memory, each clients represent their need of
* extra memory through the need callback. If one of the need callbacks
* returns true, it means that someone needs extra memory so that
* page extension core should allocates memory for page extension. If
* none of need callbacks return true, memory isn't needed at all in this boot
* and page extension core can skip to allocate memory. As result,
* none of memory is wasted.
*
* When need callback returns true, page_ext checks if there is a request for
* extra memory through size in struct page_ext_operations. If it is non-zero,
* extra space is allocated for each page_ext entry and offset is returned to
* user through offset in struct page_ext_operations.
*
* The init callback is used to do proper initialization after page extension
* is completely initialized. In sparse memory system, extra memory is
* allocated some time later than memmap is allocated. In other words, lifetime
* of memory for page extension isn't same with memmap for struct page.
* Therefore, clients can't store extra data until page extension is
* initialized, even if pages are allocated and used freely. This could
* cause inadequate state of extra data per page, so, to prevent it, client
* can utilize this callback to initialize the state of it correctly.
*/
static struct page_ext_operations *page_ext_ops[] = {
&debug_guardpage_ops,
#ifdef CONFIG_PAGE_POISONING
&page_poisoning_ops,
#endif
#ifdef CONFIG_PAGE_OWNER
&page_owner_ops,
#endif
#if defined(CONFIG_IDLE_PAGE_TRACKING) && !defined(CONFIG_64BIT)
&page_idle_ops,
#endif
};
static unsigned long total_usage;
static unsigned long extra_mem;
static bool __init invoke_need_callbacks(void)
{
int i;
int entries = ARRAY_SIZE(page_ext_ops);
bool need = false;
for (i = 0; i < entries; i++) {
if (page_ext_ops[i]->need && page_ext_ops[i]->need()) {
page_ext_ops[i]->offset = sizeof(struct page_ext) +
extra_mem;
extra_mem += page_ext_ops[i]->size;
need = true;
}
}
return need;
}
static void __init invoke_init_callbacks(void)
{
int i;
int entries = ARRAY_SIZE(page_ext_ops);
for (i = 0; i < entries; i++) {
if (page_ext_ops[i]->init)
page_ext_ops[i]->init();
}
}
static unsigned long get_entry_size(void)
{
return sizeof(struct page_ext) + extra_mem;
}
static inline struct page_ext *get_entry(void *base, unsigned long index)
{
return base + get_entry_size() * index;
}
#if !defined(CONFIG_SPARSEMEM)
void __meminit pgdat_page_ext_init(struct pglist_data *pgdat)
{
pgdat->node_page_ext = NULL;
}
struct page_ext *lookup_page_ext(struct page *page)
{
unsigned long pfn = page_to_pfn(page);
unsigned long index;
struct page_ext *base;
base = NODE_DATA(page_to_nid(page))->node_page_ext;
#if defined(CONFIG_DEBUG_VM) || defined(CONFIG_PAGE_POISONING)
/*
* The sanity checks the page allocator does upon freeing a
* page can reach here before the page_ext arrays are
* allocated when feeding a range of pages to the allocator
* for the first time during bootup or memory hotplug.
*
* This check is also necessary for ensuring page poisoning
* works as expected when enabled
*/
if (unlikely(!base))
return NULL;
#endif
index = pfn - round_down(node_start_pfn(page_to_nid(page)),
MAX_ORDER_NR_PAGES);
return get_entry(base, index);
}
static int __init alloc_node_page_ext(int nid)
{
struct page_ext *base;
unsigned long table_size;
unsigned long nr_pages;
nr_pages = NODE_DATA(nid)->node_spanned_pages;
if (!nr_pages)
return 0;
/*
* Need extra space if node range is not aligned with
* MAX_ORDER_NR_PAGES. When page allocator's buddy algorithm
* checks buddy's status, range could be out of exact node range.
*/
if (!IS_ALIGNED(node_start_pfn(nid), MAX_ORDER_NR_PAGES) ||
!IS_ALIGNED(node_end_pfn(nid), MAX_ORDER_NR_PAGES))
nr_pages += MAX_ORDER_NR_PAGES;
table_size = get_entry_size() * nr_pages;
base = memblock_virt_alloc_try_nid_nopanic(
table_size, PAGE_SIZE, __pa(MAX_DMA_ADDRESS),
BOOTMEM_ALLOC_ACCESSIBLE, nid);
if (!base)
return -ENOMEM;
NODE_DATA(nid)->node_page_ext = base;
total_usage += table_size;
return 0;
}
void __init page_ext_init_flatmem(void)
{
int nid, fail;
if (!invoke_need_callbacks())
return;
for_each_online_node(nid) {
fail = alloc_node_page_ext(nid);
if (fail)
goto fail;
}
pr_info("allocated %ld bytes of page_ext\n", total_usage);
invoke_init_callbacks();
return;
fail:
pr_crit("allocation of page_ext failed.\n");
panic("Out of memory");
}
#else /* CONFIG_FLAT_NODE_MEM_MAP */
struct page_ext *lookup_page_ext(struct page *page)
{
unsigned long pfn = page_to_pfn(page);
struct mem_section *section = __pfn_to_section(pfn);
#if defined(CONFIG_DEBUG_VM) || defined(CONFIG_PAGE_POISONING)
/*
* The sanity checks the page allocator does upon freeing a
* page can reach here before the page_ext arrays are
* allocated when feeding a range of pages to the allocator
* for the first time during bootup or memory hotplug.
*
* This check is also necessary for ensuring page poisoning
* works as expected when enabled
*/
if (!section->page_ext)
return NULL;
#endif
return get_entry(section->page_ext, pfn);
}
static void *__meminit alloc_page_ext(size_t size, int nid)
{
gfp_t flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN;
void *addr = NULL;
addr = alloc_pages_exact_nid(nid, size, flags);
if (addr) {
kmemleak_alloc(addr, size, 1, flags);
return addr;
}
if (node_state(nid, N_HIGH_MEMORY))
addr = vzalloc_node(size, nid);
else
addr = vzalloc(size);
return addr;
}
static int __meminit init_section_page_ext(unsigned long pfn, int nid)
{
struct mem_section *section;
struct page_ext *base;
unsigned long table_size;
section = __pfn_to_section(pfn);
if (section->page_ext)
return 0;
table_size = get_entry_size() * PAGES_PER_SECTION;
base = alloc_page_ext(table_size, nid);
/*
* The value stored in section->page_ext is (base - pfn)
* and it does not point to the memory block allocated above,
* causing kmemleak false positives.
*/
kmemleak_not_leak(base);
if (!base) {
pr_err("page ext allocation failure\n");
return -ENOMEM;
}
/*
* The passed "pfn" may not be aligned to SECTION. For the calculation
* we need to apply a mask.
*/
pfn &= PAGE_SECTION_MASK;
section->page_ext = (void *)base - get_entry_size() * pfn;
total_usage += table_size;
return 0;
}
#ifdef CONFIG_MEMORY_HOTPLUG
static void free_page_ext(void *addr)
{
if (is_vmalloc_addr(addr)) {
vfree(addr);
} else {
struct page *page = virt_to_page(addr);
size_t table_size;
table_size = get_entry_size() * PAGES_PER_SECTION;
BUG_ON(PageReserved(page));
free_pages_exact(addr, table_size);
}
}
static void __free_page_ext(unsigned long pfn)
{
struct mem_section *ms;
struct page_ext *base;
ms = __pfn_to_section(pfn);
if (!ms || !ms->page_ext)
return;
base = get_entry(ms->page_ext, pfn);
free_page_ext(base);
ms->page_ext = NULL;
}
static int __meminit online_page_ext(unsigned long start_pfn,
unsigned long nr_pages,
int nid)
{
unsigned long start, end, pfn;
int fail = 0;
start = SECTION_ALIGN_DOWN(start_pfn);
end = SECTION_ALIGN_UP(start_pfn + nr_pages);
if (nid == -1) {
/*
* In this case, "nid" already exists and contains valid memory.
* "start_pfn" passed to us is a pfn which is an arg for
* online__pages(), and start_pfn should exist.
*/
nid = pfn_to_nid(start_pfn);
VM_BUG_ON(!node_state(nid, N_ONLINE));
}
for (pfn = start; !fail && pfn < end; pfn += PAGES_PER_SECTION) {
if (!pfn_present(pfn))
continue;
fail = init_section_page_ext(pfn, nid);
}
if (!fail)
return 0;
/* rollback */
for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
__free_page_ext(pfn);
return -ENOMEM;
}
static int __meminit offline_page_ext(unsigned long start_pfn,
unsigned long nr_pages, int nid)
{
unsigned long start, end, pfn;
start = SECTION_ALIGN_DOWN(start_pfn);
end = SECTION_ALIGN_UP(start_pfn + nr_pages);
for (pfn = start; pfn < end; pfn += PAGES_PER_SECTION)
__free_page_ext(pfn);
return 0;
}
static int __meminit page_ext_callback(struct notifier_block *self,
unsigned long action, void *arg)
{
struct memory_notify *mn = arg;
int ret = 0;
switch (action) {
case MEM_GOING_ONLINE:
ret = online_page_ext(mn->start_pfn,
mn->nr_pages, mn->status_change_nid);
break;
case MEM_OFFLINE:
offline_page_ext(mn->start_pfn,
mn->nr_pages, mn->status_change_nid);
break;
case MEM_CANCEL_ONLINE:
offline_page_ext(mn->start_pfn,
mn->nr_pages, mn->status_change_nid);
break;
case MEM_GOING_OFFLINE:
break;
case MEM_ONLINE:
case MEM_CANCEL_OFFLINE:
break;
}
return notifier_from_errno(ret);
}
#endif
void __init page_ext_init(void)
{
unsigned long pfn;
int nid;
if (!invoke_need_callbacks())
return;
for_each_node_state(nid, N_MEMORY) {
unsigned long start_pfn, end_pfn;
start_pfn = node_start_pfn(nid);
end_pfn = node_end_pfn(nid);
/*
* start_pfn and end_pfn may not be aligned to SECTION and the
* page->flags of out of node pages are not initialized. So we
* scan [start_pfn, the biggest section's pfn < end_pfn) here.
*/
for (pfn = start_pfn; pfn < end_pfn;
pfn = ALIGN(pfn + 1, PAGES_PER_SECTION)) {
if (!pfn_valid(pfn))
continue;
/*
* Nodes's pfns can be overlapping.
* We know some arch can have a nodes layout such as
* -------------pfn-------------->
* N0 | N1 | N2 | N0 | N1 | N2|....
*
* Take into account DEFERRED_STRUCT_PAGE_INIT.
*/
if (early_pfn_to_nid(pfn) != nid)
continue;
if (init_section_page_ext(pfn, nid))
goto oom;
}
}
hotplug_memory_notifier(page_ext_callback, 0);
pr_info("allocated %ld bytes of page_ext\n", total_usage);
invoke_init_callbacks();
return;
oom:
panic("Out of memory");
}
void __meminit pgdat_page_ext_init(struct pglist_data *pgdat)
{
}
#endif
| gpl-2.0 |
xinchoubiology/gcc | gcc/testsuite/gfortran.dg/protected_4.f90 | 136 | 1763 | ! { dg-do compile }
! { dg-shouldfail "Invalid Fortran 2003 code" }
! { dg-options "-std=f2003 -fall-intrinsics" }
! PR fortran/23994
!
! Test PROTECTED attribute. Within the module everything is allowed.
! Outside (use-associated): For pointers, their association status
! may not be changed. For nonpointers, their value may not be changed.
!
! Test of a invalid code
module protmod
implicit none
integer :: a
integer, target :: at
integer, pointer :: ap
protected :: a, at, ap
end module protmod
program main
use protmod
implicit none
integer :: j
logical :: asgnd
protected :: j ! { dg-error "only allowed in specification part of a module" }
a = 43 ! { dg-error "variable definition context" }
ap => null() ! { dg-error "pointer association context" }
nullify(ap) ! { dg-error "pointer association context" }
ap => at ! { dg-error "pointer association context" }
ap = 3 ! OK
allocate(ap) ! { dg-error "pointer association context" }
ap = 73 ! OK
call increment(a,at) ! { dg-error "variable definition context" }
call pointer_assignments(ap) ! { dg-error "pointer association context" }
asgnd = pointer_check(ap)
contains
subroutine increment(a1,a3)
integer, intent(inout) :: a1, a3
a1 = a1 + 1
a3 = a3 + 1
end subroutine increment
subroutine pointer_assignments(p)
integer, pointer,intent(out) :: p
p => null()
end subroutine pointer_assignments
function pointer_check(p)
integer, pointer,intent(in) :: p
logical :: pointer_check
pointer_check = associated(p)
end function pointer_check
end program main
module test
real :: a
protected :: test ! { dg-error "MODULE attribute conflicts with PROTECTED" }
end module test
| gpl-2.0 |
pacificIT/linux-udoo | drivers/gpu/drm/i915/intel_fbdev.c | 136 | 22619 | /*
* Copyright © 2007 David Airlie
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* David Airlie
*/
#include <linux/async.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/console.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/sysrq.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/vga_switcheroo.h>
#include <drm/drmP.h>
#include <drm/drm_crtc.h>
#include <drm/drm_fb_helper.h>
#include "intel_drv.h"
#include <drm/i915_drm.h>
#include "i915_drv.h"
static int intel_fbdev_set_par(struct fb_info *info)
{
struct drm_fb_helper *fb_helper = info->par;
struct intel_fbdev *ifbdev =
container_of(fb_helper, struct intel_fbdev, helper);
int ret;
ret = drm_fb_helper_set_par(info);
if (ret == 0) {
/*
* FIXME: fbdev presumes that all callbacks also work from
* atomic contexts and relies on that for emergency oops
* printing. KMS totally doesn't do that and the locking here is
* by far not the only place this goes wrong. Ignore this for
* now until we solve this for real.
*/
mutex_lock(&fb_helper->dev->struct_mutex);
ret = i915_gem_object_set_to_gtt_domain(ifbdev->fb->obj,
true);
mutex_unlock(&fb_helper->dev->struct_mutex);
}
return ret;
}
static struct fb_ops intelfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = drm_fb_helper_check_var,
.fb_set_par = intel_fbdev_set_par,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
.fb_pan_display = drm_fb_helper_pan_display,
.fb_blank = drm_fb_helper_blank,
.fb_setcmap = drm_fb_helper_setcmap,
.fb_debug_enter = drm_fb_helper_debug_enter,
.fb_debug_leave = drm_fb_helper_debug_leave,
};
static int intelfb_alloc(struct drm_fb_helper *helper,
struct drm_fb_helper_surface_size *sizes)
{
struct intel_fbdev *ifbdev =
container_of(helper, struct intel_fbdev, helper);
struct drm_framebuffer *fb;
struct drm_device *dev = helper->dev;
struct drm_mode_fb_cmd2 mode_cmd = {};
struct drm_i915_gem_object *obj;
int size, ret;
/* we don't do packed 24bpp */
if (sizes->surface_bpp == 24)
sizes->surface_bpp = 32;
mode_cmd.width = sizes->surface_width;
mode_cmd.height = sizes->surface_height;
mode_cmd.pitches[0] = ALIGN(mode_cmd.width *
DIV_ROUND_UP(sizes->surface_bpp, 8), 64);
mode_cmd.pixel_format = drm_mode_legacy_fb_format(sizes->surface_bpp,
sizes->surface_depth);
size = mode_cmd.pitches[0] * mode_cmd.height;
size = PAGE_ALIGN(size);
obj = i915_gem_object_create_stolen(dev, size);
if (obj == NULL)
obj = i915_gem_alloc_object(dev, size);
if (!obj) {
DRM_ERROR("failed to allocate framebuffer\n");
ret = -ENOMEM;
goto out;
}
fb = __intel_framebuffer_create(dev, &mode_cmd, obj);
if (IS_ERR(fb)) {
ret = PTR_ERR(fb);
goto out_unref;
}
/* Flush everything out, we'll be doing GTT only from now on */
ret = intel_pin_and_fence_fb_obj(NULL, fb, NULL);
if (ret) {
DRM_ERROR("failed to pin obj: %d\n", ret);
goto out_fb;
}
ifbdev->fb = to_intel_framebuffer(fb);
return 0;
out_fb:
drm_framebuffer_remove(fb);
out_unref:
drm_gem_object_unreference(&obj->base);
out:
return ret;
}
static int intelfb_create(struct drm_fb_helper *helper,
struct drm_fb_helper_surface_size *sizes)
{
struct intel_fbdev *ifbdev =
container_of(helper, struct intel_fbdev, helper);
struct intel_framebuffer *intel_fb = ifbdev->fb;
struct drm_device *dev = helper->dev;
struct drm_i915_private *dev_priv = dev->dev_private;
struct fb_info *info;
struct drm_framebuffer *fb;
struct drm_i915_gem_object *obj;
int size, ret;
bool prealloc = false;
mutex_lock(&dev->struct_mutex);
if (intel_fb &&
(sizes->fb_width > intel_fb->base.width ||
sizes->fb_height > intel_fb->base.height)) {
DRM_DEBUG_KMS("BIOS fb too small (%dx%d), we require (%dx%d),"
" releasing it\n",
intel_fb->base.width, intel_fb->base.height,
sizes->fb_width, sizes->fb_height);
drm_framebuffer_unreference(&intel_fb->base);
intel_fb = ifbdev->fb = NULL;
}
if (!intel_fb || WARN_ON(!intel_fb->obj)) {
DRM_DEBUG_KMS("no BIOS fb, allocating a new one\n");
ret = intelfb_alloc(helper, sizes);
if (ret)
goto out_unlock;
intel_fb = ifbdev->fb;
} else {
DRM_DEBUG_KMS("re-using BIOS fb\n");
prealloc = true;
sizes->fb_width = intel_fb->base.width;
sizes->fb_height = intel_fb->base.height;
}
obj = intel_fb->obj;
size = obj->base.size;
info = framebuffer_alloc(0, &dev->pdev->dev);
if (!info) {
ret = -ENOMEM;
goto out_unpin;
}
info->par = helper;
fb = &ifbdev->fb->base;
ifbdev->helper.fb = fb;
ifbdev->helper.fbdev = info;
strcpy(info->fix.id, "inteldrmfb");
info->flags = FBINFO_DEFAULT | FBINFO_CAN_FORCE_OUTPUT;
info->fbops = &intelfb_ops;
ret = fb_alloc_cmap(&info->cmap, 256, 0);
if (ret) {
ret = -ENOMEM;
goto out_unpin;
}
/* setup aperture base/size for vesafb takeover */
info->apertures = alloc_apertures(1);
if (!info->apertures) {
ret = -ENOMEM;
goto out_unpin;
}
info->apertures->ranges[0].base = dev->mode_config.fb_base;
info->apertures->ranges[0].size = dev_priv->gtt.mappable_end;
info->fix.smem_start = dev->mode_config.fb_base + i915_gem_obj_ggtt_offset(obj);
info->fix.smem_len = size;
info->screen_base =
ioremap_wc(dev_priv->gtt.mappable_base + i915_gem_obj_ggtt_offset(obj),
size);
if (!info->screen_base) {
ret = -ENOSPC;
goto out_unpin;
}
info->screen_size = size;
/* This driver doesn't need a VT switch to restore the mode on resume */
info->skip_vt_switch = true;
drm_fb_helper_fill_fix(info, fb->pitches[0], fb->depth);
drm_fb_helper_fill_var(info, &ifbdev->helper, sizes->fb_width, sizes->fb_height);
/* If the object is shmemfs backed, it will have given us zeroed pages.
* If the object is stolen however, it will be full of whatever
* garbage was left in there.
*/
if (ifbdev->fb->obj->stolen && !prealloc)
memset_io(info->screen_base, 0, info->screen_size);
/* Use default scratch pixmap (info->pixmap.flags = FB_PIXMAP_SYSTEM) */
DRM_DEBUG_KMS("allocated %dx%d fb: 0x%08lx, bo %p\n",
fb->width, fb->height,
i915_gem_obj_ggtt_offset(obj), obj);
mutex_unlock(&dev->struct_mutex);
vga_switcheroo_client_fb_set(dev->pdev, info);
return 0;
out_unpin:
i915_gem_object_ggtt_unpin(obj);
drm_gem_object_unreference(&obj->base);
out_unlock:
mutex_unlock(&dev->struct_mutex);
return ret;
}
/** Sets the color ramps on behalf of RandR */
static void intel_crtc_fb_gamma_set(struct drm_crtc *crtc, u16 red, u16 green,
u16 blue, int regno)
{
struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
intel_crtc->lut_r[regno] = red >> 8;
intel_crtc->lut_g[regno] = green >> 8;
intel_crtc->lut_b[regno] = blue >> 8;
}
static void intel_crtc_fb_gamma_get(struct drm_crtc *crtc, u16 *red, u16 *green,
u16 *blue, int regno)
{
struct intel_crtc *intel_crtc = to_intel_crtc(crtc);
*red = intel_crtc->lut_r[regno] << 8;
*green = intel_crtc->lut_g[regno] << 8;
*blue = intel_crtc->lut_b[regno] << 8;
}
static struct drm_fb_helper_crtc *
intel_fb_helper_crtc(struct drm_fb_helper *fb_helper, struct drm_crtc *crtc)
{
int i;
for (i = 0; i < fb_helper->crtc_count; i++)
if (fb_helper->crtc_info[i].mode_set.crtc == crtc)
return &fb_helper->crtc_info[i];
return NULL;
}
/*
* Try to read the BIOS display configuration and use it for the initial
* fb configuration.
*
* The BIOS or boot loader will generally create an initial display
* configuration for us that includes some set of active pipes and displays.
* This routine tries to figure out which pipes and connectors are active
* and stuffs them into the crtcs and modes array given to us by the
* drm_fb_helper code.
*
* The overall sequence is:
* intel_fbdev_init - from driver load
* intel_fbdev_init_bios - initialize the intel_fbdev using BIOS data
* drm_fb_helper_init - build fb helper structs
* drm_fb_helper_single_add_all_connectors - more fb helper structs
* intel_fbdev_initial_config - apply the config
* drm_fb_helper_initial_config - call ->probe then register_framebuffer()
* drm_setup_crtcs - build crtc config for fbdev
* intel_fb_initial_config - find active connectors etc
* drm_fb_helper_single_fb_probe - set up fbdev
* intelfb_create - re-use or alloc fb, build out fbdev structs
*
* Note that we don't make special consideration whether we could actually
* switch to the selected modes without a full modeset. E.g. when the display
* is in VGA mode we need to recalculate watermarks and set a new high-res
* framebuffer anyway.
*/
static bool intel_fb_initial_config(struct drm_fb_helper *fb_helper,
struct drm_fb_helper_crtc **crtcs,
struct drm_display_mode **modes,
struct drm_fb_offset *offsets,
bool *enabled, int width, int height)
{
struct drm_device *dev = fb_helper->dev;
int i, j;
bool *save_enabled;
bool fallback = true;
int num_connectors_enabled = 0;
int num_connectors_detected = 0;
uint64_t conn_configured = 0, mask;
int pass = 0;
save_enabled = kcalloc(dev->mode_config.num_connector, sizeof(bool),
GFP_KERNEL);
if (!save_enabled)
return false;
memcpy(save_enabled, enabled, dev->mode_config.num_connector);
mask = (1 << fb_helper->connector_count) - 1;
retry:
for (i = 0; i < fb_helper->connector_count; i++) {
struct drm_fb_helper_connector *fb_conn;
struct drm_connector *connector;
struct drm_encoder *encoder;
struct drm_fb_helper_crtc *new_crtc;
fb_conn = fb_helper->connector_info[i];
connector = fb_conn->connector;
if (conn_configured & (1 << i))
continue;
if (pass == 0 && !connector->has_tile)
continue;
if (connector->status == connector_status_connected)
num_connectors_detected++;
if (!enabled[i]) {
DRM_DEBUG_KMS("connector %s not enabled, skipping\n",
connector->name);
conn_configured |= (1 << i);
continue;
}
if (connector->force == DRM_FORCE_OFF) {
DRM_DEBUG_KMS("connector %s is disabled by user, skipping\n",
connector->name);
enabled[i] = false;
continue;
}
encoder = connector->encoder;
if (!encoder || WARN_ON(!encoder->crtc)) {
if (connector->force > DRM_FORCE_OFF)
goto bail;
DRM_DEBUG_KMS("connector %s has no encoder or crtc, skipping\n",
connector->name);
enabled[i] = false;
conn_configured |= (1 << i);
continue;
}
num_connectors_enabled++;
new_crtc = intel_fb_helper_crtc(fb_helper, encoder->crtc);
/*
* Make sure we're not trying to drive multiple connectors
* with a single CRTC, since our cloning support may not
* match the BIOS.
*/
for (j = 0; j < fb_helper->connector_count; j++) {
if (crtcs[j] == new_crtc) {
DRM_DEBUG_KMS("fallback: cloned configuration\n");
goto bail;
}
}
DRM_DEBUG_KMS("looking for cmdline mode on connector %s\n",
connector->name);
/* go for command line mode first */
modes[i] = drm_pick_cmdline_mode(fb_conn, width, height);
/* try for preferred next */
if (!modes[i]) {
DRM_DEBUG_KMS("looking for preferred mode on connector %s %d\n",
connector->name, connector->has_tile);
modes[i] = drm_has_preferred_mode(fb_conn, width,
height);
}
/* No preferred mode marked by the EDID? Are there any modes? */
if (!modes[i] && !list_empty(&connector->modes)) {
DRM_DEBUG_KMS("using first mode listed on connector %s\n",
connector->name);
modes[i] = list_first_entry(&connector->modes,
struct drm_display_mode,
head);
}
/* last resort: use current mode */
if (!modes[i]) {
/*
* IMPORTANT: We want to use the adjusted mode (i.e.
* after the panel fitter upscaling) as the initial
* config, not the input mode, which is what crtc->mode
* usually contains. But since our current fastboot
* code puts a mode derived from the post-pfit timings
* into crtc->mode this works out correctly. We don't
* use hwmode anywhere right now, so use it for this
* since the fb helper layer wants a pointer to
* something we own.
*/
DRM_DEBUG_KMS("looking for current mode on connector %s\n",
connector->name);
intel_mode_from_pipe_config(&encoder->crtc->hwmode,
to_intel_crtc(encoder->crtc)->config);
modes[i] = &encoder->crtc->hwmode;
}
crtcs[i] = new_crtc;
DRM_DEBUG_KMS("connector %s on pipe %c [CRTC:%d]: %dx%d%s\n",
connector->name,
pipe_name(to_intel_crtc(encoder->crtc)->pipe),
encoder->crtc->base.id,
modes[i]->hdisplay, modes[i]->vdisplay,
modes[i]->flags & DRM_MODE_FLAG_INTERLACE ? "i" :"");
fallback = false;
conn_configured |= (1 << i);
}
if ((conn_configured & mask) != mask) {
pass++;
goto retry;
}
/*
* If the BIOS didn't enable everything it could, fall back to have the
* same user experiencing of lighting up as much as possible like the
* fbdev helper library.
*/
if (num_connectors_enabled != num_connectors_detected &&
num_connectors_enabled < INTEL_INFO(dev)->num_pipes) {
DRM_DEBUG_KMS("fallback: Not all outputs enabled\n");
DRM_DEBUG_KMS("Enabled: %i, detected: %i\n", num_connectors_enabled,
num_connectors_detected);
fallback = true;
}
if (fallback) {
bail:
DRM_DEBUG_KMS("Not using firmware configuration\n");
memcpy(enabled, save_enabled, dev->mode_config.num_connector);
kfree(save_enabled);
return false;
}
kfree(save_enabled);
return true;
}
static const struct drm_fb_helper_funcs intel_fb_helper_funcs = {
.initial_config = intel_fb_initial_config,
.gamma_set = intel_crtc_fb_gamma_set,
.gamma_get = intel_crtc_fb_gamma_get,
.fb_probe = intelfb_create,
};
static void intel_fbdev_destroy(struct drm_device *dev,
struct intel_fbdev *ifbdev)
{
if (ifbdev->helper.fbdev) {
struct fb_info *info = ifbdev->helper.fbdev;
unregister_framebuffer(info);
iounmap(info->screen_base);
if (info->cmap.len)
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
drm_fb_helper_fini(&ifbdev->helper);
drm_framebuffer_unregister_private(&ifbdev->fb->base);
drm_framebuffer_remove(&ifbdev->fb->base);
}
/*
* Build an intel_fbdev struct using a BIOS allocated framebuffer, if possible.
* The core display code will have read out the current plane configuration,
* so we use that to figure out if there's an object for us to use as the
* fb, and if so, we re-use it for the fbdev configuration.
*
* Note we only support a single fb shared across pipes for boot (mostly for
* fbcon), so we just find the biggest and use that.
*/
static bool intel_fbdev_init_bios(struct drm_device *dev,
struct intel_fbdev *ifbdev)
{
struct intel_framebuffer *fb = NULL;
struct drm_crtc *crtc;
struct intel_crtc *intel_crtc;
struct intel_initial_plane_config *plane_config = NULL;
unsigned int max_size = 0;
if (!i915.fastboot)
return false;
/* Find the largest fb */
for_each_crtc(dev, crtc) {
intel_crtc = to_intel_crtc(crtc);
if (!intel_crtc->active || !crtc->primary->fb) {
DRM_DEBUG_KMS("pipe %c not active or no fb, skipping\n",
pipe_name(intel_crtc->pipe));
continue;
}
if (intel_crtc->plane_config.size > max_size) {
DRM_DEBUG_KMS("found possible fb from plane %c\n",
pipe_name(intel_crtc->pipe));
plane_config = &intel_crtc->plane_config;
fb = to_intel_framebuffer(crtc->primary->fb);
max_size = plane_config->size;
}
}
if (!fb) {
DRM_DEBUG_KMS("no active fbs found, not using BIOS config\n");
goto out;
}
/* Now make sure all the pipes will fit into it */
for_each_crtc(dev, crtc) {
unsigned int cur_size;
intel_crtc = to_intel_crtc(crtc);
if (!intel_crtc->active) {
DRM_DEBUG_KMS("pipe %c not active, skipping\n",
pipe_name(intel_crtc->pipe));
continue;
}
DRM_DEBUG_KMS("checking plane %c for BIOS fb\n",
pipe_name(intel_crtc->pipe));
/*
* See if the plane fb we found above will fit on this
* pipe. Note we need to use the selected fb's pitch and bpp
* rather than the current pipe's, since they differ.
*/
cur_size = intel_crtc->config->base.adjusted_mode.crtc_hdisplay;
cur_size = cur_size * fb->base.bits_per_pixel / 8;
if (fb->base.pitches[0] < cur_size) {
DRM_DEBUG_KMS("fb not wide enough for plane %c (%d vs %d)\n",
pipe_name(intel_crtc->pipe),
cur_size, fb->base.pitches[0]);
plane_config = NULL;
fb = NULL;
break;
}
cur_size = intel_crtc->config->base.adjusted_mode.crtc_vdisplay;
cur_size = intel_fb_align_height(dev, cur_size,
plane_config->tiling);
cur_size *= fb->base.pitches[0];
DRM_DEBUG_KMS("pipe %c area: %dx%d, bpp: %d, size: %d\n",
pipe_name(intel_crtc->pipe),
intel_crtc->config->base.adjusted_mode.crtc_hdisplay,
intel_crtc->config->base.adjusted_mode.crtc_vdisplay,
fb->base.bits_per_pixel,
cur_size);
if (cur_size > max_size) {
DRM_DEBUG_KMS("fb not big enough for plane %c (%d vs %d)\n",
pipe_name(intel_crtc->pipe),
cur_size, max_size);
plane_config = NULL;
fb = NULL;
break;
}
DRM_DEBUG_KMS("fb big enough for plane %c (%d >= %d)\n",
pipe_name(intel_crtc->pipe),
max_size, cur_size);
}
if (!fb) {
DRM_DEBUG_KMS("BIOS fb not suitable for all pipes, not using\n");
goto out;
}
ifbdev->preferred_bpp = fb->base.bits_per_pixel;
ifbdev->fb = fb;
drm_framebuffer_reference(&ifbdev->fb->base);
/* Final pass to check if any active pipes don't have fbs */
for_each_crtc(dev, crtc) {
intel_crtc = to_intel_crtc(crtc);
if (!intel_crtc->active)
continue;
WARN(!crtc->primary->fb,
"re-used BIOS config but lost an fb on crtc %d\n",
crtc->base.id);
}
DRM_DEBUG_KMS("using BIOS fb for initial console\n");
return true;
out:
return false;
}
static void intel_fbdev_suspend_worker(struct work_struct *work)
{
intel_fbdev_set_suspend(container_of(work,
struct drm_i915_private,
fbdev_suspend_work)->dev,
FBINFO_STATE_RUNNING,
true);
}
int intel_fbdev_init(struct drm_device *dev)
{
struct intel_fbdev *ifbdev;
struct drm_i915_private *dev_priv = dev->dev_private;
int ret;
if (WARN_ON(INTEL_INFO(dev)->num_pipes == 0))
return -ENODEV;
ifbdev = kzalloc(sizeof(struct intel_fbdev), GFP_KERNEL);
if (ifbdev == NULL)
return -ENOMEM;
drm_fb_helper_prepare(dev, &ifbdev->helper, &intel_fb_helper_funcs);
if (!intel_fbdev_init_bios(dev, ifbdev))
ifbdev->preferred_bpp = 32;
ret = drm_fb_helper_init(dev, &ifbdev->helper,
INTEL_INFO(dev)->num_pipes, 4);
if (ret) {
kfree(ifbdev);
return ret;
}
dev_priv->fbdev = ifbdev;
INIT_WORK(&dev_priv->fbdev_suspend_work, intel_fbdev_suspend_worker);
drm_fb_helper_single_add_all_connectors(&ifbdev->helper);
return 0;
}
void intel_fbdev_initial_config(void *data, async_cookie_t cookie)
{
struct drm_i915_private *dev_priv = data;
struct intel_fbdev *ifbdev = dev_priv->fbdev;
/* Due to peculiar init order wrt to hpd handling this is separate. */
drm_fb_helper_initial_config(&ifbdev->helper, ifbdev->preferred_bpp);
}
void intel_fbdev_fini(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
if (!dev_priv->fbdev)
return;
flush_work(&dev_priv->fbdev_suspend_work);
async_synchronize_full();
intel_fbdev_destroy(dev, dev_priv->fbdev);
kfree(dev_priv->fbdev);
dev_priv->fbdev = NULL;
}
void intel_fbdev_set_suspend(struct drm_device *dev, int state, bool synchronous)
{
struct drm_i915_private *dev_priv = dev->dev_private;
struct intel_fbdev *ifbdev = dev_priv->fbdev;
struct fb_info *info;
if (!ifbdev)
return;
info = ifbdev->helper.fbdev;
if (synchronous) {
/* Flush any pending work to turn the console on, and then
* wait to turn it off. It must be synchronous as we are
* about to suspend or unload the driver.
*
* Note that from within the work-handler, we cannot flush
* ourselves, so only flush outstanding work upon suspend!
*/
if (state != FBINFO_STATE_RUNNING)
flush_work(&dev_priv->fbdev_suspend_work);
console_lock();
} else {
/*
* The console lock can be pretty contented on resume due
* to all the printk activity. Try to keep it out of the hot
* path of resume if possible.
*/
WARN_ON(state != FBINFO_STATE_RUNNING);
if (!console_trylock()) {
/* Don't block our own workqueue as this can
* be run in parallel with other i915.ko tasks.
*/
schedule_work(&dev_priv->fbdev_suspend_work);
return;
}
}
/* On resume from hibernation: If the object is shmemfs backed, it has
* been restored from swap. If the object is stolen however, it will be
* full of whatever garbage was left in there.
*/
if (state == FBINFO_STATE_RUNNING && ifbdev->fb->obj->stolen)
memset_io(info->screen_base, 0, info->screen_size);
fb_set_suspend(info, state);
console_unlock();
}
void intel_fbdev_output_poll_changed(struct drm_device *dev)
{
struct drm_i915_private *dev_priv = dev->dev_private;
if (dev_priv->fbdev)
drm_fb_helper_hotplug_event(&dev_priv->fbdev->helper);
}
void intel_fbdev_restore_mode(struct drm_device *dev)
{
int ret;
struct drm_i915_private *dev_priv = dev->dev_private;
if (!dev_priv->fbdev)
return;
ret = drm_fb_helper_restore_fbdev_mode_unlocked(&dev_priv->fbdev->helper);
if (ret)
DRM_DEBUG("failed to restore crtc mode\n");
}
| gpl-2.0 |
786228836/linux | sound/soc/samsung/smdk_wm8994pcm.c | 392 | 3602 | /*
* sound/soc/samsung/smdk_wm8994pcm.c
*
* Copyright (c) 2011 Samsung Electronics Co., Ltd
* http://www.samsung.com
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License 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>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include "../codecs/wm8994.h"
#include "pcm.h"
/*
* Board Settings:
* o '1' means 'ON'
* o '0' means 'OFF'
* o 'X' means 'Don't care'
*
* SMDKC210, SMDKV310: CFG3- 1001, CFG5-1000, CFG7-111111
*/
/*
* Configure audio route as :-
* $ amixer sset 'DAC1' on,on
* $ amixer sset 'Right Headphone Mux' 'DAC'
* $ amixer sset 'Left Headphone Mux' 'DAC'
* $ amixer sset 'DAC1R Mixer AIF1.1' on
* $ amixer sset 'DAC1L Mixer AIF1.1' on
* $ amixer sset 'IN2L' on
* $ amixer sset 'IN2L PGA IN2LN' on
* $ amixer sset 'MIXINL IN2L' on
* $ amixer sset 'AIF1ADC1L Mixer ADC/DMIC' on
* $ amixer sset 'IN2R' on
* $ amixer sset 'IN2R PGA IN2RN' on
* $ amixer sset 'MIXINR IN2R' on
* $ amixer sset 'AIF1ADC1R Mixer ADC/DMIC' on
*/
/* SMDK has a 16.9344MHZ crystal attached to WM8994 */
#define SMDK_WM8994_FREQ 16934400
static int smdk_wm8994_pcm_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;
unsigned long mclk_freq;
int rfs, ret;
switch(params_rate(params)) {
case 8000:
rfs = 512;
break;
default:
dev_err(cpu_dai->dev, "%s:%d Sampling Rate %u not supported!\n",
__func__, __LINE__, params_rate(params));
return -EINVAL;
}
mclk_freq = params_rate(params) * rfs;
ret = snd_soc_dai_set_sysclk(codec_dai, WM8994_SYSCLK_FLL1,
mclk_freq, SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
ret = snd_soc_dai_set_pll(codec_dai, WM8994_FLL1, WM8994_FLL_SRC_MCLK1,
SMDK_WM8994_FREQ, mclk_freq);
if (ret < 0)
return ret;
/* Set PCM source clock on CPU */
ret = snd_soc_dai_set_sysclk(cpu_dai, S3C_PCM_CLKSRC_MUX,
mclk_freq, SND_SOC_CLOCK_IN);
if (ret < 0)
return ret;
/* Set SCLK_DIV for making bclk */
ret = snd_soc_dai_set_clkdiv(cpu_dai, S3C_PCM_SCLK_PER_FS, rfs);
if (ret < 0)
return ret;
return 0;
}
static struct snd_soc_ops smdk_wm8994_pcm_ops = {
.hw_params = smdk_wm8994_pcm_hw_params,
};
static struct snd_soc_dai_link smdk_dai[] = {
{
.name = "WM8994 PAIF PCM",
.stream_name = "Primary PCM",
.cpu_dai_name = "samsung-pcm.0",
.codec_dai_name = "wm8994-aif1",
.platform_name = "samsung-pcm.0",
.codec_name = "wm8994-codec",
.dai_fmt = SND_SOC_DAIFMT_DSP_B | SND_SOC_DAIFMT_IB_NF |
SND_SOC_DAIFMT_CBS_CFS,
.ops = &smdk_wm8994_pcm_ops,
},
};
static struct snd_soc_card smdk_pcm = {
.name = "SMDK-PCM",
.owner = THIS_MODULE,
.dai_link = smdk_dai,
.num_links = 1,
};
static int snd_smdk_probe(struct platform_device *pdev)
{
int ret = 0;
smdk_pcm.dev = &pdev->dev;
ret = devm_snd_soc_register_card(&pdev->dev, &smdk_pcm);
if (ret)
dev_err(&pdev->dev, "snd_soc_register_card failed %d\n", ret);
return ret;
}
static struct platform_driver snd_smdk_driver = {
.driver = {
.name = "samsung-smdk-pcm",
},
.probe = snd_smdk_probe,
};
module_platform_driver(snd_smdk_driver);
MODULE_AUTHOR("Sangbeom Kim, <sbkim73@samsung.com>");
MODULE_DESCRIPTION("ALSA SoC SMDK WM8994 for PCM");
MODULE_LICENSE("GPL");
| gpl-2.0 |
abhisit/TechNexion-linux | arch/arm/mach-shmobile/setup-rcar-gen2.c | 392 | 5079 | /*
* R-Car Generation 2 support
*
* Copyright (C) 2013 Renesas Solutions Corp.
* Copyright (C) 2013 Magnus Damm
* Copyright (C) 2014 Ulrich Hecht
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/clk/shmobile.h>
#include <linux/clocksource.h>
#include <linux/device.h>
#include <linux/dma-contiguous.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/memblock.h>
#include <linux/of.h>
#include <linux/of_fdt.h>
#include <asm/mach/arch.h>
#include "common.h"
#include "rcar-gen2.h"
#define MODEMR 0xe6160060
u32 rcar_gen2_read_mode_pins(void)
{
static u32 mode;
static bool mode_valid;
if (!mode_valid) {
void __iomem *modemr = ioremap_nocache(MODEMR, 4);
BUG_ON(!modemr);
mode = ioread32(modemr);
iounmap(modemr);
mode_valid = true;
}
return mode;
}
#define CNTCR 0
#define CNTFID0 0x20
void __init rcar_gen2_timer_init(void)
{
u32 mode = rcar_gen2_read_mode_pins();
#ifdef CONFIG_ARM_ARCH_TIMER
void __iomem *base;
int extal_mhz = 0;
u32 freq;
if (of_machine_is_compatible("renesas,r8a7794")) {
freq = 260000000 / 8; /* ZS / 8 */
/* CNTVOFF has to be initialized either from non-secure
* Hypervisor mode or secure Monitor mode with SCR.NS==1.
* If TrustZone is enabled then it should be handled by the
* secure code.
*/
asm volatile(
" cps 0x16\n"
" mrc p15, 0, r1, c1, c1, 0\n"
" orr r0, r1, #1\n"
" mcr p15, 0, r0, c1, c1, 0\n"
" isb\n"
" mov r0, #0\n"
" mcrr p15, 4, r0, r0, c14\n"
" isb\n"
" mcr p15, 0, r1, c1, c1, 0\n"
" isb\n"
" cps 0x13\n"
: : : "r0", "r1");
} else {
/* At Linux boot time the r8a7790 arch timer comes up
* with the counter disabled. Moreover, it may also report
* a potentially incorrect fixed 13 MHz frequency. To be
* correct these registers need to be updated to use the
* frequency EXTAL / 2 which can be determined by the MD pins.
*/
switch (mode & (MD(14) | MD(13))) {
case 0:
extal_mhz = 15;
break;
case MD(13):
extal_mhz = 20;
break;
case MD(14):
extal_mhz = 26;
break;
case MD(13) | MD(14):
extal_mhz = 30;
break;
}
/* The arch timer frequency equals EXTAL / 2 */
freq = extal_mhz * (1000000 / 2);
}
/* Remap "armgcnt address map" space */
base = ioremap(0xe6080000, PAGE_SIZE);
/*
* Update the timer if it is either not running, or is not at the
* right frequency. The timer is only configurable in secure mode
* so this avoids an abort if the loader started the timer and
* entered the kernel in non-secure mode.
*/
if ((ioread32(base + CNTCR) & 1) == 0 ||
ioread32(base + CNTFID0) != freq) {
/* Update registers with correct frequency */
iowrite32(freq, base + CNTFID0);
asm volatile("mcr p15, 0, %0, c14, c0, 0" : : "r" (freq));
/* make sure arch timer is started by setting bit 0 of CNTCR */
iowrite32(1, base + CNTCR);
}
iounmap(base);
#endif /* CONFIG_ARM_ARCH_TIMER */
rcar_gen2_clocks_init(mode);
#ifdef CONFIG_ARCH_SHMOBILE_MULTI
clocksource_of_init();
#endif
}
struct memory_reserve_config {
u64 reserved;
u64 base, size;
};
static int __init rcar_gen2_scan_mem(unsigned long node, const char *uname,
int depth, void *data)
{
const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
const __be32 *reg, *endp;
int l;
struct memory_reserve_config *mrc = data;
u64 lpae_start = 1ULL << 32;
/* We are scanning "memory" nodes only */
if (type == NULL || strcmp(type, "memory"))
return 0;
reg = of_get_flat_dt_prop(node, "linux,usable-memory", &l);
if (reg == NULL)
reg = of_get_flat_dt_prop(node, "reg", &l);
if (reg == NULL)
return 0;
endp = reg + (l / sizeof(__be32));
while ((endp - reg) >= (dt_root_addr_cells + dt_root_size_cells)) {
u64 base, size;
base = dt_mem_next_cell(dt_root_addr_cells, ®);
size = dt_mem_next_cell(dt_root_size_cells, ®);
if (base >= lpae_start)
continue;
if ((base + size) >= lpae_start)
size = lpae_start - base;
if (size < mrc->reserved)
continue;
if (base < mrc->base)
continue;
/* keep the area at top near the 32-bit legacy limit */
mrc->base = base + size - mrc->reserved;
mrc->size = mrc->reserved;
}
return 0;
}
struct cma *rcar_gen2_dma_contiguous;
void __init rcar_gen2_reserve(void)
{
struct memory_reserve_config mrc;
/* reserve 256 MiB at the top of the physical legacy 32-bit space */
memset(&mrc, 0, sizeof(mrc));
mrc.reserved = SZ_256M;
of_scan_flat_dt(rcar_gen2_scan_mem, &mrc);
#ifdef CONFIG_DMA_CMA
if (mrc.size && memblock_is_region_memory(mrc.base, mrc.size))
dma_contiguous_reserve_area(mrc.size, mrc.base, 0,
&rcar_gen2_dma_contiguous, true);
#endif
}
| gpl-2.0 |
rfalize/endeavoru-suitcasekernel | net/sched/cls_cgroup.c | 648 | 7381 | /*
* net/sched/cls_cgroup.c Control Group Classifier
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Authors: Thomas Graf <tgraf@suug.ch>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/skbuff.h>
#include <linux/cgroup.h>
#include <linux/rcupdate.h>
#include <net/rtnetlink.h>
#include <net/pkt_cls.h>
#include <net/sock.h>
#include <net/cls_cgroup.h>
static struct cgroup_subsys_state *cgrp_create(struct cgroup_subsys *ss,
struct cgroup *cgrp);
static void cgrp_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp);
static int cgrp_populate(struct cgroup_subsys *ss, struct cgroup *cgrp);
struct cgroup_subsys net_cls_subsys = {
.name = "net_cls",
.create = cgrp_create,
.destroy = cgrp_destroy,
.populate = cgrp_populate,
#ifdef CONFIG_NET_CLS_CGROUP
.subsys_id = net_cls_subsys_id,
#endif
.module = THIS_MODULE,
};
static inline struct cgroup_cls_state *cgrp_cls_state(struct cgroup *cgrp)
{
return container_of(cgroup_subsys_state(cgrp, net_cls_subsys_id),
struct cgroup_cls_state, css);
}
static inline struct cgroup_cls_state *task_cls_state(struct task_struct *p)
{
return container_of(task_subsys_state(p, net_cls_subsys_id),
struct cgroup_cls_state, css);
}
static struct cgroup_subsys_state *cgrp_create(struct cgroup_subsys *ss,
struct cgroup *cgrp)
{
struct cgroup_cls_state *cs;
cs = kzalloc(sizeof(*cs), GFP_KERNEL);
if (!cs)
return ERR_PTR(-ENOMEM);
if (cgrp->parent)
cs->classid = cgrp_cls_state(cgrp->parent)->classid;
return &cs->css;
}
static void cgrp_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
{
kfree(cgrp_cls_state(cgrp));
}
static u64 read_classid(struct cgroup *cgrp, struct cftype *cft)
{
return cgrp_cls_state(cgrp)->classid;
}
static int write_classid(struct cgroup *cgrp, struct cftype *cft, u64 value)
{
cgrp_cls_state(cgrp)->classid = (u32) value;
return 0;
}
static struct cftype ss_files[] = {
{
.name = "classid",
.read_u64 = read_classid,
.write_u64 = write_classid,
},
};
static int cgrp_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
{
return cgroup_add_files(cgrp, ss, ss_files, ARRAY_SIZE(ss_files));
}
struct cls_cgroup_head {
u32 handle;
struct tcf_exts exts;
struct tcf_ematch_tree ematches;
};
static int cls_cgroup_classify(struct sk_buff *skb, const struct tcf_proto *tp,
struct tcf_result *res)
{
struct cls_cgroup_head *head = tp->root;
u32 classid;
rcu_read_lock();
classid = task_cls_state(current)->classid;
rcu_read_unlock();
/*
* Due to the nature of the classifier it is required to ignore all
* packets originating from softirq context as accessing `current'
* would lead to false results.
*
* This test assumes that all callers of dev_queue_xmit() explicitely
* disable bh. Knowing this, it is possible to detect softirq based
* calls by looking at the number of nested bh disable calls because
* softirqs always disables bh.
*/
if (in_serving_softirq()) {
/* If there is an sk_classid we'll use that. */
if (!skb->sk)
return -1;
classid = skb->sk->sk_classid;
}
if (!classid)
return -1;
if (!tcf_em_tree_match(skb, &head->ematches, NULL))
return -1;
res->classid = classid;
res->class = 0;
return tcf_exts_exec(skb, &head->exts, res);
}
static unsigned long cls_cgroup_get(struct tcf_proto *tp, u32 handle)
{
return 0UL;
}
static void cls_cgroup_put(struct tcf_proto *tp, unsigned long f)
{
}
static int cls_cgroup_init(struct tcf_proto *tp)
{
return 0;
}
static const struct tcf_ext_map cgroup_ext_map = {
.action = TCA_CGROUP_ACT,
.police = TCA_CGROUP_POLICE,
};
static const struct nla_policy cgroup_policy[TCA_CGROUP_MAX + 1] = {
[TCA_CGROUP_EMATCHES] = { .type = NLA_NESTED },
};
static int cls_cgroup_change(struct tcf_proto *tp, unsigned long base,
u32 handle, struct nlattr **tca,
unsigned long *arg)
{
struct nlattr *tb[TCA_CGROUP_MAX + 1];
struct cls_cgroup_head *head = tp->root;
struct tcf_ematch_tree t;
struct tcf_exts e;
int err;
if (!tca[TCA_OPTIONS])
return -EINVAL;
if (head == NULL) {
if (!handle)
return -EINVAL;
head = kzalloc(sizeof(*head), GFP_KERNEL);
if (head == NULL)
return -ENOBUFS;
head->handle = handle;
tcf_tree_lock(tp);
tp->root = head;
tcf_tree_unlock(tp);
}
if (handle != head->handle)
return -ENOENT;
err = nla_parse_nested(tb, TCA_CGROUP_MAX, tca[TCA_OPTIONS],
cgroup_policy);
if (err < 0)
return err;
err = tcf_exts_validate(tp, tb, tca[TCA_RATE], &e, &cgroup_ext_map);
if (err < 0)
return err;
err = tcf_em_tree_validate(tp, tb[TCA_CGROUP_EMATCHES], &t);
if (err < 0)
return err;
tcf_exts_change(tp, &head->exts, &e);
tcf_em_tree_change(tp, &head->ematches, &t);
return 0;
}
static void cls_cgroup_destroy(struct tcf_proto *tp)
{
struct cls_cgroup_head *head = tp->root;
if (head) {
tcf_exts_destroy(tp, &head->exts);
tcf_em_tree_destroy(tp, &head->ematches);
kfree(head);
}
}
static int cls_cgroup_delete(struct tcf_proto *tp, unsigned long arg)
{
return -EOPNOTSUPP;
}
static void cls_cgroup_walk(struct tcf_proto *tp, struct tcf_walker *arg)
{
struct cls_cgroup_head *head = tp->root;
if (arg->count < arg->skip)
goto skip;
if (arg->fn(tp, (unsigned long) head, arg) < 0) {
arg->stop = 1;
return;
}
skip:
arg->count++;
}
static int cls_cgroup_dump(struct tcf_proto *tp, unsigned long fh,
struct sk_buff *skb, struct tcmsg *t)
{
struct cls_cgroup_head *head = tp->root;
unsigned char *b = skb_tail_pointer(skb);
struct nlattr *nest;
t->tcm_handle = head->handle;
nest = nla_nest_start(skb, TCA_OPTIONS);
if (nest == NULL)
goto nla_put_failure;
if (tcf_exts_dump(skb, &head->exts, &cgroup_ext_map) < 0 ||
tcf_em_tree_dump(skb, &head->ematches, TCA_CGROUP_EMATCHES) < 0)
goto nla_put_failure;
nla_nest_end(skb, nest);
if (tcf_exts_dump_stats(skb, &head->exts, &cgroup_ext_map) < 0)
goto nla_put_failure;
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static struct tcf_proto_ops cls_cgroup_ops __read_mostly = {
.kind = "cgroup",
.init = cls_cgroup_init,
.change = cls_cgroup_change,
.classify = cls_cgroup_classify,
.destroy = cls_cgroup_destroy,
.get = cls_cgroup_get,
.put = cls_cgroup_put,
.delete = cls_cgroup_delete,
.walk = cls_cgroup_walk,
.dump = cls_cgroup_dump,
.owner = THIS_MODULE,
};
static int __init init_cgroup_cls(void)
{
int ret;
ret = cgroup_load_subsys(&net_cls_subsys);
if (ret)
goto out;
#ifndef CONFIG_NET_CLS_CGROUP
/* We can't use rcu_assign_pointer because this is an int. */
smp_wmb();
net_cls_subsys_id = net_cls_subsys.subsys_id;
#endif
ret = register_tcf_proto_ops(&cls_cgroup_ops);
if (ret)
cgroup_unload_subsys(&net_cls_subsys);
out:
return ret;
}
static void __exit exit_cgroup_cls(void)
{
unregister_tcf_proto_ops(&cls_cgroup_ops);
#ifndef CONFIG_NET_CLS_CGROUP
net_cls_subsys_id = -1;
synchronize_rcu();
#endif
cgroup_unload_subsys(&net_cls_subsys);
}
module_init(init_cgroup_cls);
module_exit(exit_cgroup_cls);
MODULE_LICENSE("GPL");
| gpl-2.0 |
misham/etaluma-kernel | arch/ia64/kernel/efi.c | 648 | 37468 | /*
* Extensible Firmware Interface
*
* Based on Extensible Firmware Interface Specification version 0.9
* April 30, 1999
*
* Copyright (C) 1999 VA Linux Systems
* Copyright (C) 1999 Walt Drummond <drummond@valinux.com>
* Copyright (C) 1999-2003 Hewlett-Packard Co.
* David Mosberger-Tang <davidm@hpl.hp.com>
* Stephane Eranian <eranian@hpl.hp.com>
* (c) Copyright 2006 Hewlett-Packard Development Company, L.P.
* Bjorn Helgaas <bjorn.helgaas@hp.com>
*
* All EFI Runtime Services are not implemented yet as EFI only
* supports physical mode addressing on SoftSDV. This is to be fixed
* in a future version. --drummond 1999-07-20
*
* Implemented EFI runtime services and virtual mode calls. --davidm
*
* Goutham Rao: <goutham.rao@intel.com>
* Skip non-WB memory and ignore empty memory ranges.
*/
#include <linux/module.h>
#include <linux/bootmem.h>
#include <linux/crash_dump.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/efi.h>
#include <linux/kexec.h>
#include <linux/mm.h>
#include <asm/io.h>
#include <asm/kregs.h>
#include <asm/meminit.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/mca.h>
#include <asm/tlbflush.h>
#define EFI_DEBUG 0
extern efi_status_t efi_call_phys (void *, ...);
struct efi efi;
EXPORT_SYMBOL(efi);
static efi_runtime_services_t *runtime;
static u64 mem_limit = ~0UL, max_addr = ~0UL, min_addr = 0UL;
#define efi_call_virt(f, args...) (*(f))(args)
#define STUB_GET_TIME(prefix, adjust_arg) \
static efi_status_t \
prefix##_get_time (efi_time_t *tm, efi_time_cap_t *tc) \
{ \
struct ia64_fpreg fr[6]; \
efi_time_cap_t *atc = NULL; \
efi_status_t ret; \
\
if (tc) \
atc = adjust_arg(tc); \
ia64_save_scratch_fpregs(fr); \
ret = efi_call_##prefix((efi_get_time_t *) __va(runtime->get_time), \
adjust_arg(tm), atc); \
ia64_load_scratch_fpregs(fr); \
return ret; \
}
#define STUB_SET_TIME(prefix, adjust_arg) \
static efi_status_t \
prefix##_set_time (efi_time_t *tm) \
{ \
struct ia64_fpreg fr[6]; \
efi_status_t ret; \
\
ia64_save_scratch_fpregs(fr); \
ret = efi_call_##prefix((efi_set_time_t *) __va(runtime->set_time), \
adjust_arg(tm)); \
ia64_load_scratch_fpregs(fr); \
return ret; \
}
#define STUB_GET_WAKEUP_TIME(prefix, adjust_arg) \
static efi_status_t \
prefix##_get_wakeup_time (efi_bool_t *enabled, efi_bool_t *pending, \
efi_time_t *tm) \
{ \
struct ia64_fpreg fr[6]; \
efi_status_t ret; \
\
ia64_save_scratch_fpregs(fr); \
ret = efi_call_##prefix( \
(efi_get_wakeup_time_t *) __va(runtime->get_wakeup_time), \
adjust_arg(enabled), adjust_arg(pending), adjust_arg(tm)); \
ia64_load_scratch_fpregs(fr); \
return ret; \
}
#define STUB_SET_WAKEUP_TIME(prefix, adjust_arg) \
static efi_status_t \
prefix##_set_wakeup_time (efi_bool_t enabled, efi_time_t *tm) \
{ \
struct ia64_fpreg fr[6]; \
efi_time_t *atm = NULL; \
efi_status_t ret; \
\
if (tm) \
atm = adjust_arg(tm); \
ia64_save_scratch_fpregs(fr); \
ret = efi_call_##prefix( \
(efi_set_wakeup_time_t *) __va(runtime->set_wakeup_time), \
enabled, atm); \
ia64_load_scratch_fpregs(fr); \
return ret; \
}
#define STUB_GET_VARIABLE(prefix, adjust_arg) \
static efi_status_t \
prefix##_get_variable (efi_char16_t *name, efi_guid_t *vendor, u32 *attr, \
unsigned long *data_size, void *data) \
{ \
struct ia64_fpreg fr[6]; \
u32 *aattr = NULL; \
efi_status_t ret; \
\
if (attr) \
aattr = adjust_arg(attr); \
ia64_save_scratch_fpregs(fr); \
ret = efi_call_##prefix( \
(efi_get_variable_t *) __va(runtime->get_variable), \
adjust_arg(name), adjust_arg(vendor), aattr, \
adjust_arg(data_size), adjust_arg(data)); \
ia64_load_scratch_fpregs(fr); \
return ret; \
}
#define STUB_GET_NEXT_VARIABLE(prefix, adjust_arg) \
static efi_status_t \
prefix##_get_next_variable (unsigned long *name_size, efi_char16_t *name, \
efi_guid_t *vendor) \
{ \
struct ia64_fpreg fr[6]; \
efi_status_t ret; \
\
ia64_save_scratch_fpregs(fr); \
ret = efi_call_##prefix( \
(efi_get_next_variable_t *) __va(runtime->get_next_variable), \
adjust_arg(name_size), adjust_arg(name), adjust_arg(vendor)); \
ia64_load_scratch_fpregs(fr); \
return ret; \
}
#define STUB_SET_VARIABLE(prefix, adjust_arg) \
static efi_status_t \
prefix##_set_variable (efi_char16_t *name, efi_guid_t *vendor, \
u32 attr, unsigned long data_size, \
void *data) \
{ \
struct ia64_fpreg fr[6]; \
efi_status_t ret; \
\
ia64_save_scratch_fpregs(fr); \
ret = efi_call_##prefix( \
(efi_set_variable_t *) __va(runtime->set_variable), \
adjust_arg(name), adjust_arg(vendor), attr, data_size, \
adjust_arg(data)); \
ia64_load_scratch_fpregs(fr); \
return ret; \
}
#define STUB_GET_NEXT_HIGH_MONO_COUNT(prefix, adjust_arg) \
static efi_status_t \
prefix##_get_next_high_mono_count (u32 *count) \
{ \
struct ia64_fpreg fr[6]; \
efi_status_t ret; \
\
ia64_save_scratch_fpregs(fr); \
ret = efi_call_##prefix((efi_get_next_high_mono_count_t *) \
__va(runtime->get_next_high_mono_count), \
adjust_arg(count)); \
ia64_load_scratch_fpregs(fr); \
return ret; \
}
#define STUB_RESET_SYSTEM(prefix, adjust_arg) \
static void \
prefix##_reset_system (int reset_type, efi_status_t status, \
unsigned long data_size, efi_char16_t *data) \
{ \
struct ia64_fpreg fr[6]; \
efi_char16_t *adata = NULL; \
\
if (data) \
adata = adjust_arg(data); \
\
ia64_save_scratch_fpregs(fr); \
efi_call_##prefix( \
(efi_reset_system_t *) __va(runtime->reset_system), \
reset_type, status, data_size, adata); \
/* should not return, but just in case... */ \
ia64_load_scratch_fpregs(fr); \
}
#define phys_ptr(arg) ((__typeof__(arg)) ia64_tpa(arg))
STUB_GET_TIME(phys, phys_ptr)
STUB_SET_TIME(phys, phys_ptr)
STUB_GET_WAKEUP_TIME(phys, phys_ptr)
STUB_SET_WAKEUP_TIME(phys, phys_ptr)
STUB_GET_VARIABLE(phys, phys_ptr)
STUB_GET_NEXT_VARIABLE(phys, phys_ptr)
STUB_SET_VARIABLE(phys, phys_ptr)
STUB_GET_NEXT_HIGH_MONO_COUNT(phys, phys_ptr)
STUB_RESET_SYSTEM(phys, phys_ptr)
#define id(arg) arg
STUB_GET_TIME(virt, id)
STUB_SET_TIME(virt, id)
STUB_GET_WAKEUP_TIME(virt, id)
STUB_SET_WAKEUP_TIME(virt, id)
STUB_GET_VARIABLE(virt, id)
STUB_GET_NEXT_VARIABLE(virt, id)
STUB_SET_VARIABLE(virt, id)
STUB_GET_NEXT_HIGH_MONO_COUNT(virt, id)
STUB_RESET_SYSTEM(virt, id)
void
efi_gettimeofday (struct timespec *ts)
{
efi_time_t tm;
if ((*efi.get_time)(&tm, NULL) != EFI_SUCCESS) {
memset(ts, 0, sizeof(*ts));
return;
}
ts->tv_sec = mktime(tm.year, tm.month, tm.day,
tm.hour, tm.minute, tm.second);
ts->tv_nsec = tm.nanosecond;
}
static int
is_memory_available (efi_memory_desc_t *md)
{
if (!(md->attribute & EFI_MEMORY_WB))
return 0;
switch (md->type) {
case EFI_LOADER_CODE:
case EFI_LOADER_DATA:
case EFI_BOOT_SERVICES_CODE:
case EFI_BOOT_SERVICES_DATA:
case EFI_CONVENTIONAL_MEMORY:
return 1;
}
return 0;
}
typedef struct kern_memdesc {
u64 attribute;
u64 start;
u64 num_pages;
} kern_memdesc_t;
static kern_memdesc_t *kern_memmap;
#define efi_md_size(md) (md->num_pages << EFI_PAGE_SHIFT)
static inline u64
kmd_end(kern_memdesc_t *kmd)
{
return (kmd->start + (kmd->num_pages << EFI_PAGE_SHIFT));
}
static inline u64
efi_md_end(efi_memory_desc_t *md)
{
return (md->phys_addr + efi_md_size(md));
}
static inline int
efi_wb(efi_memory_desc_t *md)
{
return (md->attribute & EFI_MEMORY_WB);
}
static inline int
efi_uc(efi_memory_desc_t *md)
{
return (md->attribute & EFI_MEMORY_UC);
}
static void
walk (efi_freemem_callback_t callback, void *arg, u64 attr)
{
kern_memdesc_t *k;
u64 start, end, voff;
voff = (attr == EFI_MEMORY_WB) ? PAGE_OFFSET : __IA64_UNCACHED_OFFSET;
for (k = kern_memmap; k->start != ~0UL; k++) {
if (k->attribute != attr)
continue;
start = PAGE_ALIGN(k->start);
end = (k->start + (k->num_pages << EFI_PAGE_SHIFT)) & PAGE_MASK;
if (start < end)
if ((*callback)(start + voff, end + voff, arg) < 0)
return;
}
}
/*
* Walk the EFI memory map and call CALLBACK once for each EFI memory
* descriptor that has memory that is available for OS use.
*/
void
efi_memmap_walk (efi_freemem_callback_t callback, void *arg)
{
walk(callback, arg, EFI_MEMORY_WB);
}
/*
* Walk the EFI memory map and call CALLBACK once for each EFI memory
* descriptor that has memory that is available for uncached allocator.
*/
void
efi_memmap_walk_uc (efi_freemem_callback_t callback, void *arg)
{
walk(callback, arg, EFI_MEMORY_UC);
}
/*
* Look for the PAL_CODE region reported by EFI and map it using an
* ITR to enable safe PAL calls in virtual mode. See IA-64 Processor
* Abstraction Layer chapter 11 in ADAG
*/
void *
efi_get_pal_addr (void)
{
void *efi_map_start, *efi_map_end, *p;
efi_memory_desc_t *md;
u64 efi_desc_size;
int pal_code_count = 0;
u64 vaddr, mask;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
for (p = efi_map_start; p < efi_map_end; p += efi_desc_size) {
md = p;
if (md->type != EFI_PAL_CODE)
continue;
if (++pal_code_count > 1) {
printk(KERN_ERR "Too many EFI Pal Code memory ranges, "
"dropped @ %llx\n", md->phys_addr);
continue;
}
/*
* The only ITLB entry in region 7 that is used is the one
* installed by __start(). That entry covers a 64MB range.
*/
mask = ~((1 << KERNEL_TR_PAGE_SHIFT) - 1);
vaddr = PAGE_OFFSET + md->phys_addr;
/*
* We must check that the PAL mapping won't overlap with the
* kernel mapping.
*
* PAL code is guaranteed to be aligned on a power of 2 between
* 4k and 256KB and that only one ITR is needed to map it. This
* implies that the PAL code is always aligned on its size,
* i.e., the closest matching page size supported by the TLB.
* Therefore PAL code is guaranteed never to cross a 64MB unless
* it is bigger than 64MB (very unlikely!). So for now the
* following test is enough to determine whether or not we need
* a dedicated ITR for the PAL code.
*/
if ((vaddr & mask) == (KERNEL_START & mask)) {
printk(KERN_INFO "%s: no need to install ITR for PAL code\n",
__func__);
continue;
}
if (efi_md_size(md) > IA64_GRANULE_SIZE)
panic("Whoa! PAL code size bigger than a granule!");
#if EFI_DEBUG
mask = ~((1 << IA64_GRANULE_SHIFT) - 1);
printk(KERN_INFO "CPU %d: mapping PAL code "
"[0x%lx-0x%lx) into [0x%lx-0x%lx)\n",
smp_processor_id(), md->phys_addr,
md->phys_addr + efi_md_size(md),
vaddr & mask, (vaddr & mask) + IA64_GRANULE_SIZE);
#endif
return __va(md->phys_addr);
}
printk(KERN_WARNING "%s: no PAL-code memory-descriptor found\n",
__func__);
return NULL;
}
static u8 __init palo_checksum(u8 *buffer, u32 length)
{
u8 sum = 0;
u8 *end = buffer + length;
while (buffer < end)
sum = (u8) (sum + *(buffer++));
return sum;
}
/*
* Parse and handle PALO table which is published at:
* http://www.dig64.org/home/DIG64_PALO_R1_0.pdf
*/
static void __init handle_palo(unsigned long palo_phys)
{
struct palo_table *palo = __va(palo_phys);
u8 checksum;
if (strncmp(palo->signature, PALO_SIG, sizeof(PALO_SIG) - 1)) {
printk(KERN_INFO "PALO signature incorrect.\n");
return;
}
checksum = palo_checksum((u8 *)palo, palo->length);
if (checksum) {
printk(KERN_INFO "PALO checksum incorrect.\n");
return;
}
setup_ptcg_sem(palo->max_tlb_purges, NPTCG_FROM_PALO);
}
void
efi_map_pal_code (void)
{
void *pal_vaddr = efi_get_pal_addr ();
u64 psr;
if (!pal_vaddr)
return;
/*
* Cannot write to CRx with PSR.ic=1
*/
psr = ia64_clear_ic();
ia64_itr(0x1, IA64_TR_PALCODE,
GRANULEROUNDDOWN((unsigned long) pal_vaddr),
pte_val(pfn_pte(__pa(pal_vaddr) >> PAGE_SHIFT, PAGE_KERNEL)),
IA64_GRANULE_SHIFT);
paravirt_dv_serialize_data();
ia64_set_psr(psr); /* restore psr */
}
void __init
efi_init (void)
{
void *efi_map_start, *efi_map_end;
efi_config_table_t *config_tables;
efi_char16_t *c16;
u64 efi_desc_size;
char *cp, vendor[100] = "unknown";
int i;
unsigned long palo_phys;
/*
* It's too early to be able to use the standard kernel command line
* support...
*/
for (cp = boot_command_line; *cp; ) {
if (memcmp(cp, "mem=", 4) == 0) {
mem_limit = memparse(cp + 4, &cp);
} else if (memcmp(cp, "max_addr=", 9) == 0) {
max_addr = GRANULEROUNDDOWN(memparse(cp + 9, &cp));
} else if (memcmp(cp, "min_addr=", 9) == 0) {
min_addr = GRANULEROUNDDOWN(memparse(cp + 9, &cp));
} else {
while (*cp != ' ' && *cp)
++cp;
while (*cp == ' ')
++cp;
}
}
if (min_addr != 0UL)
printk(KERN_INFO "Ignoring memory below %lluMB\n",
min_addr >> 20);
if (max_addr != ~0UL)
printk(KERN_INFO "Ignoring memory above %lluMB\n",
max_addr >> 20);
efi.systab = __va(ia64_boot_param->efi_systab);
/*
* Verify the EFI Table
*/
if (efi.systab == NULL)
panic("Whoa! Can't find EFI system table.\n");
if (efi.systab->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE)
panic("Whoa! EFI system table signature incorrect\n");
if ((efi.systab->hdr.revision >> 16) == 0)
printk(KERN_WARNING "Warning: EFI system table version "
"%d.%02d, expected 1.00 or greater\n",
efi.systab->hdr.revision >> 16,
efi.systab->hdr.revision & 0xffff);
config_tables = __va(efi.systab->tables);
/* Show what we know for posterity */
c16 = __va(efi.systab->fw_vendor);
if (c16) {
for (i = 0;i < (int) sizeof(vendor) - 1 && *c16; ++i)
vendor[i] = *c16++;
vendor[i] = '\0';
}
printk(KERN_INFO "EFI v%u.%.02u by %s:",
efi.systab->hdr.revision >> 16,
efi.systab->hdr.revision & 0xffff, vendor);
efi.mps = EFI_INVALID_TABLE_ADDR;
efi.acpi = EFI_INVALID_TABLE_ADDR;
efi.acpi20 = EFI_INVALID_TABLE_ADDR;
efi.smbios = EFI_INVALID_TABLE_ADDR;
efi.sal_systab = EFI_INVALID_TABLE_ADDR;
efi.boot_info = EFI_INVALID_TABLE_ADDR;
efi.hcdp = EFI_INVALID_TABLE_ADDR;
efi.uga = EFI_INVALID_TABLE_ADDR;
palo_phys = EFI_INVALID_TABLE_ADDR;
for (i = 0; i < (int) efi.systab->nr_tables; i++) {
if (efi_guidcmp(config_tables[i].guid, MPS_TABLE_GUID) == 0) {
efi.mps = config_tables[i].table;
printk(" MPS=0x%lx", config_tables[i].table);
} else if (efi_guidcmp(config_tables[i].guid, ACPI_20_TABLE_GUID) == 0) {
efi.acpi20 = config_tables[i].table;
printk(" ACPI 2.0=0x%lx", config_tables[i].table);
} else if (efi_guidcmp(config_tables[i].guid, ACPI_TABLE_GUID) == 0) {
efi.acpi = config_tables[i].table;
printk(" ACPI=0x%lx", config_tables[i].table);
} else if (efi_guidcmp(config_tables[i].guid, SMBIOS_TABLE_GUID) == 0) {
efi.smbios = config_tables[i].table;
printk(" SMBIOS=0x%lx", config_tables[i].table);
} else if (efi_guidcmp(config_tables[i].guid, SAL_SYSTEM_TABLE_GUID) == 0) {
efi.sal_systab = config_tables[i].table;
printk(" SALsystab=0x%lx", config_tables[i].table);
} else if (efi_guidcmp(config_tables[i].guid, HCDP_TABLE_GUID) == 0) {
efi.hcdp = config_tables[i].table;
printk(" HCDP=0x%lx", config_tables[i].table);
} else if (efi_guidcmp(config_tables[i].guid,
PROCESSOR_ABSTRACTION_LAYER_OVERWRITE_GUID) == 0) {
palo_phys = config_tables[i].table;
printk(" PALO=0x%lx", config_tables[i].table);
}
}
printk("\n");
if (palo_phys != EFI_INVALID_TABLE_ADDR)
handle_palo(palo_phys);
runtime = __va(efi.systab->runtime);
efi.get_time = phys_get_time;
efi.set_time = phys_set_time;
efi.get_wakeup_time = phys_get_wakeup_time;
efi.set_wakeup_time = phys_set_wakeup_time;
efi.get_variable = phys_get_variable;
efi.get_next_variable = phys_get_next_variable;
efi.set_variable = phys_set_variable;
efi.get_next_high_mono_count = phys_get_next_high_mono_count;
efi.reset_system = phys_reset_system;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
#if EFI_DEBUG
/* print EFI memory map: */
{
efi_memory_desc_t *md;
void *p;
for (i = 0, p = efi_map_start; p < efi_map_end;
++i, p += efi_desc_size)
{
const char *unit;
unsigned long size;
md = p;
size = md->num_pages << EFI_PAGE_SHIFT;
if ((size >> 40) > 0) {
size >>= 40;
unit = "TB";
} else if ((size >> 30) > 0) {
size >>= 30;
unit = "GB";
} else if ((size >> 20) > 0) {
size >>= 20;
unit = "MB";
} else {
size >>= 10;
unit = "KB";
}
printk("mem%02d: type=%2u, attr=0x%016lx, "
"range=[0x%016lx-0x%016lx) (%4lu%s)\n",
i, md->type, md->attribute, md->phys_addr,
md->phys_addr + efi_md_size(md), size, unit);
}
}
#endif
efi_map_pal_code();
efi_enter_virtual_mode();
}
void
efi_enter_virtual_mode (void)
{
void *efi_map_start, *efi_map_end, *p;
efi_memory_desc_t *md;
efi_status_t status;
u64 efi_desc_size;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
for (p = efi_map_start; p < efi_map_end; p += efi_desc_size) {
md = p;
if (md->attribute & EFI_MEMORY_RUNTIME) {
/*
* Some descriptors have multiple bits set, so the
* order of the tests is relevant.
*/
if (md->attribute & EFI_MEMORY_WB) {
md->virt_addr = (u64) __va(md->phys_addr);
} else if (md->attribute & EFI_MEMORY_UC) {
md->virt_addr = (u64) ioremap(md->phys_addr, 0);
} else if (md->attribute & EFI_MEMORY_WC) {
#if 0
md->virt_addr = ia64_remap(md->phys_addr,
(_PAGE_A |
_PAGE_P |
_PAGE_D |
_PAGE_MA_WC |
_PAGE_PL_0 |
_PAGE_AR_RW));
#else
printk(KERN_INFO "EFI_MEMORY_WC mapping\n");
md->virt_addr = (u64) ioremap(md->phys_addr, 0);
#endif
} else if (md->attribute & EFI_MEMORY_WT) {
#if 0
md->virt_addr = ia64_remap(md->phys_addr,
(_PAGE_A |
_PAGE_P |
_PAGE_D |
_PAGE_MA_WT |
_PAGE_PL_0 |
_PAGE_AR_RW));
#else
printk(KERN_INFO "EFI_MEMORY_WT mapping\n");
md->virt_addr = (u64) ioremap(md->phys_addr, 0);
#endif
}
}
}
status = efi_call_phys(__va(runtime->set_virtual_address_map),
ia64_boot_param->efi_memmap_size,
efi_desc_size,
ia64_boot_param->efi_memdesc_version,
ia64_boot_param->efi_memmap);
if (status != EFI_SUCCESS) {
printk(KERN_WARNING "warning: unable to switch EFI into "
"virtual mode (status=%lu)\n", status);
return;
}
/*
* Now that EFI is in virtual mode, we call the EFI functions more
* efficiently:
*/
efi.get_time = virt_get_time;
efi.set_time = virt_set_time;
efi.get_wakeup_time = virt_get_wakeup_time;
efi.set_wakeup_time = virt_set_wakeup_time;
efi.get_variable = virt_get_variable;
efi.get_next_variable = virt_get_next_variable;
efi.set_variable = virt_set_variable;
efi.get_next_high_mono_count = virt_get_next_high_mono_count;
efi.reset_system = virt_reset_system;
}
/*
* Walk the EFI memory map looking for the I/O port range. There can only be
* one entry of this type, other I/O port ranges should be described via ACPI.
*/
u64
efi_get_iobase (void)
{
void *efi_map_start, *efi_map_end, *p;
efi_memory_desc_t *md;
u64 efi_desc_size;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
for (p = efi_map_start; p < efi_map_end; p += efi_desc_size) {
md = p;
if (md->type == EFI_MEMORY_MAPPED_IO_PORT_SPACE) {
if (md->attribute & EFI_MEMORY_UC)
return md->phys_addr;
}
}
return 0;
}
static struct kern_memdesc *
kern_memory_descriptor (unsigned long phys_addr)
{
struct kern_memdesc *md;
for (md = kern_memmap; md->start != ~0UL; md++) {
if (phys_addr - md->start < (md->num_pages << EFI_PAGE_SHIFT))
return md;
}
return NULL;
}
static efi_memory_desc_t *
efi_memory_descriptor (unsigned long phys_addr)
{
void *efi_map_start, *efi_map_end, *p;
efi_memory_desc_t *md;
u64 efi_desc_size;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
for (p = efi_map_start; p < efi_map_end; p += efi_desc_size) {
md = p;
if (phys_addr - md->phys_addr < efi_md_size(md))
return md;
}
return NULL;
}
static int
efi_memmap_intersects (unsigned long phys_addr, unsigned long size)
{
void *efi_map_start, *efi_map_end, *p;
efi_memory_desc_t *md;
u64 efi_desc_size;
unsigned long end;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
end = phys_addr + size;
for (p = efi_map_start; p < efi_map_end; p += efi_desc_size) {
md = p;
if (md->phys_addr < end && efi_md_end(md) > phys_addr)
return 1;
}
return 0;
}
u32
efi_mem_type (unsigned long phys_addr)
{
efi_memory_desc_t *md = efi_memory_descriptor(phys_addr);
if (md)
return md->type;
return 0;
}
u64
efi_mem_attributes (unsigned long phys_addr)
{
efi_memory_desc_t *md = efi_memory_descriptor(phys_addr);
if (md)
return md->attribute;
return 0;
}
EXPORT_SYMBOL(efi_mem_attributes);
u64
efi_mem_attribute (unsigned long phys_addr, unsigned long size)
{
unsigned long end = phys_addr + size;
efi_memory_desc_t *md = efi_memory_descriptor(phys_addr);
u64 attr;
if (!md)
return 0;
/*
* EFI_MEMORY_RUNTIME is not a memory attribute; it just tells
* the kernel that firmware needs this region mapped.
*/
attr = md->attribute & ~EFI_MEMORY_RUNTIME;
do {
unsigned long md_end = efi_md_end(md);
if (end <= md_end)
return attr;
md = efi_memory_descriptor(md_end);
if (!md || (md->attribute & ~EFI_MEMORY_RUNTIME) != attr)
return 0;
} while (md);
return 0; /* never reached */
}
u64
kern_mem_attribute (unsigned long phys_addr, unsigned long size)
{
unsigned long end = phys_addr + size;
struct kern_memdesc *md;
u64 attr;
/*
* This is a hack for ioremap calls before we set up kern_memmap.
* Maybe we should do efi_memmap_init() earlier instead.
*/
if (!kern_memmap) {
attr = efi_mem_attribute(phys_addr, size);
if (attr & EFI_MEMORY_WB)
return EFI_MEMORY_WB;
return 0;
}
md = kern_memory_descriptor(phys_addr);
if (!md)
return 0;
attr = md->attribute;
do {
unsigned long md_end = kmd_end(md);
if (end <= md_end)
return attr;
md = kern_memory_descriptor(md_end);
if (!md || md->attribute != attr)
return 0;
} while (md);
return 0; /* never reached */
}
EXPORT_SYMBOL(kern_mem_attribute);
int
valid_phys_addr_range (unsigned long phys_addr, unsigned long size)
{
u64 attr;
/*
* /dev/mem reads and writes use copy_to_user(), which implicitly
* uses a granule-sized kernel identity mapping. It's really
* only safe to do this for regions in kern_memmap. For more
* details, see Documentation/ia64/aliasing.txt.
*/
attr = kern_mem_attribute(phys_addr, size);
if (attr & EFI_MEMORY_WB || attr & EFI_MEMORY_UC)
return 1;
return 0;
}
int
valid_mmap_phys_addr_range (unsigned long pfn, unsigned long size)
{
unsigned long phys_addr = pfn << PAGE_SHIFT;
u64 attr;
attr = efi_mem_attribute(phys_addr, size);
/*
* /dev/mem mmap uses normal user pages, so we don't need the entire
* granule, but the entire region we're mapping must support the same
* attribute.
*/
if (attr & EFI_MEMORY_WB || attr & EFI_MEMORY_UC)
return 1;
/*
* Intel firmware doesn't tell us about all the MMIO regions, so
* in general we have to allow mmap requests. But if EFI *does*
* tell us about anything inside this region, we should deny it.
* The user can always map a smaller region to avoid the overlap.
*/
if (efi_memmap_intersects(phys_addr, size))
return 0;
return 1;
}
pgprot_t
phys_mem_access_prot(struct file *file, unsigned long pfn, unsigned long size,
pgprot_t vma_prot)
{
unsigned long phys_addr = pfn << PAGE_SHIFT;
u64 attr;
/*
* For /dev/mem mmap, we use user mappings, but if the region is
* in kern_memmap (and hence may be covered by a kernel mapping),
* we must use the same attribute as the kernel mapping.
*/
attr = kern_mem_attribute(phys_addr, size);
if (attr & EFI_MEMORY_WB)
return pgprot_cacheable(vma_prot);
else if (attr & EFI_MEMORY_UC)
return pgprot_noncached(vma_prot);
/*
* Some chipsets don't support UC access to memory. If
* WB is supported, we prefer that.
*/
if (efi_mem_attribute(phys_addr, size) & EFI_MEMORY_WB)
return pgprot_cacheable(vma_prot);
return pgprot_noncached(vma_prot);
}
int __init
efi_uart_console_only(void)
{
efi_status_t status;
char *s, name[] = "ConOut";
efi_guid_t guid = EFI_GLOBAL_VARIABLE_GUID;
efi_char16_t *utf16, name_utf16[32];
unsigned char data[1024];
unsigned long size = sizeof(data);
struct efi_generic_dev_path *hdr, *end_addr;
int uart = 0;
/* Convert to UTF-16 */
utf16 = name_utf16;
s = name;
while (*s)
*utf16++ = *s++ & 0x7f;
*utf16 = 0;
status = efi.get_variable(name_utf16, &guid, NULL, &size, data);
if (status != EFI_SUCCESS) {
printk(KERN_ERR "No EFI %s variable?\n", name);
return 0;
}
hdr = (struct efi_generic_dev_path *) data;
end_addr = (struct efi_generic_dev_path *) ((u8 *) data + size);
while (hdr < end_addr) {
if (hdr->type == EFI_DEV_MSG &&
hdr->sub_type == EFI_DEV_MSG_UART)
uart = 1;
else if (hdr->type == EFI_DEV_END_PATH ||
hdr->type == EFI_DEV_END_PATH2) {
if (!uart)
return 0;
if (hdr->sub_type == EFI_DEV_END_ENTIRE)
return 1;
uart = 0;
}
hdr = (struct efi_generic_dev_path *)((u8 *) hdr + hdr->length);
}
printk(KERN_ERR "Malformed %s value\n", name);
return 0;
}
/*
* Look for the first granule aligned memory descriptor memory
* that is big enough to hold EFI memory map. Make sure this
* descriptor is atleast granule sized so it does not get trimmed
*/
struct kern_memdesc *
find_memmap_space (void)
{
u64 contig_low=0, contig_high=0;
u64 as = 0, ae;
void *efi_map_start, *efi_map_end, *p, *q;
efi_memory_desc_t *md, *pmd = NULL, *check_md;
u64 space_needed, efi_desc_size;
unsigned long total_mem = 0;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
/*
* Worst case: we need 3 kernel descriptors for each efi descriptor
* (if every entry has a WB part in the middle, and UC head and tail),
* plus one for the end marker.
*/
space_needed = sizeof(kern_memdesc_t) *
(3 * (ia64_boot_param->efi_memmap_size/efi_desc_size) + 1);
for (p = efi_map_start; p < efi_map_end; pmd = md, p += efi_desc_size) {
md = p;
if (!efi_wb(md)) {
continue;
}
if (pmd == NULL || !efi_wb(pmd) ||
efi_md_end(pmd) != md->phys_addr) {
contig_low = GRANULEROUNDUP(md->phys_addr);
contig_high = efi_md_end(md);
for (q = p + efi_desc_size; q < efi_map_end;
q += efi_desc_size) {
check_md = q;
if (!efi_wb(check_md))
break;
if (contig_high != check_md->phys_addr)
break;
contig_high = efi_md_end(check_md);
}
contig_high = GRANULEROUNDDOWN(contig_high);
}
if (!is_memory_available(md) || md->type == EFI_LOADER_DATA)
continue;
/* Round ends inward to granule boundaries */
as = max(contig_low, md->phys_addr);
ae = min(contig_high, efi_md_end(md));
/* keep within max_addr= and min_addr= command line arg */
as = max(as, min_addr);
ae = min(ae, max_addr);
if (ae <= as)
continue;
/* avoid going over mem= command line arg */
if (total_mem + (ae - as) > mem_limit)
ae -= total_mem + (ae - as) - mem_limit;
if (ae <= as)
continue;
if (ae - as > space_needed)
break;
}
if (p >= efi_map_end)
panic("Can't allocate space for kernel memory descriptors");
return __va(as);
}
/*
* Walk the EFI memory map and gather all memory available for kernel
* to use. We can allocate partial granules only if the unavailable
* parts exist, and are WB.
*/
unsigned long
efi_memmap_init(u64 *s, u64 *e)
{
struct kern_memdesc *k, *prev = NULL;
u64 contig_low=0, contig_high=0;
u64 as, ae, lim;
void *efi_map_start, *efi_map_end, *p, *q;
efi_memory_desc_t *md, *pmd = NULL, *check_md;
u64 efi_desc_size;
unsigned long total_mem = 0;
k = kern_memmap = find_memmap_space();
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
for (p = efi_map_start; p < efi_map_end; pmd = md, p += efi_desc_size) {
md = p;
if (!efi_wb(md)) {
if (efi_uc(md) &&
(md->type == EFI_CONVENTIONAL_MEMORY ||
md->type == EFI_BOOT_SERVICES_DATA)) {
k->attribute = EFI_MEMORY_UC;
k->start = md->phys_addr;
k->num_pages = md->num_pages;
k++;
}
continue;
}
if (pmd == NULL || !efi_wb(pmd) ||
efi_md_end(pmd) != md->phys_addr) {
contig_low = GRANULEROUNDUP(md->phys_addr);
contig_high = efi_md_end(md);
for (q = p + efi_desc_size; q < efi_map_end;
q += efi_desc_size) {
check_md = q;
if (!efi_wb(check_md))
break;
if (contig_high != check_md->phys_addr)
break;
contig_high = efi_md_end(check_md);
}
contig_high = GRANULEROUNDDOWN(contig_high);
}
if (!is_memory_available(md))
continue;
#ifdef CONFIG_CRASH_DUMP
/* saved_max_pfn should ignore max_addr= command line arg */
if (saved_max_pfn < (efi_md_end(md) >> PAGE_SHIFT))
saved_max_pfn = (efi_md_end(md) >> PAGE_SHIFT);
#endif
/*
* Round ends inward to granule boundaries
* Give trimmings to uncached allocator
*/
if (md->phys_addr < contig_low) {
lim = min(efi_md_end(md), contig_low);
if (efi_uc(md)) {
if (k > kern_memmap &&
(k-1)->attribute == EFI_MEMORY_UC &&
kmd_end(k-1) == md->phys_addr) {
(k-1)->num_pages +=
(lim - md->phys_addr)
>> EFI_PAGE_SHIFT;
} else {
k->attribute = EFI_MEMORY_UC;
k->start = md->phys_addr;
k->num_pages = (lim - md->phys_addr)
>> EFI_PAGE_SHIFT;
k++;
}
}
as = contig_low;
} else
as = md->phys_addr;
if (efi_md_end(md) > contig_high) {
lim = max(md->phys_addr, contig_high);
if (efi_uc(md)) {
if (lim == md->phys_addr && k > kern_memmap &&
(k-1)->attribute == EFI_MEMORY_UC &&
kmd_end(k-1) == md->phys_addr) {
(k-1)->num_pages += md->num_pages;
} else {
k->attribute = EFI_MEMORY_UC;
k->start = lim;
k->num_pages = (efi_md_end(md) - lim)
>> EFI_PAGE_SHIFT;
k++;
}
}
ae = contig_high;
} else
ae = efi_md_end(md);
/* keep within max_addr= and min_addr= command line arg */
as = max(as, min_addr);
ae = min(ae, max_addr);
if (ae <= as)
continue;
/* avoid going over mem= command line arg */
if (total_mem + (ae - as) > mem_limit)
ae -= total_mem + (ae - as) - mem_limit;
if (ae <= as)
continue;
if (prev && kmd_end(prev) == md->phys_addr) {
prev->num_pages += (ae - as) >> EFI_PAGE_SHIFT;
total_mem += ae - as;
continue;
}
k->attribute = EFI_MEMORY_WB;
k->start = as;
k->num_pages = (ae - as) >> EFI_PAGE_SHIFT;
total_mem += ae - as;
prev = k++;
}
k->start = ~0L; /* end-marker */
/* reserve the memory we are using for kern_memmap */
*s = (u64)kern_memmap;
*e = (u64)++k;
return total_mem;
}
void
efi_initialize_iomem_resources(struct resource *code_resource,
struct resource *data_resource,
struct resource *bss_resource)
{
struct resource *res;
void *efi_map_start, *efi_map_end, *p;
efi_memory_desc_t *md;
u64 efi_desc_size;
char *name;
unsigned long flags;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
res = NULL;
for (p = efi_map_start; p < efi_map_end; p += efi_desc_size) {
md = p;
if (md->num_pages == 0) /* should not happen */
continue;
flags = IORESOURCE_MEM | IORESOURCE_BUSY;
switch (md->type) {
case EFI_MEMORY_MAPPED_IO:
case EFI_MEMORY_MAPPED_IO_PORT_SPACE:
continue;
case EFI_LOADER_CODE:
case EFI_LOADER_DATA:
case EFI_BOOT_SERVICES_DATA:
case EFI_BOOT_SERVICES_CODE:
case EFI_CONVENTIONAL_MEMORY:
if (md->attribute & EFI_MEMORY_WP) {
name = "System ROM";
flags |= IORESOURCE_READONLY;
} else if (md->attribute == EFI_MEMORY_UC)
name = "Uncached RAM";
else
name = "System RAM";
break;
case EFI_ACPI_MEMORY_NVS:
name = "ACPI Non-volatile Storage";
break;
case EFI_UNUSABLE_MEMORY:
name = "reserved";
flags |= IORESOURCE_DISABLED;
break;
case EFI_RESERVED_TYPE:
case EFI_RUNTIME_SERVICES_CODE:
case EFI_RUNTIME_SERVICES_DATA:
case EFI_ACPI_RECLAIM_MEMORY:
default:
name = "reserved";
break;
}
if ((res = kzalloc(sizeof(struct resource),
GFP_KERNEL)) == NULL) {
printk(KERN_ERR
"failed to allocate resource for iomem\n");
return;
}
res->name = name;
res->start = md->phys_addr;
res->end = md->phys_addr + efi_md_size(md) - 1;
res->flags = flags;
if (insert_resource(&iomem_resource, res) < 0)
kfree(res);
else {
/*
* We don't know which region contains
* kernel data so we try it repeatedly and
* let the resource manager test it.
*/
insert_resource(res, code_resource);
insert_resource(res, data_resource);
insert_resource(res, bss_resource);
#ifdef CONFIG_KEXEC
insert_resource(res, &efi_memmap_res);
insert_resource(res, &boot_param_res);
if (crashk_res.end > crashk_res.start)
insert_resource(res, &crashk_res);
#endif
}
}
}
#ifdef CONFIG_KEXEC
/* find a block of memory aligned to 64M exclude reserved regions
rsvd_regions are sorted
*/
unsigned long __init
kdump_find_rsvd_region (unsigned long size, struct rsvd_region *r, int n)
{
int i;
u64 start, end;
u64 alignment = 1UL << _PAGE_SIZE_64M;
void *efi_map_start, *efi_map_end, *p;
efi_memory_desc_t *md;
u64 efi_desc_size;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
for (p = efi_map_start; p < efi_map_end; p += efi_desc_size) {
md = p;
if (!efi_wb(md))
continue;
start = ALIGN(md->phys_addr, alignment);
end = efi_md_end(md);
for (i = 0; i < n; i++) {
if (__pa(r[i].start) >= start && __pa(r[i].end) < end) {
if (__pa(r[i].start) > start + size)
return start;
start = ALIGN(__pa(r[i].end), alignment);
if (i < n-1 &&
__pa(r[i+1].start) < start + size)
continue;
else
break;
}
}
if (end > start + size)
return start;
}
printk(KERN_WARNING
"Cannot reserve 0x%lx byte of memory for crashdump\n", size);
return ~0UL;
}
#endif
#ifdef CONFIG_CRASH_DUMP
/* locate the size find a the descriptor at a certain address */
unsigned long __init
vmcore_find_descriptor_size (unsigned long address)
{
void *efi_map_start, *efi_map_end, *p;
efi_memory_desc_t *md;
u64 efi_desc_size;
unsigned long ret = 0;
efi_map_start = __va(ia64_boot_param->efi_memmap);
efi_map_end = efi_map_start + ia64_boot_param->efi_memmap_size;
efi_desc_size = ia64_boot_param->efi_memdesc_size;
for (p = efi_map_start; p < efi_map_end; p += efi_desc_size) {
md = p;
if (efi_wb(md) && md->type == EFI_LOADER_DATA
&& md->phys_addr == address) {
ret = efi_md_size(md);
break;
}
}
if (ret == 0)
printk(KERN_WARNING "Cannot locate EFI vmcore descriptor\n");
return ret;
}
#endif
| gpl-2.0 |
DirtyUnicorns/android_kernel_asus_Z00A | kernel/profile.c | 1160 | 16463 | /*
* linux/kernel/profile.c
* Simple profiling. Manages a direct-mapped profile hit count buffer,
* with configurable resolution, support for restricting the cpus on
* which profiling is done, and switching between cpu time and
* schedule() calls via kernel command line parameters passed at boot.
*
* Scheduler profiling support, Arjan van de Ven and Ingo Molnar,
* Red Hat, July 2004
* Consolidation of architecture support code for profiling,
* Nadia Yvette Chambers, Oracle, July 2004
* Amortized hit count accounting via per-cpu open-addressed hashtables
* to resolve timer interrupt livelocks, Nadia Yvette Chambers,
* Oracle, 2004
*/
#include <linux/export.h>
#include <linux/profile.h>
#include <linux/bootmem.h>
#include <linux/notifier.h>
#include <linux/mm.h>
#include <linux/cpumask.h>
#include <linux/cpu.h>
#include <linux/highmem.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <asm/sections.h>
#include <asm/irq_regs.h>
#include <asm/ptrace.h>
struct profile_hit {
u32 pc, hits;
};
#define PROFILE_GRPSHIFT 3
#define PROFILE_GRPSZ (1 << PROFILE_GRPSHIFT)
#define NR_PROFILE_HIT (PAGE_SIZE/sizeof(struct profile_hit))
#define NR_PROFILE_GRP (NR_PROFILE_HIT/PROFILE_GRPSZ)
static atomic_t *prof_buffer;
static unsigned long prof_len, prof_shift;
int prof_on __read_mostly;
EXPORT_SYMBOL_GPL(prof_on);
static cpumask_var_t prof_cpu_mask;
#ifdef CONFIG_SMP
static DEFINE_PER_CPU(struct profile_hit *[2], cpu_profile_hits);
static DEFINE_PER_CPU(int, cpu_profile_flip);
static DEFINE_MUTEX(profile_flip_mutex);
#endif /* CONFIG_SMP */
int profile_setup(char *str)
{
static char schedstr[] = "schedule";
static char sleepstr[] = "sleep";
static char kvmstr[] = "kvm";
int par;
if (!strncmp(str, sleepstr, strlen(sleepstr))) {
#ifdef CONFIG_SCHEDSTATS
prof_on = SLEEP_PROFILING;
if (str[strlen(sleepstr)] == ',')
str += strlen(sleepstr) + 1;
if (get_option(&str, &par))
prof_shift = par;
printk(KERN_INFO
"kernel sleep profiling enabled (shift: %ld)\n",
prof_shift);
#else
printk(KERN_WARNING
"kernel sleep profiling requires CONFIG_SCHEDSTATS\n");
#endif /* CONFIG_SCHEDSTATS */
} else if (!strncmp(str, schedstr, strlen(schedstr))) {
prof_on = SCHED_PROFILING;
if (str[strlen(schedstr)] == ',')
str += strlen(schedstr) + 1;
if (get_option(&str, &par))
prof_shift = par;
printk(KERN_INFO
"kernel schedule profiling enabled (shift: %ld)\n",
prof_shift);
} else if (!strncmp(str, kvmstr, strlen(kvmstr))) {
prof_on = KVM_PROFILING;
if (str[strlen(kvmstr)] == ',')
str += strlen(kvmstr) + 1;
if (get_option(&str, &par))
prof_shift = par;
printk(KERN_INFO
"kernel KVM profiling enabled (shift: %ld)\n",
prof_shift);
} else if (get_option(&str, &par)) {
prof_shift = par;
prof_on = CPU_PROFILING;
printk(KERN_INFO "kernel profiling enabled (shift: %ld)\n",
prof_shift);
}
return 1;
}
__setup("profile=", profile_setup);
int __ref profile_init(void)
{
int buffer_bytes;
if (!prof_on)
return 0;
/* only text is profiled */
prof_len = (_etext - _stext) >> prof_shift;
buffer_bytes = prof_len*sizeof(atomic_t);
if (!alloc_cpumask_var(&prof_cpu_mask, GFP_KERNEL))
return -ENOMEM;
cpumask_copy(prof_cpu_mask, cpu_possible_mask);
prof_buffer = kzalloc(buffer_bytes, GFP_KERNEL|__GFP_NOWARN);
if (prof_buffer)
return 0;
prof_buffer = alloc_pages_exact(buffer_bytes,
GFP_KERNEL|__GFP_ZERO|__GFP_NOWARN);
if (prof_buffer)
return 0;
prof_buffer = vzalloc(buffer_bytes);
if (prof_buffer)
return 0;
free_cpumask_var(prof_cpu_mask);
return -ENOMEM;
}
/* Profile event notifications */
static BLOCKING_NOTIFIER_HEAD(task_exit_notifier);
static ATOMIC_NOTIFIER_HEAD(task_free_notifier);
static BLOCKING_NOTIFIER_HEAD(munmap_notifier);
void profile_task_exit(struct task_struct *task)
{
blocking_notifier_call_chain(&task_exit_notifier, 0, task);
}
int profile_handoff_task(struct task_struct *task)
{
int ret;
ret = atomic_notifier_call_chain(&task_free_notifier, 0, task);
return (ret == NOTIFY_OK) ? 1 : 0;
}
void profile_munmap(unsigned long addr)
{
blocking_notifier_call_chain(&munmap_notifier, 0, (void *)addr);
}
int task_handoff_register(struct notifier_block *n)
{
return atomic_notifier_chain_register(&task_free_notifier, n);
}
EXPORT_SYMBOL_GPL(task_handoff_register);
int task_handoff_unregister(struct notifier_block *n)
{
return atomic_notifier_chain_unregister(&task_free_notifier, n);
}
EXPORT_SYMBOL_GPL(task_handoff_unregister);
int profile_event_register(enum profile_type type, struct notifier_block *n)
{
int err = -EINVAL;
switch (type) {
case PROFILE_TASK_EXIT:
err = blocking_notifier_chain_register(
&task_exit_notifier, n);
break;
case PROFILE_MUNMAP:
err = blocking_notifier_chain_register(
&munmap_notifier, n);
break;
}
return err;
}
EXPORT_SYMBOL_GPL(profile_event_register);
int profile_event_unregister(enum profile_type type, struct notifier_block *n)
{
int err = -EINVAL;
switch (type) {
case PROFILE_TASK_EXIT:
err = blocking_notifier_chain_unregister(
&task_exit_notifier, n);
break;
case PROFILE_MUNMAP:
err = blocking_notifier_chain_unregister(
&munmap_notifier, n);
break;
}
return err;
}
EXPORT_SYMBOL_GPL(profile_event_unregister);
#ifdef CONFIG_SMP
/*
* Each cpu has a pair of open-addressed hashtables for pending
* profile hits. read_profile() IPI's all cpus to request them
* to flip buffers and flushes their contents to prof_buffer itself.
* Flip requests are serialized by the profile_flip_mutex. The sole
* use of having a second hashtable is for avoiding cacheline
* contention that would otherwise happen during flushes of pending
* profile hits required for the accuracy of reported profile hits
* and so resurrect the interrupt livelock issue.
*
* The open-addressed hashtables are indexed by profile buffer slot
* and hold the number of pending hits to that profile buffer slot on
* a cpu in an entry. When the hashtable overflows, all pending hits
* are accounted to their corresponding profile buffer slots with
* atomic_add() and the hashtable emptied. As numerous pending hits
* may be accounted to a profile buffer slot in a hashtable entry,
* this amortizes a number of atomic profile buffer increments likely
* to be far larger than the number of entries in the hashtable,
* particularly given that the number of distinct profile buffer
* positions to which hits are accounted during short intervals (e.g.
* several seconds) is usually very small. Exclusion from buffer
* flipping is provided by interrupt disablement (note that for
* SCHED_PROFILING or SLEEP_PROFILING profile_hit() may be called from
* process context).
* The hash function is meant to be lightweight as opposed to strong,
* and was vaguely inspired by ppc64 firmware-supported inverted
* pagetable hash functions, but uses a full hashtable full of finite
* collision chains, not just pairs of them.
*
* -- nyc
*/
static void __profile_flip_buffers(void *unused)
{
int cpu = smp_processor_id();
per_cpu(cpu_profile_flip, cpu) = !per_cpu(cpu_profile_flip, cpu);
}
static void profile_flip_buffers(void)
{
int i, j, cpu;
mutex_lock(&profile_flip_mutex);
j = per_cpu(cpu_profile_flip, get_cpu());
put_cpu();
on_each_cpu(__profile_flip_buffers, NULL, 1);
for_each_online_cpu(cpu) {
struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[j];
for (i = 0; i < NR_PROFILE_HIT; ++i) {
if (!hits[i].hits) {
if (hits[i].pc)
hits[i].pc = 0;
continue;
}
atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
hits[i].hits = hits[i].pc = 0;
}
}
mutex_unlock(&profile_flip_mutex);
}
static void profile_discard_flip_buffers(void)
{
int i, cpu;
mutex_lock(&profile_flip_mutex);
i = per_cpu(cpu_profile_flip, get_cpu());
put_cpu();
on_each_cpu(__profile_flip_buffers, NULL, 1);
for_each_online_cpu(cpu) {
struct profile_hit *hits = per_cpu(cpu_profile_hits, cpu)[i];
memset(hits, 0, NR_PROFILE_HIT*sizeof(struct profile_hit));
}
mutex_unlock(&profile_flip_mutex);
}
static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
{
unsigned long primary, secondary, flags, pc = (unsigned long)__pc;
int i, j, cpu;
struct profile_hit *hits;
pc = min((pc - (unsigned long)_stext) >> prof_shift, prof_len - 1);
i = primary = (pc & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
secondary = (~(pc << 1) & (NR_PROFILE_GRP - 1)) << PROFILE_GRPSHIFT;
cpu = get_cpu();
hits = per_cpu(cpu_profile_hits, cpu)[per_cpu(cpu_profile_flip, cpu)];
if (!hits) {
put_cpu();
return;
}
/*
* We buffer the global profiler buffer into a per-CPU
* queue and thus reduce the number of global (and possibly
* NUMA-alien) accesses. The write-queue is self-coalescing:
*/
local_irq_save(flags);
do {
for (j = 0; j < PROFILE_GRPSZ; ++j) {
if (hits[i + j].pc == pc) {
hits[i + j].hits += nr_hits;
goto out;
} else if (!hits[i + j].hits) {
hits[i + j].pc = pc;
hits[i + j].hits = nr_hits;
goto out;
}
}
i = (i + secondary) & (NR_PROFILE_HIT - 1);
} while (i != primary);
/*
* Add the current hit(s) and flush the write-queue out
* to the global buffer:
*/
atomic_add(nr_hits, &prof_buffer[pc]);
for (i = 0; i < NR_PROFILE_HIT; ++i) {
atomic_add(hits[i].hits, &prof_buffer[hits[i].pc]);
hits[i].pc = hits[i].hits = 0;
}
out:
local_irq_restore(flags);
put_cpu();
}
static int __cpuinit profile_cpu_callback(struct notifier_block *info,
unsigned long action, void *__cpu)
{
int node, cpu = (unsigned long)__cpu;
struct page *page;
switch (action) {
case CPU_UP_PREPARE:
case CPU_UP_PREPARE_FROZEN:
node = cpu_to_mem(cpu);
per_cpu(cpu_profile_flip, cpu) = 0;
if (!per_cpu(cpu_profile_hits, cpu)[1]) {
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO,
0);
if (!page)
return notifier_from_errno(-ENOMEM);
per_cpu(cpu_profile_hits, cpu)[1] = page_address(page);
}
if (!per_cpu(cpu_profile_hits, cpu)[0]) {
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO,
0);
if (!page)
goto out_free;
per_cpu(cpu_profile_hits, cpu)[0] = page_address(page);
}
break;
out_free:
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[1]);
per_cpu(cpu_profile_hits, cpu)[1] = NULL;
__free_page(page);
return notifier_from_errno(-ENOMEM);
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
if (prof_cpu_mask != NULL)
cpumask_set_cpu(cpu, prof_cpu_mask);
break;
case CPU_UP_CANCELED:
case CPU_UP_CANCELED_FROZEN:
case CPU_DEAD:
case CPU_DEAD_FROZEN:
if (prof_cpu_mask != NULL)
cpumask_clear_cpu(cpu, prof_cpu_mask);
if (per_cpu(cpu_profile_hits, cpu)[0]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[0]);
per_cpu(cpu_profile_hits, cpu)[0] = NULL;
__free_page(page);
}
if (per_cpu(cpu_profile_hits, cpu)[1]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[1]);
per_cpu(cpu_profile_hits, cpu)[1] = NULL;
__free_page(page);
}
break;
}
return NOTIFY_OK;
}
#else /* !CONFIG_SMP */
#define profile_flip_buffers() do { } while (0)
#define profile_discard_flip_buffers() do { } while (0)
#define profile_cpu_callback NULL
static void do_profile_hits(int type, void *__pc, unsigned int nr_hits)
{
unsigned long pc;
pc = ((unsigned long)__pc - (unsigned long)_stext) >> prof_shift;
atomic_add(nr_hits, &prof_buffer[min(pc, prof_len - 1)]);
}
#endif /* !CONFIG_SMP */
void profile_hits(int type, void *__pc, unsigned int nr_hits)
{
if (prof_on != type || !prof_buffer)
return;
do_profile_hits(type, __pc, nr_hits);
}
EXPORT_SYMBOL_GPL(profile_hits);
void profile_tick(int type)
{
struct pt_regs *regs = get_irq_regs();
if (!user_mode(regs) && prof_cpu_mask != NULL &&
cpumask_test_cpu(smp_processor_id(), prof_cpu_mask))
profile_hit(type, (void *)profile_pc(regs));
}
#ifdef CONFIG_PROC_FS
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/uaccess.h>
static int prof_cpu_mask_proc_show(struct seq_file *m, void *v)
{
seq_cpumask(m, prof_cpu_mask);
seq_putc(m, '\n');
return 0;
}
static int prof_cpu_mask_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, prof_cpu_mask_proc_show, NULL);
}
static ssize_t prof_cpu_mask_proc_write(struct file *file,
const char __user *buffer, size_t count, loff_t *pos)
{
cpumask_var_t new_value;
int err;
if (!alloc_cpumask_var(&new_value, GFP_KERNEL))
return -ENOMEM;
err = cpumask_parse_user(buffer, count, new_value);
if (!err) {
cpumask_copy(prof_cpu_mask, new_value);
err = count;
}
free_cpumask_var(new_value);
return err;
}
static const struct file_operations prof_cpu_mask_proc_fops = {
.open = prof_cpu_mask_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
.write = prof_cpu_mask_proc_write,
};
void create_prof_cpu_mask(void)
{
/* create /proc/irq/prof_cpu_mask */
proc_create("irq/prof_cpu_mask", 0600, NULL, &prof_cpu_mask_proc_fops);
}
/*
* This function accesses profiling information. The returned data is
* binary: the sampling step and the actual contents of the profile
* buffer. Use of the program readprofile is recommended in order to
* get meaningful info out of these data.
*/
static ssize_t
read_profile(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
unsigned long p = *ppos;
ssize_t read;
char *pnt;
unsigned int sample_step = 1 << prof_shift;
profile_flip_buffers();
if (p >= (prof_len+1)*sizeof(unsigned int))
return 0;
if (count > (prof_len+1)*sizeof(unsigned int) - p)
count = (prof_len+1)*sizeof(unsigned int) - p;
read = 0;
while (p < sizeof(unsigned int) && count > 0) {
if (put_user(*((char *)(&sample_step)+p), buf))
return -EFAULT;
buf++; p++; count--; read++;
}
pnt = (char *)prof_buffer + p - sizeof(atomic_t);
if (copy_to_user(buf, (void *)pnt, count))
return -EFAULT;
read += count;
*ppos += read;
return read;
}
/*
* Writing to /proc/profile resets the counters
*
* Writing a 'profiling multiplier' value into it also re-sets the profiling
* interrupt frequency, on architectures that support this.
*/
static ssize_t write_profile(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
#ifdef CONFIG_SMP
extern int setup_profiling_timer(unsigned int multiplier);
if (count == sizeof(int)) {
unsigned int multiplier;
if (copy_from_user(&multiplier, buf, sizeof(int)))
return -EFAULT;
if (setup_profiling_timer(multiplier))
return -EINVAL;
}
#endif
profile_discard_flip_buffers();
memset(prof_buffer, 0, prof_len * sizeof(atomic_t));
return count;
}
static const struct file_operations proc_profile_operations = {
.read = read_profile,
.write = write_profile,
.llseek = default_llseek,
};
#ifdef CONFIG_SMP
static void profile_nop(void *unused)
{
}
static int create_hash_tables(void)
{
int cpu;
for_each_online_cpu(cpu) {
int node = cpu_to_mem(cpu);
struct page *page;
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO | GFP_THISNODE,
0);
if (!page)
goto out_cleanup;
per_cpu(cpu_profile_hits, cpu)[1]
= (struct profile_hit *)page_address(page);
page = alloc_pages_exact_node(node,
GFP_KERNEL | __GFP_ZERO | GFP_THISNODE,
0);
if (!page)
goto out_cleanup;
per_cpu(cpu_profile_hits, cpu)[0]
= (struct profile_hit *)page_address(page);
}
return 0;
out_cleanup:
prof_on = 0;
smp_mb();
on_each_cpu(profile_nop, NULL, 1);
for_each_online_cpu(cpu) {
struct page *page;
if (per_cpu(cpu_profile_hits, cpu)[0]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[0]);
per_cpu(cpu_profile_hits, cpu)[0] = NULL;
__free_page(page);
}
if (per_cpu(cpu_profile_hits, cpu)[1]) {
page = virt_to_page(per_cpu(cpu_profile_hits, cpu)[1]);
per_cpu(cpu_profile_hits, cpu)[1] = NULL;
__free_page(page);
}
}
return -1;
}
#else
#define create_hash_tables() ({ 0; })
#endif
int __ref create_proc_profile(void) /* false positive from hotcpu_notifier */
{
struct proc_dir_entry *entry;
if (!prof_on)
return 0;
if (create_hash_tables())
return -ENOMEM;
entry = proc_create("profile", S_IWUSR | S_IRUGO,
NULL, &proc_profile_operations);
if (!entry)
return 0;
proc_set_size(entry, (1 + prof_len) * sizeof(atomic_t));
hotcpu_notifier(profile_cpu_callback, 0);
return 0;
}
module_init(create_proc_profile);
#endif /* CONFIG_PROC_FS */
| gpl-2.0 |
allanm84/linux-fslc | drivers/watchdog/it87_wdt.c | 1160 | 18703 | /*
* Watchdog Timer Driver
* for ITE IT87xx Environment Control - Low Pin Count Input / Output
*
* (c) Copyright 2007 Oliver Schuster <olivers137@aol.com>
*
* Based on softdog.c by Alan Cox,
* 83977f_wdt.c by Jose Goncalves,
* it87.c by Chris Gauthron, Jean Delvare
*
* Data-sheets: Publicly available at the ITE website
* http://www.ite.com.tw/
*
* Support of the watchdog timers, which are available on
* IT8702, IT8712, IT8716, IT8718, IT8720, IT8721, IT8726,
* IT8728 and IT8783.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/watchdog.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/uaccess.h>
#include <linux/io.h>
#define WATCHDOG_VERSION "1.14"
#define WATCHDOG_NAME "IT87 WDT"
#define DRIVER_VERSION WATCHDOG_NAME " driver, v" WATCHDOG_VERSION "\n"
#define WD_MAGIC 'V'
/* Defaults for Module Parameter */
#define DEFAULT_NOGAMEPORT 0
#define DEFAULT_NOCIR 0
#define DEFAULT_EXCLUSIVE 1
#define DEFAULT_TIMEOUT 60
#define DEFAULT_TESTMODE 0
#define DEFAULT_NOWAYOUT WATCHDOG_NOWAYOUT
/* IO Ports */
#define REG 0x2e
#define VAL 0x2f
/* Logical device Numbers LDN */
#define GPIO 0x07
#define GAMEPORT 0x09
#define CIR 0x0a
/* Configuration Registers and Functions */
#define LDNREG 0x07
#define CHIPID 0x20
#define CHIPREV 0x22
#define ACTREG 0x30
#define BASEREG 0x60
/* Chip Id numbers */
#define NO_DEV_ID 0xffff
#define IT8702_ID 0x8702
#define IT8705_ID 0x8705
#define IT8712_ID 0x8712
#define IT8716_ID 0x8716
#define IT8718_ID 0x8718
#define IT8720_ID 0x8720
#define IT8721_ID 0x8721
#define IT8726_ID 0x8726 /* the data sheet suggest wrongly 0x8716 */
#define IT8728_ID 0x8728
#define IT8783_ID 0x8783
/* GPIO Configuration Registers LDN=0x07 */
#define WDTCTRL 0x71
#define WDTCFG 0x72
#define WDTVALLSB 0x73
#define WDTVALMSB 0x74
/* GPIO Bits WDTCTRL */
#define WDT_CIRINT 0x80
#define WDT_MOUSEINT 0x40
#define WDT_KYBINT 0x20
#define WDT_GAMEPORT 0x10 /* not in it8718, it8720, it8721, it8728 */
#define WDT_FORCE 0x02
#define WDT_ZERO 0x01
/* GPIO Bits WDTCFG */
#define WDT_TOV1 0x80
#define WDT_KRST 0x40
#define WDT_TOVE 0x20
#define WDT_PWROK 0x10 /* not in it8721 */
#define WDT_INT_MASK 0x0f
/* CIR Configuration Register LDN=0x0a */
#define CIR_ILS 0x70
/* The default Base address is not always available, we use this */
#define CIR_BASE 0x0208
/* CIR Controller */
#define CIR_DR(b) (b)
#define CIR_IER(b) (b + 1)
#define CIR_RCR(b) (b + 2)
#define CIR_TCR1(b) (b + 3)
#define CIR_TCR2(b) (b + 4)
#define CIR_TSR(b) (b + 5)
#define CIR_RSR(b) (b + 6)
#define CIR_BDLR(b) (b + 5)
#define CIR_BDHR(b) (b + 6)
#define CIR_IIR(b) (b + 7)
/* Default Base address of Game port */
#define GP_BASE_DEFAULT 0x0201
/* wdt_status */
#define WDTS_TIMER_RUN 0
#define WDTS_DEV_OPEN 1
#define WDTS_KEEPALIVE 2
#define WDTS_LOCKED 3
#define WDTS_USE_GP 4
#define WDTS_EXPECTED 5
#define WDTS_USE_CIR 6
static unsigned int base, gpact, ciract, max_units, chip_type;
static unsigned long wdt_status;
static int nogameport = DEFAULT_NOGAMEPORT;
static int nocir = DEFAULT_NOCIR;
static int exclusive = DEFAULT_EXCLUSIVE;
static int timeout = DEFAULT_TIMEOUT;
static int testmode = DEFAULT_TESTMODE;
static bool nowayout = DEFAULT_NOWAYOUT;
module_param(nogameport, int, 0);
MODULE_PARM_DESC(nogameport, "Forbid the activation of game port, default="
__MODULE_STRING(DEFAULT_NOGAMEPORT));
module_param(nocir, int, 0);
MODULE_PARM_DESC(nocir, "Forbid the use of Consumer IR interrupts to reset timer, default="
__MODULE_STRING(DEFAULT_NOCIR));
module_param(exclusive, int, 0);
MODULE_PARM_DESC(exclusive, "Watchdog exclusive device open, default="
__MODULE_STRING(DEFAULT_EXCLUSIVE));
module_param(timeout, int, 0);
MODULE_PARM_DESC(timeout, "Watchdog timeout in seconds, default="
__MODULE_STRING(DEFAULT_TIMEOUT));
module_param(testmode, int, 0);
MODULE_PARM_DESC(testmode, "Watchdog test mode (1 = no reboot), default="
__MODULE_STRING(DEFAULT_TESTMODE));
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started, default="
__MODULE_STRING(WATCHDOG_NOWAYOUT));
/* Superio Chip */
static inline int superio_enter(void)
{
/*
* Try to reserve REG and REG + 1 for exclusive access.
*/
if (!request_muxed_region(REG, 2, WATCHDOG_NAME))
return -EBUSY;
outb(0x87, REG);
outb(0x01, REG);
outb(0x55, REG);
outb(0x55, REG);
return 0;
}
static inline void superio_exit(void)
{
outb(0x02, REG);
outb(0x02, VAL);
release_region(REG, 2);
}
static inline void superio_select(int ldn)
{
outb(LDNREG, REG);
outb(ldn, VAL);
}
static inline int superio_inb(int reg)
{
outb(reg, REG);
return inb(VAL);
}
static inline void superio_outb(int val, int reg)
{
outb(reg, REG);
outb(val, VAL);
}
static inline int superio_inw(int reg)
{
int val;
outb(reg++, REG);
val = inb(VAL) << 8;
outb(reg, REG);
val |= inb(VAL);
return val;
}
static inline void superio_outw(int val, int reg)
{
outb(reg++, REG);
outb(val >> 8, VAL);
outb(reg, REG);
outb(val, VAL);
}
/* Internal function, should be called after superio_select(GPIO) */
static void wdt_update_timeout(void)
{
unsigned char cfg = WDT_KRST;
int tm = timeout;
if (testmode)
cfg = 0;
if (tm <= max_units)
cfg |= WDT_TOV1;
else
tm /= 60;
if (chip_type != IT8721_ID)
cfg |= WDT_PWROK;
superio_outb(cfg, WDTCFG);
superio_outb(tm, WDTVALLSB);
if (max_units > 255)
superio_outb(tm>>8, WDTVALMSB);
}
static int wdt_round_time(int t)
{
t += 59;
t -= t % 60;
return t;
}
/* watchdog timer handling */
static void wdt_keepalive(void)
{
if (test_bit(WDTS_USE_GP, &wdt_status))
inb(base);
else if (test_bit(WDTS_USE_CIR, &wdt_status))
/* The timer reloads with around 5 msec delay */
outb(0x55, CIR_DR(base));
else {
if (superio_enter())
return;
superio_select(GPIO);
wdt_update_timeout();
superio_exit();
}
set_bit(WDTS_KEEPALIVE, &wdt_status);
}
static int wdt_start(void)
{
int ret = superio_enter();
if (ret)
return ret;
superio_select(GPIO);
if (test_bit(WDTS_USE_GP, &wdt_status))
superio_outb(WDT_GAMEPORT, WDTCTRL);
else if (test_bit(WDTS_USE_CIR, &wdt_status))
superio_outb(WDT_CIRINT, WDTCTRL);
wdt_update_timeout();
superio_exit();
return 0;
}
static int wdt_stop(void)
{
int ret = superio_enter();
if (ret)
return ret;
superio_select(GPIO);
superio_outb(0x00, WDTCTRL);
superio_outb(WDT_TOV1, WDTCFG);
superio_outb(0x00, WDTVALLSB);
if (max_units > 255)
superio_outb(0x00, WDTVALMSB);
superio_exit();
return 0;
}
/**
* wdt_set_timeout - set a new timeout value with watchdog ioctl
* @t: timeout value in seconds
*
* The hardware device has a 8 or 16 bit watchdog timer (depends on
* chip version) that can be configured to count seconds or minutes.
*
* Used within WDIOC_SETTIMEOUT watchdog device ioctl.
*/
static int wdt_set_timeout(int t)
{
if (t < 1 || t > max_units * 60)
return -EINVAL;
if (t > max_units)
timeout = wdt_round_time(t);
else
timeout = t;
if (test_bit(WDTS_TIMER_RUN, &wdt_status)) {
int ret = superio_enter();
if (ret)
return ret;
superio_select(GPIO);
wdt_update_timeout();
superio_exit();
}
return 0;
}
/**
* wdt_get_status - determines the status supported by watchdog ioctl
* @status: status returned to user space
*
* The status bit of the device does not allow to distinguish
* between a regular system reset and a watchdog forced reset.
* But, in test mode it is useful, so it is supported through
* WDIOC_GETSTATUS watchdog ioctl. Additionally the driver
* reports the keepalive signal and the acception of the magic.
*
* Used within WDIOC_GETSTATUS watchdog device ioctl.
*/
static int wdt_get_status(int *status)
{
*status = 0;
if (testmode) {
int ret = superio_enter();
if (ret)
return ret;
superio_select(GPIO);
if (superio_inb(WDTCTRL) & WDT_ZERO) {
superio_outb(0x00, WDTCTRL);
clear_bit(WDTS_TIMER_RUN, &wdt_status);
*status |= WDIOF_CARDRESET;
}
superio_exit();
}
if (test_and_clear_bit(WDTS_KEEPALIVE, &wdt_status))
*status |= WDIOF_KEEPALIVEPING;
if (test_bit(WDTS_EXPECTED, &wdt_status))
*status |= WDIOF_MAGICCLOSE;
return 0;
}
/* /dev/watchdog handling */
/**
* wdt_open - watchdog file_operations .open
* @inode: inode of the device
* @file: file handle to the device
*
* The watchdog timer starts by opening the device.
*
* Used within the file operation of the watchdog device.
*/
static int wdt_open(struct inode *inode, struct file *file)
{
if (exclusive && test_and_set_bit(WDTS_DEV_OPEN, &wdt_status))
return -EBUSY;
if (!test_and_set_bit(WDTS_TIMER_RUN, &wdt_status)) {
int ret;
if (nowayout && !test_and_set_bit(WDTS_LOCKED, &wdt_status))
__module_get(THIS_MODULE);
ret = wdt_start();
if (ret) {
clear_bit(WDTS_LOCKED, &wdt_status);
clear_bit(WDTS_TIMER_RUN, &wdt_status);
clear_bit(WDTS_DEV_OPEN, &wdt_status);
return ret;
}
}
return nonseekable_open(inode, file);
}
/**
* wdt_release - watchdog file_operations .release
* @inode: inode of the device
* @file: file handle to the device
*
* Closing the watchdog device either stops the watchdog timer
* or in the case, that nowayout is set or the magic character
* wasn't written, a critical warning about an running watchdog
* timer is given.
*
* Used within the file operation of the watchdog device.
*/
static int wdt_release(struct inode *inode, struct file *file)
{
if (test_bit(WDTS_TIMER_RUN, &wdt_status)) {
if (test_and_clear_bit(WDTS_EXPECTED, &wdt_status)) {
int ret = wdt_stop();
if (ret) {
/*
* Stop failed. Just keep the watchdog alive
* and hope nothing bad happens.
*/
set_bit(WDTS_EXPECTED, &wdt_status);
wdt_keepalive();
return ret;
}
clear_bit(WDTS_TIMER_RUN, &wdt_status);
} else {
wdt_keepalive();
pr_crit("unexpected close, not stopping watchdog!\n");
}
}
clear_bit(WDTS_DEV_OPEN, &wdt_status);
return 0;
}
/**
* wdt_write - watchdog file_operations .write
* @file: file handle to the watchdog
* @buf: buffer to write
* @count: count of bytes
* @ppos: pointer to the position to write. No seeks allowed
*
* A write to a watchdog device is defined as a keepalive signal. Any
* write of data will do, as we don't define content meaning.
*
* Used within the file operation of the watchdog device.
*/
static ssize_t wdt_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
if (count) {
clear_bit(WDTS_EXPECTED, &wdt_status);
wdt_keepalive();
}
if (!nowayout) {
size_t ofs;
/* note: just in case someone wrote the magic character long ago */
for (ofs = 0; ofs != count; ofs++) {
char c;
if (get_user(c, buf + ofs))
return -EFAULT;
if (c == WD_MAGIC)
set_bit(WDTS_EXPECTED, &wdt_status);
}
}
return count;
}
static const struct watchdog_info ident = {
.options = WDIOF_SETTIMEOUT | WDIOF_MAGICCLOSE | WDIOF_KEEPALIVEPING,
.firmware_version = 1,
.identity = WATCHDOG_NAME,
};
/**
* wdt_ioctl - watchdog file_operations .unlocked_ioctl
* @file: file handle to the device
* @cmd: watchdog command
* @arg: argument pointer
*
* The watchdog API defines a common set of functions for all watchdogs
* according to their available features.
*
* Used within the file operation of the watchdog device.
*/
static long wdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int rc = 0, status, new_options, new_timeout;
union {
struct watchdog_info __user *ident;
int __user *i;
} uarg;
uarg.i = (int __user *)arg;
switch (cmd) {
case WDIOC_GETSUPPORT:
return copy_to_user(uarg.ident,
&ident, sizeof(ident)) ? -EFAULT : 0;
case WDIOC_GETSTATUS:
rc = wdt_get_status(&status);
if (rc)
return rc;
return put_user(status, uarg.i);
case WDIOC_GETBOOTSTATUS:
return put_user(0, uarg.i);
case WDIOC_KEEPALIVE:
wdt_keepalive();
return 0;
case WDIOC_SETOPTIONS:
if (get_user(new_options, uarg.i))
return -EFAULT;
switch (new_options) {
case WDIOS_DISABLECARD:
if (test_bit(WDTS_TIMER_RUN, &wdt_status)) {
rc = wdt_stop();
if (rc)
return rc;
}
clear_bit(WDTS_TIMER_RUN, &wdt_status);
return 0;
case WDIOS_ENABLECARD:
if (!test_and_set_bit(WDTS_TIMER_RUN, &wdt_status)) {
rc = wdt_start();
if (rc) {
clear_bit(WDTS_TIMER_RUN, &wdt_status);
return rc;
}
}
return 0;
default:
return -EFAULT;
}
case WDIOC_SETTIMEOUT:
if (get_user(new_timeout, uarg.i))
return -EFAULT;
rc = wdt_set_timeout(new_timeout);
case WDIOC_GETTIMEOUT:
if (put_user(timeout, uarg.i))
return -EFAULT;
return rc;
default:
return -ENOTTY;
}
}
static int wdt_notify_sys(struct notifier_block *this, unsigned long code,
void *unused)
{
if (code == SYS_DOWN || code == SYS_HALT)
wdt_stop();
return NOTIFY_DONE;
}
static const struct file_operations wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = wdt_write,
.unlocked_ioctl = wdt_ioctl,
.open = wdt_open,
.release = wdt_release,
};
static struct miscdevice wdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &wdt_fops,
};
static struct notifier_block wdt_notifier = {
.notifier_call = wdt_notify_sys,
};
static int __init it87_wdt_init(void)
{
int rc = 0;
int try_gameport = !nogameport;
u8 chip_rev;
int gp_rreq_fail = 0;
wdt_status = 0;
rc = superio_enter();
if (rc)
return rc;
chip_type = superio_inw(CHIPID);
chip_rev = superio_inb(CHIPREV) & 0x0f;
superio_exit();
switch (chip_type) {
case IT8702_ID:
max_units = 255;
break;
case IT8712_ID:
max_units = (chip_rev < 8) ? 255 : 65535;
break;
case IT8716_ID:
case IT8726_ID:
max_units = 65535;
break;
case IT8718_ID:
case IT8720_ID:
case IT8721_ID:
case IT8728_ID:
case IT8783_ID:
max_units = 65535;
try_gameport = 0;
break;
case IT8705_ID:
pr_err("Unsupported Chip found, Chip %04x Revision %02x\n",
chip_type, chip_rev);
return -ENODEV;
case NO_DEV_ID:
pr_err("no device\n");
return -ENODEV;
default:
pr_err("Unknown Chip found, Chip %04x Revision %04x\n",
chip_type, chip_rev);
return -ENODEV;
}
rc = superio_enter();
if (rc)
return rc;
superio_select(GPIO);
superio_outb(WDT_TOV1, WDTCFG);
superio_outb(0x00, WDTCTRL);
/* First try to get Gameport support */
if (try_gameport) {
superio_select(GAMEPORT);
base = superio_inw(BASEREG);
if (!base) {
base = GP_BASE_DEFAULT;
superio_outw(base, BASEREG);
}
gpact = superio_inb(ACTREG);
superio_outb(0x01, ACTREG);
if (request_region(base, 1, WATCHDOG_NAME))
set_bit(WDTS_USE_GP, &wdt_status);
else
gp_rreq_fail = 1;
}
/* If we haven't Gameport support, try to get CIR support */
if (!nocir && !test_bit(WDTS_USE_GP, &wdt_status)) {
if (!request_region(CIR_BASE, 8, WATCHDOG_NAME)) {
if (gp_rreq_fail)
pr_err("I/O Address 0x%04x and 0x%04x already in use\n",
base, CIR_BASE);
else
pr_err("I/O Address 0x%04x already in use\n",
CIR_BASE);
rc = -EIO;
goto err_out;
}
base = CIR_BASE;
superio_select(CIR);
superio_outw(base, BASEREG);
superio_outb(0x00, CIR_ILS);
ciract = superio_inb(ACTREG);
superio_outb(0x01, ACTREG);
if (gp_rreq_fail) {
superio_select(GAMEPORT);
superio_outb(gpact, ACTREG);
}
set_bit(WDTS_USE_CIR, &wdt_status);
}
if (timeout < 1 || timeout > max_units * 60) {
timeout = DEFAULT_TIMEOUT;
pr_warn("Timeout value out of range, use default %d sec\n",
DEFAULT_TIMEOUT);
}
if (timeout > max_units)
timeout = wdt_round_time(timeout);
rc = register_reboot_notifier(&wdt_notifier);
if (rc) {
pr_err("Cannot register reboot notifier (err=%d)\n", rc);
goto err_out_region;
}
rc = misc_register(&wdt_miscdev);
if (rc) {
pr_err("Cannot register miscdev on minor=%d (err=%d)\n",
wdt_miscdev.minor, rc);
goto err_out_reboot;
}
/* Initialize CIR to use it as keepalive source */
if (test_bit(WDTS_USE_CIR, &wdt_status)) {
outb(0x00, CIR_RCR(base));
outb(0xc0, CIR_TCR1(base));
outb(0x5c, CIR_TCR2(base));
outb(0x10, CIR_IER(base));
outb(0x00, CIR_BDHR(base));
outb(0x01, CIR_BDLR(base));
outb(0x09, CIR_IER(base));
}
pr_info("Chip IT%04x revision %d initialized. timeout=%d sec (nowayout=%d testmode=%d exclusive=%d nogameport=%d nocir=%d)\n",
chip_type, chip_rev, timeout,
nowayout, testmode, exclusive, nogameport, nocir);
superio_exit();
return 0;
err_out_reboot:
unregister_reboot_notifier(&wdt_notifier);
err_out_region:
if (test_bit(WDTS_USE_GP, &wdt_status))
release_region(base, 1);
else if (test_bit(WDTS_USE_CIR, &wdt_status)) {
release_region(base, 8);
superio_select(CIR);
superio_outb(ciract, ACTREG);
}
err_out:
if (try_gameport) {
superio_select(GAMEPORT);
superio_outb(gpact, ACTREG);
}
superio_exit();
return rc;
}
static void __exit it87_wdt_exit(void)
{
if (superio_enter() == 0) {
superio_select(GPIO);
superio_outb(0x00, WDTCTRL);
superio_outb(0x00, WDTCFG);
superio_outb(0x00, WDTVALLSB);
if (max_units > 255)
superio_outb(0x00, WDTVALMSB);
if (test_bit(WDTS_USE_GP, &wdt_status)) {
superio_select(GAMEPORT);
superio_outb(gpact, ACTREG);
} else if (test_bit(WDTS_USE_CIR, &wdt_status)) {
superio_select(CIR);
superio_outb(ciract, ACTREG);
}
superio_exit();
}
misc_deregister(&wdt_miscdev);
unregister_reboot_notifier(&wdt_notifier);
if (test_bit(WDTS_USE_GP, &wdt_status))
release_region(base, 1);
else if (test_bit(WDTS_USE_CIR, &wdt_status))
release_region(base, 8);
}
module_init(it87_wdt_init);
module_exit(it87_wdt_exit);
MODULE_AUTHOR("Oliver Schuster");
MODULE_DESCRIPTION("Hardware Watchdog Device Driver for IT87xx EC-LPC I/O");
MODULE_LICENSE("GPL");
| gpl-2.0 |
bgn9000/Dragon-Shiryu | arch/sparc/kernel/setup_32.c | 2184 | 8220 | /*
* linux/arch/sparc/kernel/setup.c
*
* Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 2000 Anton Blanchard (anton@samba.org)
*/
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/initrd.h>
#include <asm/smp.h>
#include <linux/user.h>
#include <linux/screen_info.h>
#include <linux/delay.h>
#include <linux/fs.h>
#include <linux/seq_file.h>
#include <linux/syscalls.h>
#include <linux/kdev_t.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/console.h>
#include <linux/spinlock.h>
#include <linux/root_dev.h>
#include <linux/cpu.h>
#include <linux/kdebug.h>
#include <asm/system.h>
#include <asm/io.h>
#include <asm/processor.h>
#include <asm/oplib.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/traps.h>
#include <asm/vaddrs.h>
#include <asm/mbus.h>
#include <asm/idprom.h>
#include <asm/machines.h>
#include <asm/cpudata.h>
#include <asm/setup.h>
#include "kernel.h"
struct screen_info screen_info = {
0, 0, /* orig-x, orig-y */
0, /* unused */
0, /* orig-video-page */
0, /* orig-video-mode */
128, /* orig-video-cols */
0,0,0, /* ega_ax, ega_bx, ega_cx */
54, /* orig-video-lines */
0, /* orig-video-isVGA */
16 /* orig-video-points */
};
/* Typing sync at the prom prompt calls the function pointed to by
* romvec->pv_synchook which I set to the following function.
* This should sync all filesystems and return, for now it just
* prints out pretty messages and returns.
*/
extern unsigned long trapbase;
/* Pretty sick eh? */
static void prom_sync_me(void)
{
unsigned long prom_tbr, flags;
/* XXX Badly broken. FIX! - Anton */
local_irq_save(flags);
__asm__ __volatile__("rd %%tbr, %0\n\t" : "=r" (prom_tbr));
__asm__ __volatile__("wr %0, 0x0, %%tbr\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t" : : "r" (&trapbase));
prom_printf("PROM SYNC COMMAND...\n");
show_free_areas(0);
if(current->pid != 0) {
local_irq_enable();
sys_sync();
local_irq_disable();
}
prom_printf("Returning to prom\n");
__asm__ __volatile__("wr %0, 0x0, %%tbr\n\t"
"nop\n\t"
"nop\n\t"
"nop\n\t" : : "r" (prom_tbr));
local_irq_restore(flags);
}
static unsigned int boot_flags __initdata = 0;
#define BOOTME_DEBUG 0x1
/* Exported for mm/init.c:paging_init. */
unsigned long cmdline_memory_size __initdata = 0;
/* which CPU booted us (0xff = not set) */
unsigned char boot_cpu_id = 0xff; /* 0xff will make it into DATA section... */
unsigned char boot_cpu_id4; /* boot_cpu_id << 2 */
static void
prom_console_write(struct console *con, const char *s, unsigned n)
{
prom_write(s, n);
}
static struct console prom_early_console = {
.name = "earlyprom",
.write = prom_console_write,
.flags = CON_PRINTBUFFER | CON_BOOT,
.index = -1,
};
/*
* Process kernel command line switches that are specific to the
* SPARC or that require special low-level processing.
*/
static void __init process_switch(char c)
{
switch (c) {
case 'd':
boot_flags |= BOOTME_DEBUG;
break;
case 's':
break;
case 'h':
prom_printf("boot_flags_init: Halt!\n");
prom_halt();
break;
case 'p':
/* Just ignore, this behavior is now the default. */
break;
default:
printk("Unknown boot switch (-%c)\n", c);
break;
}
}
static void __init boot_flags_init(char *commands)
{
while (*commands) {
/* Move to the start of the next "argument". */
while (*commands && *commands == ' ')
commands++;
/* Process any command switches, otherwise skip it. */
if (*commands == '\0')
break;
if (*commands == '-') {
commands++;
while (*commands && *commands != ' ')
process_switch(*commands++);
continue;
}
if (!strncmp(commands, "mem=", 4)) {
/*
* "mem=XXX[kKmM] overrides the PROM-reported
* memory size.
*/
cmdline_memory_size = simple_strtoul(commands + 4,
&commands, 0);
if (*commands == 'K' || *commands == 'k') {
cmdline_memory_size <<= 10;
commands++;
} else if (*commands=='M' || *commands=='m') {
cmdline_memory_size <<= 20;
commands++;
}
}
while (*commands && *commands != ' ')
commands++;
}
}
/* This routine will in the future do all the nasty prom stuff
* to probe for the mmu type and its parameters, etc. This will
* also be where SMP things happen.
*/
extern void sun4c_probe_vac(void);
extern unsigned short root_flags;
extern unsigned short root_dev;
extern unsigned short ram_flags;
#define RAMDISK_IMAGE_START_MASK 0x07FF
#define RAMDISK_PROMPT_FLAG 0x8000
#define RAMDISK_LOAD_FLAG 0x4000
extern int root_mountflags;
char reboot_command[COMMAND_LINE_SIZE];
enum sparc_cpu sparc_cpu_model;
EXPORT_SYMBOL(sparc_cpu_model);
struct tt_entry *sparc_ttable;
struct pt_regs fake_swapper_regs;
void __init setup_arch(char **cmdline_p)
{
int i;
unsigned long highest_paddr;
sparc_ttable = (struct tt_entry *) &trapbase;
/* Initialize PROM console and command line. */
*cmdline_p = prom_getbootargs();
strcpy(boot_command_line, *cmdline_p);
parse_early_param();
boot_flags_init(*cmdline_p);
register_console(&prom_early_console);
/* Set sparc_cpu_model */
sparc_cpu_model = sun_unknown;
if (!strcmp(&cputypval[0], "sun4 "))
sparc_cpu_model = sun4;
if (!strcmp(&cputypval[0], "sun4c"))
sparc_cpu_model = sun4c;
if (!strcmp(&cputypval[0], "sun4m"))
sparc_cpu_model = sun4m;
if (!strcmp(&cputypval[0], "sun4s"))
sparc_cpu_model = sun4m; /* CP-1200 with PROM 2.30 -E */
if (!strcmp(&cputypval[0], "sun4d"))
sparc_cpu_model = sun4d;
if (!strcmp(&cputypval[0], "sun4e"))
sparc_cpu_model = sun4e;
if (!strcmp(&cputypval[0], "sun4u"))
sparc_cpu_model = sun4u;
if (!strncmp(&cputypval[0], "leon" , 4))
sparc_cpu_model = sparc_leon;
printk("ARCH: ");
switch(sparc_cpu_model) {
case sun4:
printk("SUN4\n");
break;
case sun4c:
printk("SUN4C\n");
break;
case sun4m:
printk("SUN4M\n");
break;
case sun4d:
printk("SUN4D\n");
break;
case sun4e:
printk("SUN4E\n");
break;
case sun4u:
printk("SUN4U\n");
break;
case sparc_leon:
printk("LEON\n");
break;
default:
printk("UNKNOWN!\n");
break;
}
#ifdef CONFIG_DUMMY_CONSOLE
conswitchp = &dummy_con;
#endif
idprom_init();
if (ARCH_SUN4C)
sun4c_probe_vac();
load_mmu();
phys_base = 0xffffffffUL;
highest_paddr = 0UL;
for (i = 0; sp_banks[i].num_bytes != 0; i++) {
unsigned long top;
if (sp_banks[i].base_addr < phys_base)
phys_base = sp_banks[i].base_addr;
top = sp_banks[i].base_addr +
sp_banks[i].num_bytes;
if (highest_paddr < top)
highest_paddr = top;
}
pfn_base = phys_base >> PAGE_SHIFT;
if (!root_flags)
root_mountflags &= ~MS_RDONLY;
ROOT_DEV = old_decode_dev(root_dev);
#ifdef CONFIG_BLK_DEV_RAM
rd_image_start = ram_flags & RAMDISK_IMAGE_START_MASK;
rd_prompt = ((ram_flags & RAMDISK_PROMPT_FLAG) != 0);
rd_doload = ((ram_flags & RAMDISK_LOAD_FLAG) != 0);
#endif
prom_setsync(prom_sync_me);
if((boot_flags&BOOTME_DEBUG) && (linux_dbvec!=0) &&
((*(short *)linux_dbvec) != -1)) {
printk("Booted under KADB. Syncing trap table.\n");
(*(linux_dbvec->teach_debugger))();
}
init_mm.context = (unsigned long) NO_CONTEXT;
init_task.thread.kregs = &fake_swapper_regs;
paging_init();
smp_setup_cpu_possible_map();
}
extern int stop_a_enabled;
void sun_do_break(void)
{
if (!stop_a_enabled)
return;
printk("\n");
flush_user_windows();
prom_cmdline();
}
EXPORT_SYMBOL(sun_do_break);
int stop_a_enabled = 1;
static int __init topology_init(void)
{
int i, ncpus, err;
/* Count the number of physically present processors in
* the machine, even on uniprocessor, so that /proc/cpuinfo
* output is consistent with 2.4.x
*/
ncpus = 0;
while (!cpu_find_by_instance(ncpus, NULL, NULL))
ncpus++;
ncpus_probed = ncpus;
err = 0;
for_each_online_cpu(i) {
struct cpu *p = kzalloc(sizeof(*p), GFP_KERNEL);
if (!p)
err = -ENOMEM;
else
register_cpu(p, i);
}
return err;
}
subsys_initcall(topology_init);
| gpl-2.0 |
davidmueller13/L900_3.4_Experiment | net/netfilter/ipvs/ip_vs_conn.c | 5000 | 33748 | /*
* IPVS An implementation of the IP virtual server support for the
* LINUX operating system. IPVS is now implemented as a module
* over the Netfilter framework. IPVS can be used to build a
* high-performance and highly available server based on a
* cluster of servers.
*
* Authors: Wensong Zhang <wensong@linuxvirtualserver.org>
* Peter Kese <peter.kese@ijs.si>
* Julian Anastasov <ja@ssi.bg>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* The IPVS code for kernel 2.2 was done by Wensong Zhang and Peter Kese,
* with changes/fixes from Julian Anastasov, Lars Marowsky-Bree, Horms
* and others. Many code here is taken from IP MASQ code of kernel 2.2.
*
* Changes:
*
*/
#define KMSG_COMPONENT "IPVS"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/interrupt.h>
#include <linux/in.h>
#include <linux/net.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/proc_fs.h> /* for proc_net_* */
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/jhash.h>
#include <linux/random.h>
#include <net/net_namespace.h>
#include <net/ip_vs.h>
#ifndef CONFIG_IP_VS_TAB_BITS
#define CONFIG_IP_VS_TAB_BITS 12
#endif
/*
* Connection hash size. Default is what was selected at compile time.
*/
static int ip_vs_conn_tab_bits = CONFIG_IP_VS_TAB_BITS;
module_param_named(conn_tab_bits, ip_vs_conn_tab_bits, int, 0444);
MODULE_PARM_DESC(conn_tab_bits, "Set connections' hash size");
/* size and mask values */
int ip_vs_conn_tab_size __read_mostly;
static int ip_vs_conn_tab_mask __read_mostly;
/*
* Connection hash table: for input and output packets lookups of IPVS
*/
static struct hlist_head *ip_vs_conn_tab __read_mostly;
/* SLAB cache for IPVS connections */
static struct kmem_cache *ip_vs_conn_cachep __read_mostly;
/* counter for no client port connections */
static atomic_t ip_vs_conn_no_cport_cnt = ATOMIC_INIT(0);
/* random value for IPVS connection hash */
static unsigned int ip_vs_conn_rnd __read_mostly;
/*
* Fine locking granularity for big connection hash table
*/
#define CT_LOCKARRAY_BITS 5
#define CT_LOCKARRAY_SIZE (1<<CT_LOCKARRAY_BITS)
#define CT_LOCKARRAY_MASK (CT_LOCKARRAY_SIZE-1)
struct ip_vs_aligned_lock
{
rwlock_t l;
} __attribute__((__aligned__(SMP_CACHE_BYTES)));
/* lock array for conn table */
static struct ip_vs_aligned_lock
__ip_vs_conntbl_lock_array[CT_LOCKARRAY_SIZE] __cacheline_aligned;
static inline void ct_read_lock(unsigned key)
{
read_lock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_read_unlock(unsigned key)
{
read_unlock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_write_lock(unsigned key)
{
write_lock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_write_unlock(unsigned key)
{
write_unlock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_read_lock_bh(unsigned key)
{
read_lock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_read_unlock_bh(unsigned key)
{
read_unlock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_write_lock_bh(unsigned key)
{
write_lock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_write_unlock_bh(unsigned key)
{
write_unlock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
/*
* Returns hash value for IPVS connection entry
*/
static unsigned int ip_vs_conn_hashkey(struct net *net, int af, unsigned proto,
const union nf_inet_addr *addr,
__be16 port)
{
#ifdef CONFIG_IP_VS_IPV6
if (af == AF_INET6)
return (jhash_3words(jhash(addr, 16, ip_vs_conn_rnd),
(__force u32)port, proto, ip_vs_conn_rnd) ^
((size_t)net>>8)) & ip_vs_conn_tab_mask;
#endif
return (jhash_3words((__force u32)addr->ip, (__force u32)port, proto,
ip_vs_conn_rnd) ^
((size_t)net>>8)) & ip_vs_conn_tab_mask;
}
static unsigned int ip_vs_conn_hashkey_param(const struct ip_vs_conn_param *p,
bool inverse)
{
const union nf_inet_addr *addr;
__be16 port;
if (p->pe_data && p->pe->hashkey_raw)
return p->pe->hashkey_raw(p, ip_vs_conn_rnd, inverse) &
ip_vs_conn_tab_mask;
if (likely(!inverse)) {
addr = p->caddr;
port = p->cport;
} else {
addr = p->vaddr;
port = p->vport;
}
return ip_vs_conn_hashkey(p->net, p->af, p->protocol, addr, port);
}
static unsigned int ip_vs_conn_hashkey_conn(const struct ip_vs_conn *cp)
{
struct ip_vs_conn_param p;
ip_vs_conn_fill_param(ip_vs_conn_net(cp), cp->af, cp->protocol,
&cp->caddr, cp->cport, NULL, 0, &p);
if (cp->pe) {
p.pe = cp->pe;
p.pe_data = cp->pe_data;
p.pe_data_len = cp->pe_data_len;
}
return ip_vs_conn_hashkey_param(&p, false);
}
/*
* Hashes ip_vs_conn in ip_vs_conn_tab by netns,proto,addr,port.
* returns bool success.
*/
static inline int ip_vs_conn_hash(struct ip_vs_conn *cp)
{
unsigned hash;
int ret;
if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
return 0;
/* Hash by protocol, client address and port */
hash = ip_vs_conn_hashkey_conn(cp);
ct_write_lock(hash);
spin_lock(&cp->lock);
if (!(cp->flags & IP_VS_CONN_F_HASHED)) {
hlist_add_head(&cp->c_list, &ip_vs_conn_tab[hash]);
cp->flags |= IP_VS_CONN_F_HASHED;
atomic_inc(&cp->refcnt);
ret = 1;
} else {
pr_err("%s(): request for already hashed, called from %pF\n",
__func__, __builtin_return_address(0));
ret = 0;
}
spin_unlock(&cp->lock);
ct_write_unlock(hash);
return ret;
}
/*
* UNhashes ip_vs_conn from ip_vs_conn_tab.
* returns bool success.
*/
static inline int ip_vs_conn_unhash(struct ip_vs_conn *cp)
{
unsigned hash;
int ret;
/* unhash it and decrease its reference counter */
hash = ip_vs_conn_hashkey_conn(cp);
ct_write_lock(hash);
spin_lock(&cp->lock);
if (cp->flags & IP_VS_CONN_F_HASHED) {
hlist_del(&cp->c_list);
cp->flags &= ~IP_VS_CONN_F_HASHED;
atomic_dec(&cp->refcnt);
ret = 1;
} else
ret = 0;
spin_unlock(&cp->lock);
ct_write_unlock(hash);
return ret;
}
/*
* Gets ip_vs_conn associated with supplied parameters in the ip_vs_conn_tab.
* Called for pkts coming from OUTside-to-INside.
* p->caddr, p->cport: pkt source address (foreign host)
* p->vaddr, p->vport: pkt dest address (load balancer)
*/
static inline struct ip_vs_conn *
__ip_vs_conn_in_get(const struct ip_vs_conn_param *p)
{
unsigned hash;
struct ip_vs_conn *cp;
struct hlist_node *n;
hash = ip_vs_conn_hashkey_param(p, false);
ct_read_lock(hash);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[hash], c_list) {
if (cp->af == p->af &&
p->cport == cp->cport && p->vport == cp->vport &&
ip_vs_addr_equal(p->af, p->caddr, &cp->caddr) &&
ip_vs_addr_equal(p->af, p->vaddr, &cp->vaddr) &&
((!p->cport) ^ (!(cp->flags & IP_VS_CONN_F_NO_CPORT))) &&
p->protocol == cp->protocol &&
ip_vs_conn_net_eq(cp, p->net)) {
/* HIT */
atomic_inc(&cp->refcnt);
ct_read_unlock(hash);
return cp;
}
}
ct_read_unlock(hash);
return NULL;
}
struct ip_vs_conn *ip_vs_conn_in_get(const struct ip_vs_conn_param *p)
{
struct ip_vs_conn *cp;
cp = __ip_vs_conn_in_get(p);
if (!cp && atomic_read(&ip_vs_conn_no_cport_cnt)) {
struct ip_vs_conn_param cport_zero_p = *p;
cport_zero_p.cport = 0;
cp = __ip_vs_conn_in_get(&cport_zero_p);
}
IP_VS_DBG_BUF(9, "lookup/in %s %s:%d->%s:%d %s\n",
ip_vs_proto_name(p->protocol),
IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport),
cp ? "hit" : "not hit");
return cp;
}
static int
ip_vs_conn_fill_param_proto(int af, const struct sk_buff *skb,
const struct ip_vs_iphdr *iph,
unsigned int proto_off, int inverse,
struct ip_vs_conn_param *p)
{
__be16 _ports[2], *pptr;
struct net *net = skb_net(skb);
pptr = skb_header_pointer(skb, proto_off, sizeof(_ports), _ports);
if (pptr == NULL)
return 1;
if (likely(!inverse))
ip_vs_conn_fill_param(net, af, iph->protocol, &iph->saddr,
pptr[0], &iph->daddr, pptr[1], p);
else
ip_vs_conn_fill_param(net, af, iph->protocol, &iph->daddr,
pptr[1], &iph->saddr, pptr[0], p);
return 0;
}
struct ip_vs_conn *
ip_vs_conn_in_get_proto(int af, const struct sk_buff *skb,
const struct ip_vs_iphdr *iph,
unsigned int proto_off, int inverse)
{
struct ip_vs_conn_param p;
if (ip_vs_conn_fill_param_proto(af, skb, iph, proto_off, inverse, &p))
return NULL;
return ip_vs_conn_in_get(&p);
}
EXPORT_SYMBOL_GPL(ip_vs_conn_in_get_proto);
/* Get reference to connection template */
struct ip_vs_conn *ip_vs_ct_in_get(const struct ip_vs_conn_param *p)
{
unsigned hash;
struct ip_vs_conn *cp;
struct hlist_node *n;
hash = ip_vs_conn_hashkey_param(p, false);
ct_read_lock(hash);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[hash], c_list) {
if (!ip_vs_conn_net_eq(cp, p->net))
continue;
if (p->pe_data && p->pe->ct_match) {
if (p->pe == cp->pe && p->pe->ct_match(p, cp))
goto out;
continue;
}
if (cp->af == p->af &&
ip_vs_addr_equal(p->af, p->caddr, &cp->caddr) &&
/* protocol should only be IPPROTO_IP if
* p->vaddr is a fwmark */
ip_vs_addr_equal(p->protocol == IPPROTO_IP ? AF_UNSPEC :
p->af, p->vaddr, &cp->vaddr) &&
p->cport == cp->cport && p->vport == cp->vport &&
cp->flags & IP_VS_CONN_F_TEMPLATE &&
p->protocol == cp->protocol)
goto out;
}
cp = NULL;
out:
if (cp)
atomic_inc(&cp->refcnt);
ct_read_unlock(hash);
IP_VS_DBG_BUF(9, "template lookup/in %s %s:%d->%s:%d %s\n",
ip_vs_proto_name(p->protocol),
IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport),
cp ? "hit" : "not hit");
return cp;
}
/* Gets ip_vs_conn associated with supplied parameters in the ip_vs_conn_tab.
* Called for pkts coming from inside-to-OUTside.
* p->caddr, p->cport: pkt source address (inside host)
* p->vaddr, p->vport: pkt dest address (foreign host) */
struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p)
{
unsigned hash;
struct ip_vs_conn *cp, *ret=NULL;
struct hlist_node *n;
/*
* Check for "full" addressed entries
*/
hash = ip_vs_conn_hashkey_param(p, true);
ct_read_lock(hash);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[hash], c_list) {
if (cp->af == p->af &&
p->vport == cp->cport && p->cport == cp->dport &&
ip_vs_addr_equal(p->af, p->vaddr, &cp->caddr) &&
ip_vs_addr_equal(p->af, p->caddr, &cp->daddr) &&
p->protocol == cp->protocol &&
ip_vs_conn_net_eq(cp, p->net)) {
/* HIT */
atomic_inc(&cp->refcnt);
ret = cp;
break;
}
}
ct_read_unlock(hash);
IP_VS_DBG_BUF(9, "lookup/out %s %s:%d->%s:%d %s\n",
ip_vs_proto_name(p->protocol),
IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport),
ret ? "hit" : "not hit");
return ret;
}
struct ip_vs_conn *
ip_vs_conn_out_get_proto(int af, const struct sk_buff *skb,
const struct ip_vs_iphdr *iph,
unsigned int proto_off, int inverse)
{
struct ip_vs_conn_param p;
if (ip_vs_conn_fill_param_proto(af, skb, iph, proto_off, inverse, &p))
return NULL;
return ip_vs_conn_out_get(&p);
}
EXPORT_SYMBOL_GPL(ip_vs_conn_out_get_proto);
/*
* Put back the conn and restart its timer with its timeout
*/
void ip_vs_conn_put(struct ip_vs_conn *cp)
{
unsigned long t = (cp->flags & IP_VS_CONN_F_ONE_PACKET) ?
0 : cp->timeout;
mod_timer(&cp->timer, jiffies+t);
__ip_vs_conn_put(cp);
}
/*
* Fill a no_client_port connection with a client port number
*/
void ip_vs_conn_fill_cport(struct ip_vs_conn *cp, __be16 cport)
{
if (ip_vs_conn_unhash(cp)) {
spin_lock(&cp->lock);
if (cp->flags & IP_VS_CONN_F_NO_CPORT) {
atomic_dec(&ip_vs_conn_no_cport_cnt);
cp->flags &= ~IP_VS_CONN_F_NO_CPORT;
cp->cport = cport;
}
spin_unlock(&cp->lock);
/* hash on new dport */
ip_vs_conn_hash(cp);
}
}
/*
* Bind a connection entry with the corresponding packet_xmit.
* Called by ip_vs_conn_new.
*/
static inline void ip_vs_bind_xmit(struct ip_vs_conn *cp)
{
switch (IP_VS_FWD_METHOD(cp)) {
case IP_VS_CONN_F_MASQ:
cp->packet_xmit = ip_vs_nat_xmit;
break;
case IP_VS_CONN_F_TUNNEL:
cp->packet_xmit = ip_vs_tunnel_xmit;
break;
case IP_VS_CONN_F_DROUTE:
cp->packet_xmit = ip_vs_dr_xmit;
break;
case IP_VS_CONN_F_LOCALNODE:
cp->packet_xmit = ip_vs_null_xmit;
break;
case IP_VS_CONN_F_BYPASS:
cp->packet_xmit = ip_vs_bypass_xmit;
break;
}
}
#ifdef CONFIG_IP_VS_IPV6
static inline void ip_vs_bind_xmit_v6(struct ip_vs_conn *cp)
{
switch (IP_VS_FWD_METHOD(cp)) {
case IP_VS_CONN_F_MASQ:
cp->packet_xmit = ip_vs_nat_xmit_v6;
break;
case IP_VS_CONN_F_TUNNEL:
cp->packet_xmit = ip_vs_tunnel_xmit_v6;
break;
case IP_VS_CONN_F_DROUTE:
cp->packet_xmit = ip_vs_dr_xmit_v6;
break;
case IP_VS_CONN_F_LOCALNODE:
cp->packet_xmit = ip_vs_null_xmit;
break;
case IP_VS_CONN_F_BYPASS:
cp->packet_xmit = ip_vs_bypass_xmit_v6;
break;
}
}
#endif
static inline int ip_vs_dest_totalconns(struct ip_vs_dest *dest)
{
return atomic_read(&dest->activeconns)
+ atomic_read(&dest->inactconns);
}
/*
* Bind a connection entry with a virtual service destination
* Called just after a new connection entry is created.
*/
static inline void
ip_vs_bind_dest(struct ip_vs_conn *cp, struct ip_vs_dest *dest)
{
unsigned int conn_flags;
/* if dest is NULL, then return directly */
if (!dest)
return;
/* Increase the refcnt counter of the dest */
atomic_inc(&dest->refcnt);
conn_flags = atomic_read(&dest->conn_flags);
if (cp->protocol != IPPROTO_UDP)
conn_flags &= ~IP_VS_CONN_F_ONE_PACKET;
/* Bind with the destination and its corresponding transmitter */
if (cp->flags & IP_VS_CONN_F_SYNC) {
/* if the connection is not template and is created
* by sync, preserve the activity flag.
*/
if (!(cp->flags & IP_VS_CONN_F_TEMPLATE))
conn_flags &= ~IP_VS_CONN_F_INACTIVE;
/* connections inherit forwarding method from dest */
cp->flags &= ~IP_VS_CONN_F_FWD_MASK;
}
cp->flags |= conn_flags;
cp->dest = dest;
IP_VS_DBG_BUF(7, "Bind-dest %s c:%s:%d v:%s:%d "
"d:%s:%d fwd:%c s:%u conn->flags:%X conn->refcnt:%d "
"dest->refcnt:%d\n",
ip_vs_proto_name(cp->protocol),
IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport),
IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport),
IP_VS_DBG_ADDR(cp->af, &cp->daddr), ntohs(cp->dport),
ip_vs_fwd_tag(cp), cp->state,
cp->flags, atomic_read(&cp->refcnt),
atomic_read(&dest->refcnt));
/* Update the connection counters */
if (!(cp->flags & IP_VS_CONN_F_TEMPLATE)) {
/* It is a normal connection, so increase the inactive
connection counter because it is in TCP SYNRECV
state (inactive) or other protocol inacive state */
if ((cp->flags & IP_VS_CONN_F_SYNC) &&
(!(cp->flags & IP_VS_CONN_F_INACTIVE)))
atomic_inc(&dest->activeconns);
else
atomic_inc(&dest->inactconns);
} else {
/* It is a persistent connection/template, so increase
the persistent connection counter */
atomic_inc(&dest->persistconns);
}
if (dest->u_threshold != 0 &&
ip_vs_dest_totalconns(dest) >= dest->u_threshold)
dest->flags |= IP_VS_DEST_F_OVERLOAD;
}
/*
* Check if there is a destination for the connection, if so
* bind the connection to the destination.
*/
struct ip_vs_dest *ip_vs_try_bind_dest(struct ip_vs_conn *cp)
{
struct ip_vs_dest *dest;
if ((cp) && (!cp->dest)) {
dest = ip_vs_find_dest(ip_vs_conn_net(cp), cp->af, &cp->daddr,
cp->dport, &cp->vaddr, cp->vport,
cp->protocol, cp->fwmark, cp->flags);
ip_vs_bind_dest(cp, dest);
return dest;
} else
return NULL;
}
/*
* Unbind a connection entry with its VS destination
* Called by the ip_vs_conn_expire function.
*/
static inline void ip_vs_unbind_dest(struct ip_vs_conn *cp)
{
struct ip_vs_dest *dest = cp->dest;
if (!dest)
return;
IP_VS_DBG_BUF(7, "Unbind-dest %s c:%s:%d v:%s:%d "
"d:%s:%d fwd:%c s:%u conn->flags:%X conn->refcnt:%d "
"dest->refcnt:%d\n",
ip_vs_proto_name(cp->protocol),
IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport),
IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport),
IP_VS_DBG_ADDR(cp->af, &cp->daddr), ntohs(cp->dport),
ip_vs_fwd_tag(cp), cp->state,
cp->flags, atomic_read(&cp->refcnt),
atomic_read(&dest->refcnt));
/* Update the connection counters */
if (!(cp->flags & IP_VS_CONN_F_TEMPLATE)) {
/* It is a normal connection, so decrease the inactconns
or activeconns counter */
if (cp->flags & IP_VS_CONN_F_INACTIVE) {
atomic_dec(&dest->inactconns);
} else {
atomic_dec(&dest->activeconns);
}
} else {
/* It is a persistent connection/template, so decrease
the persistent connection counter */
atomic_dec(&dest->persistconns);
}
if (dest->l_threshold != 0) {
if (ip_vs_dest_totalconns(dest) < dest->l_threshold)
dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
} else if (dest->u_threshold != 0) {
if (ip_vs_dest_totalconns(dest) * 4 < dest->u_threshold * 3)
dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
} else {
if (dest->flags & IP_VS_DEST_F_OVERLOAD)
dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
}
/*
* Simply decrease the refcnt of the dest, because the
* dest will be either in service's destination list
* or in the trash.
*/
atomic_dec(&dest->refcnt);
}
static int expire_quiescent_template(struct netns_ipvs *ipvs,
struct ip_vs_dest *dest)
{
#ifdef CONFIG_SYSCTL
return ipvs->sysctl_expire_quiescent_template &&
(atomic_read(&dest->weight) == 0);
#else
return 0;
#endif
}
/*
* Checking if the destination of a connection template is available.
* If available, return 1, otherwise invalidate this connection
* template and return 0.
*/
int ip_vs_check_template(struct ip_vs_conn *ct)
{
struct ip_vs_dest *dest = ct->dest;
struct netns_ipvs *ipvs = net_ipvs(ip_vs_conn_net(ct));
/*
* Checking the dest server status.
*/
if ((dest == NULL) ||
!(dest->flags & IP_VS_DEST_F_AVAILABLE) ||
expire_quiescent_template(ipvs, dest)) {
IP_VS_DBG_BUF(9, "check_template: dest not available for "
"protocol %s s:%s:%d v:%s:%d "
"-> d:%s:%d\n",
ip_vs_proto_name(ct->protocol),
IP_VS_DBG_ADDR(ct->af, &ct->caddr),
ntohs(ct->cport),
IP_VS_DBG_ADDR(ct->af, &ct->vaddr),
ntohs(ct->vport),
IP_VS_DBG_ADDR(ct->af, &ct->daddr),
ntohs(ct->dport));
/*
* Invalidate the connection template
*/
if (ct->vport != htons(0xffff)) {
if (ip_vs_conn_unhash(ct)) {
ct->dport = htons(0xffff);
ct->vport = htons(0xffff);
ct->cport = 0;
ip_vs_conn_hash(ct);
}
}
/*
* Simply decrease the refcnt of the template,
* don't restart its timer.
*/
atomic_dec(&ct->refcnt);
return 0;
}
return 1;
}
static void ip_vs_conn_expire(unsigned long data)
{
struct ip_vs_conn *cp = (struct ip_vs_conn *)data;
struct netns_ipvs *ipvs = net_ipvs(ip_vs_conn_net(cp));
cp->timeout = 60*HZ;
/*
* hey, I'm using it
*/
atomic_inc(&cp->refcnt);
/*
* do I control anybody?
*/
if (atomic_read(&cp->n_control))
goto expire_later;
/*
* unhash it if it is hashed in the conn table
*/
if (!ip_vs_conn_unhash(cp) && !(cp->flags & IP_VS_CONN_F_ONE_PACKET))
goto expire_later;
/*
* refcnt==1 implies I'm the only one referrer
*/
if (likely(atomic_read(&cp->refcnt) == 1)) {
/* delete the timer if it is activated by other users */
if (timer_pending(&cp->timer))
del_timer(&cp->timer);
/* does anybody control me? */
if (cp->control)
ip_vs_control_del(cp);
if (cp->flags & IP_VS_CONN_F_NFCT) {
ip_vs_conn_drop_conntrack(cp);
/* Do not access conntracks during subsys cleanup
* because nf_conntrack_find_get can not be used after
* conntrack cleanup for the net.
*/
smp_rmb();
if (ipvs->enable)
ip_vs_conn_drop_conntrack(cp);
}
ip_vs_pe_put(cp->pe);
kfree(cp->pe_data);
if (unlikely(cp->app != NULL))
ip_vs_unbind_app(cp);
ip_vs_unbind_dest(cp);
if (cp->flags & IP_VS_CONN_F_NO_CPORT)
atomic_dec(&ip_vs_conn_no_cport_cnt);
atomic_dec(&ipvs->conn_count);
kmem_cache_free(ip_vs_conn_cachep, cp);
return;
}
/* hash it back to the table */
ip_vs_conn_hash(cp);
expire_later:
IP_VS_DBG(7, "delayed: conn->refcnt-1=%d conn->n_control=%d\n",
atomic_read(&cp->refcnt)-1,
atomic_read(&cp->n_control));
ip_vs_conn_put(cp);
}
void ip_vs_conn_expire_now(struct ip_vs_conn *cp)
{
if (del_timer(&cp->timer))
mod_timer(&cp->timer, jiffies);
}
/*
* Create a new connection entry and hash it into the ip_vs_conn_tab
*/
struct ip_vs_conn *
ip_vs_conn_new(const struct ip_vs_conn_param *p,
const union nf_inet_addr *daddr, __be16 dport, unsigned flags,
struct ip_vs_dest *dest, __u32 fwmark)
{
struct ip_vs_conn *cp;
struct netns_ipvs *ipvs = net_ipvs(p->net);
struct ip_vs_proto_data *pd = ip_vs_proto_data_get(p->net,
p->protocol);
cp = kmem_cache_zalloc(ip_vs_conn_cachep, GFP_ATOMIC);
if (cp == NULL) {
IP_VS_ERR_RL("%s(): no memory\n", __func__);
return NULL;
}
INIT_HLIST_NODE(&cp->c_list);
setup_timer(&cp->timer, ip_vs_conn_expire, (unsigned long)cp);
ip_vs_conn_net_set(cp, p->net);
cp->af = p->af;
cp->protocol = p->protocol;
ip_vs_addr_copy(p->af, &cp->caddr, p->caddr);
cp->cport = p->cport;
ip_vs_addr_copy(p->af, &cp->vaddr, p->vaddr);
cp->vport = p->vport;
/* proto should only be IPPROTO_IP if d_addr is a fwmark */
ip_vs_addr_copy(p->protocol == IPPROTO_IP ? AF_UNSPEC : p->af,
&cp->daddr, daddr);
cp->dport = dport;
cp->flags = flags;
cp->fwmark = fwmark;
if (flags & IP_VS_CONN_F_TEMPLATE && p->pe) {
ip_vs_pe_get(p->pe);
cp->pe = p->pe;
cp->pe_data = p->pe_data;
cp->pe_data_len = p->pe_data_len;
}
spin_lock_init(&cp->lock);
/*
* Set the entry is referenced by the current thread before hashing
* it in the table, so that other thread run ip_vs_random_dropentry
* but cannot drop this entry.
*/
atomic_set(&cp->refcnt, 1);
atomic_set(&cp->n_control, 0);
atomic_set(&cp->in_pkts, 0);
atomic_inc(&ipvs->conn_count);
if (flags & IP_VS_CONN_F_NO_CPORT)
atomic_inc(&ip_vs_conn_no_cport_cnt);
/* Bind the connection with a destination server */
ip_vs_bind_dest(cp, dest);
/* Set its state and timeout */
cp->state = 0;
cp->timeout = 3*HZ;
/* Bind its packet transmitter */
#ifdef CONFIG_IP_VS_IPV6
if (p->af == AF_INET6)
ip_vs_bind_xmit_v6(cp);
else
#endif
ip_vs_bind_xmit(cp);
if (unlikely(pd && atomic_read(&pd->appcnt)))
ip_vs_bind_app(cp, pd->pp);
/*
* Allow conntrack to be preserved. By default, conntrack
* is created and destroyed for every packet.
* Sometimes keeping conntrack can be useful for
* IP_VS_CONN_F_ONE_PACKET too.
*/
if (ip_vs_conntrack_enabled(ipvs))
cp->flags |= IP_VS_CONN_F_NFCT;
/* Hash it in the ip_vs_conn_tab finally */
ip_vs_conn_hash(cp);
return cp;
}
/*
* /proc/net/ip_vs_conn entries
*/
#ifdef CONFIG_PROC_FS
struct ip_vs_iter_state {
struct seq_net_private p;
struct hlist_head *l;
};
static void *ip_vs_conn_array(struct seq_file *seq, loff_t pos)
{
int idx;
struct ip_vs_conn *cp;
struct ip_vs_iter_state *iter = seq->private;
struct hlist_node *n;
for (idx = 0; idx < ip_vs_conn_tab_size; idx++) {
ct_read_lock_bh(idx);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[idx], c_list) {
if (pos-- == 0) {
iter->l = &ip_vs_conn_tab[idx];
return cp;
}
}
ct_read_unlock_bh(idx);
}
return NULL;
}
static void *ip_vs_conn_seq_start(struct seq_file *seq, loff_t *pos)
{
struct ip_vs_iter_state *iter = seq->private;
iter->l = NULL;
return *pos ? ip_vs_conn_array(seq, *pos - 1) :SEQ_START_TOKEN;
}
static void *ip_vs_conn_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct ip_vs_conn *cp = v;
struct ip_vs_iter_state *iter = seq->private;
struct hlist_node *e;
struct hlist_head *l = iter->l;
int idx;
++*pos;
if (v == SEQ_START_TOKEN)
return ip_vs_conn_array(seq, 0);
/* more on same hash chain? */
if ((e = cp->c_list.next))
return hlist_entry(e, struct ip_vs_conn, c_list);
idx = l - ip_vs_conn_tab;
ct_read_unlock_bh(idx);
while (++idx < ip_vs_conn_tab_size) {
ct_read_lock_bh(idx);
hlist_for_each_entry(cp, e, &ip_vs_conn_tab[idx], c_list) {
iter->l = &ip_vs_conn_tab[idx];
return cp;
}
ct_read_unlock_bh(idx);
}
iter->l = NULL;
return NULL;
}
static void ip_vs_conn_seq_stop(struct seq_file *seq, void *v)
{
struct ip_vs_iter_state *iter = seq->private;
struct hlist_head *l = iter->l;
if (l)
ct_read_unlock_bh(l - ip_vs_conn_tab);
}
static int ip_vs_conn_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"Pro FromIP FPrt ToIP TPrt DestIP DPrt State Expires PEName PEData\n");
else {
const struct ip_vs_conn *cp = v;
struct net *net = seq_file_net(seq);
char pe_data[IP_VS_PENAME_MAXLEN + IP_VS_PEDATA_MAXLEN + 3];
size_t len = 0;
if (!ip_vs_conn_net_eq(cp, net))
return 0;
if (cp->pe_data) {
pe_data[0] = ' ';
len = strlen(cp->pe->name);
memcpy(pe_data + 1, cp->pe->name, len);
pe_data[len + 1] = ' ';
len += 2;
len += cp->pe->show_pe_data(cp, pe_data + len);
}
pe_data[len] = '\0';
#ifdef CONFIG_IP_VS_IPV6
if (cp->af == AF_INET6)
seq_printf(seq, "%-3s %pI6 %04X %pI6 %04X "
"%pI6 %04X %-11s %7lu%s\n",
ip_vs_proto_name(cp->protocol),
&cp->caddr.in6, ntohs(cp->cport),
&cp->vaddr.in6, ntohs(cp->vport),
&cp->daddr.in6, ntohs(cp->dport),
ip_vs_state_name(cp->protocol, cp->state),
(cp->timer.expires-jiffies)/HZ, pe_data);
else
#endif
seq_printf(seq,
"%-3s %08X %04X %08X %04X"
" %08X %04X %-11s %7lu%s\n",
ip_vs_proto_name(cp->protocol),
ntohl(cp->caddr.ip), ntohs(cp->cport),
ntohl(cp->vaddr.ip), ntohs(cp->vport),
ntohl(cp->daddr.ip), ntohs(cp->dport),
ip_vs_state_name(cp->protocol, cp->state),
(cp->timer.expires-jiffies)/HZ, pe_data);
}
return 0;
}
static const struct seq_operations ip_vs_conn_seq_ops = {
.start = ip_vs_conn_seq_start,
.next = ip_vs_conn_seq_next,
.stop = ip_vs_conn_seq_stop,
.show = ip_vs_conn_seq_show,
};
static int ip_vs_conn_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ip_vs_conn_seq_ops,
sizeof(struct ip_vs_iter_state));
}
static const struct file_operations ip_vs_conn_fops = {
.owner = THIS_MODULE,
.open = ip_vs_conn_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static const char *ip_vs_origin_name(unsigned flags)
{
if (flags & IP_VS_CONN_F_SYNC)
return "SYNC";
else
return "LOCAL";
}
static int ip_vs_conn_sync_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"Pro FromIP FPrt ToIP TPrt DestIP DPrt State Origin Expires\n");
else {
const struct ip_vs_conn *cp = v;
struct net *net = seq_file_net(seq);
if (!ip_vs_conn_net_eq(cp, net))
return 0;
#ifdef CONFIG_IP_VS_IPV6
if (cp->af == AF_INET6)
seq_printf(seq, "%-3s %pI6 %04X %pI6 %04X %pI6 %04X %-11s %-6s %7lu\n",
ip_vs_proto_name(cp->protocol),
&cp->caddr.in6, ntohs(cp->cport),
&cp->vaddr.in6, ntohs(cp->vport),
&cp->daddr.in6, ntohs(cp->dport),
ip_vs_state_name(cp->protocol, cp->state),
ip_vs_origin_name(cp->flags),
(cp->timer.expires-jiffies)/HZ);
else
#endif
seq_printf(seq,
"%-3s %08X %04X %08X %04X "
"%08X %04X %-11s %-6s %7lu\n",
ip_vs_proto_name(cp->protocol),
ntohl(cp->caddr.ip), ntohs(cp->cport),
ntohl(cp->vaddr.ip), ntohs(cp->vport),
ntohl(cp->daddr.ip), ntohs(cp->dport),
ip_vs_state_name(cp->protocol, cp->state),
ip_vs_origin_name(cp->flags),
(cp->timer.expires-jiffies)/HZ);
}
return 0;
}
static const struct seq_operations ip_vs_conn_sync_seq_ops = {
.start = ip_vs_conn_seq_start,
.next = ip_vs_conn_seq_next,
.stop = ip_vs_conn_seq_stop,
.show = ip_vs_conn_sync_seq_show,
};
static int ip_vs_conn_sync_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ip_vs_conn_sync_seq_ops,
sizeof(struct ip_vs_iter_state));
}
static const struct file_operations ip_vs_conn_sync_fops = {
.owner = THIS_MODULE,
.open = ip_vs_conn_sync_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
/*
* Randomly drop connection entries before running out of memory
*/
static inline int todrop_entry(struct ip_vs_conn *cp)
{
/*
* The drop rate array needs tuning for real environments.
* Called from timer bh only => no locking
*/
static const char todrop_rate[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
static char todrop_counter[9] = {0};
int i;
/* if the conn entry hasn't lasted for 60 seconds, don't drop it.
This will leave enough time for normal connection to get
through. */
if (time_before(cp->timeout + jiffies, cp->timer.expires + 60*HZ))
return 0;
/* Don't drop the entry if its number of incoming packets is not
located in [0, 8] */
i = atomic_read(&cp->in_pkts);
if (i > 8 || i < 0) return 0;
if (!todrop_rate[i]) return 0;
if (--todrop_counter[i] > 0) return 0;
todrop_counter[i] = todrop_rate[i];
return 1;
}
/* Called from keventd and must protect itself from softirqs */
void ip_vs_random_dropentry(struct net *net)
{
int idx;
struct ip_vs_conn *cp;
/*
* Randomly scan 1/32 of the whole table every second
*/
for (idx = 0; idx < (ip_vs_conn_tab_size>>5); idx++) {
unsigned hash = net_random() & ip_vs_conn_tab_mask;
struct hlist_node *n;
/*
* Lock is actually needed in this loop.
*/
ct_write_lock_bh(hash);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[hash], c_list) {
if (cp->flags & IP_VS_CONN_F_TEMPLATE)
/* connection template */
continue;
if (!ip_vs_conn_net_eq(cp, net))
continue;
if (cp->protocol == IPPROTO_TCP) {
switch(cp->state) {
case IP_VS_TCP_S_SYN_RECV:
case IP_VS_TCP_S_SYNACK:
break;
case IP_VS_TCP_S_ESTABLISHED:
if (todrop_entry(cp))
break;
continue;
default:
continue;
}
} else {
if (!todrop_entry(cp))
continue;
}
IP_VS_DBG(4, "del connection\n");
ip_vs_conn_expire_now(cp);
if (cp->control) {
IP_VS_DBG(4, "del conn template\n");
ip_vs_conn_expire_now(cp->control);
}
}
ct_write_unlock_bh(hash);
}
}
/*
* Flush all the connection entries in the ip_vs_conn_tab
*/
static void ip_vs_conn_flush(struct net *net)
{
int idx;
struct ip_vs_conn *cp;
struct netns_ipvs *ipvs = net_ipvs(net);
flush_again:
for (idx = 0; idx < ip_vs_conn_tab_size; idx++) {
struct hlist_node *n;
/*
* Lock is actually needed in this loop.
*/
ct_write_lock_bh(idx);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[idx], c_list) {
if (!ip_vs_conn_net_eq(cp, net))
continue;
IP_VS_DBG(4, "del connection\n");
ip_vs_conn_expire_now(cp);
if (cp->control) {
IP_VS_DBG(4, "del conn template\n");
ip_vs_conn_expire_now(cp->control);
}
}
ct_write_unlock_bh(idx);
}
/* the counter may be not NULL, because maybe some conn entries
are run by slow timer handler or unhashed but still referred */
if (atomic_read(&ipvs->conn_count) != 0) {
schedule();
goto flush_again;
}
}
/*
* per netns init and exit
*/
int __net_init ip_vs_conn_net_init(struct net *net)
{
struct netns_ipvs *ipvs = net_ipvs(net);
atomic_set(&ipvs->conn_count, 0);
proc_net_fops_create(net, "ip_vs_conn", 0, &ip_vs_conn_fops);
proc_net_fops_create(net, "ip_vs_conn_sync", 0, &ip_vs_conn_sync_fops);
return 0;
}
void __net_exit ip_vs_conn_net_cleanup(struct net *net)
{
/* flush all the connection entries first */
ip_vs_conn_flush(net);
proc_net_remove(net, "ip_vs_conn");
proc_net_remove(net, "ip_vs_conn_sync");
}
int __init ip_vs_conn_init(void)
{
int idx;
/* Compute size and mask */
ip_vs_conn_tab_size = 1 << ip_vs_conn_tab_bits;
ip_vs_conn_tab_mask = ip_vs_conn_tab_size - 1;
/*
* Allocate the connection hash table and initialize its list heads
*/
ip_vs_conn_tab = vmalloc(ip_vs_conn_tab_size * sizeof(*ip_vs_conn_tab));
if (!ip_vs_conn_tab)
return -ENOMEM;
/* Allocate ip_vs_conn slab cache */
ip_vs_conn_cachep = kmem_cache_create("ip_vs_conn",
sizeof(struct ip_vs_conn), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!ip_vs_conn_cachep) {
vfree(ip_vs_conn_tab);
return -ENOMEM;
}
pr_info("Connection hash table configured "
"(size=%d, memory=%ldKbytes)\n",
ip_vs_conn_tab_size,
(long)(ip_vs_conn_tab_size*sizeof(struct list_head))/1024);
IP_VS_DBG(0, "Each connection entry needs %Zd bytes at least\n",
sizeof(struct ip_vs_conn));
for (idx = 0; idx < ip_vs_conn_tab_size; idx++)
INIT_HLIST_HEAD(&ip_vs_conn_tab[idx]);
for (idx = 0; idx < CT_LOCKARRAY_SIZE; idx++) {
rwlock_init(&__ip_vs_conntbl_lock_array[idx].l);
}
/* calculate the random value for connection hash */
get_random_bytes(&ip_vs_conn_rnd, sizeof(ip_vs_conn_rnd));
return 0;
}
void ip_vs_conn_cleanup(void)
{
/* Release the empty cache */
kmem_cache_destroy(ip_vs_conn_cachep);
vfree(ip_vs_conn_tab);
}
| gpl-2.0 |
sxwzhw/iproj | arch/arm/mach-netx/nxdkn.c | 5000 | 2538 | /*
* arch/arm/mach-netx/nxdkn.c
*
* Copyright (c) 2005 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/dma-mapping.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/mtd/plat-ram.h>
#include <linux/platform_device.h>
#include <linux/amba/bus.h>
#include <linux/amba/clcd.h>
#include <mach/hardware.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <asm/hardware/vic.h>
#include <mach/netx-regs.h>
#include <mach/eth.h>
#include "generic.h"
static struct netxeth_platform_data eth0_platform_data = {
.xcno = 0,
};
static struct platform_device nxdkn_eth0_device = {
.name = "netx-eth",
.id = 0,
.num_resources = 0,
.resource = NULL,
.dev = {
.platform_data = ð0_platform_data,
}
};
static struct netxeth_platform_data eth1_platform_data = {
.xcno = 1,
};
static struct platform_device nxdkn_eth1_device = {
.name = "netx-eth",
.id = 1,
.num_resources = 0,
.resource = NULL,
.dev = {
.platform_data = ð1_platform_data,
}
};
static struct resource netx_uart0_resources[] = {
[0] = {
.start = 0x00100A00,
.end = 0x00100A3F,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = (NETX_IRQ_UART0),
.end = (NETX_IRQ_UART0),
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device netx_uart0_device = {
.name = "netx-uart",
.id = 0,
.num_resources = ARRAY_SIZE(netx_uart0_resources),
.resource = netx_uart0_resources,
};
static struct platform_device *devices[] __initdata = {
&nxdkn_eth0_device,
&nxdkn_eth1_device,
&netx_uart0_device,
};
static void __init nxdkn_init(void)
{
platform_add_devices(devices, ARRAY_SIZE(devices));
}
MACHINE_START(NXDKN, "Hilscher nxdkn")
.atag_offset = 0x100,
.map_io = netx_map_io,
.init_irq = netx_init_irq,
.handle_irq = vic_handle_irq,
.timer = &netx_timer,
.init_machine = nxdkn_init,
.restart = netx_restart,
MACHINE_END
| gpl-2.0 |
bensonhsu2013/android_kernel_samsung_lt02wifi | net/netfilter/ipvs/ip_vs_conn.c | 5000 | 33748 | /*
* IPVS An implementation of the IP virtual server support for the
* LINUX operating system. IPVS is now implemented as a module
* over the Netfilter framework. IPVS can be used to build a
* high-performance and highly available server based on a
* cluster of servers.
*
* Authors: Wensong Zhang <wensong@linuxvirtualserver.org>
* Peter Kese <peter.kese@ijs.si>
* Julian Anastasov <ja@ssi.bg>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* The IPVS code for kernel 2.2 was done by Wensong Zhang and Peter Kese,
* with changes/fixes from Julian Anastasov, Lars Marowsky-Bree, Horms
* and others. Many code here is taken from IP MASQ code of kernel 2.2.
*
* Changes:
*
*/
#define KMSG_COMPONENT "IPVS"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/interrupt.h>
#include <linux/in.h>
#include <linux/net.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/proc_fs.h> /* for proc_net_* */
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/jhash.h>
#include <linux/random.h>
#include <net/net_namespace.h>
#include <net/ip_vs.h>
#ifndef CONFIG_IP_VS_TAB_BITS
#define CONFIG_IP_VS_TAB_BITS 12
#endif
/*
* Connection hash size. Default is what was selected at compile time.
*/
static int ip_vs_conn_tab_bits = CONFIG_IP_VS_TAB_BITS;
module_param_named(conn_tab_bits, ip_vs_conn_tab_bits, int, 0444);
MODULE_PARM_DESC(conn_tab_bits, "Set connections' hash size");
/* size and mask values */
int ip_vs_conn_tab_size __read_mostly;
static int ip_vs_conn_tab_mask __read_mostly;
/*
* Connection hash table: for input and output packets lookups of IPVS
*/
static struct hlist_head *ip_vs_conn_tab __read_mostly;
/* SLAB cache for IPVS connections */
static struct kmem_cache *ip_vs_conn_cachep __read_mostly;
/* counter for no client port connections */
static atomic_t ip_vs_conn_no_cport_cnt = ATOMIC_INIT(0);
/* random value for IPVS connection hash */
static unsigned int ip_vs_conn_rnd __read_mostly;
/*
* Fine locking granularity for big connection hash table
*/
#define CT_LOCKARRAY_BITS 5
#define CT_LOCKARRAY_SIZE (1<<CT_LOCKARRAY_BITS)
#define CT_LOCKARRAY_MASK (CT_LOCKARRAY_SIZE-1)
struct ip_vs_aligned_lock
{
rwlock_t l;
} __attribute__((__aligned__(SMP_CACHE_BYTES)));
/* lock array for conn table */
static struct ip_vs_aligned_lock
__ip_vs_conntbl_lock_array[CT_LOCKARRAY_SIZE] __cacheline_aligned;
static inline void ct_read_lock(unsigned key)
{
read_lock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_read_unlock(unsigned key)
{
read_unlock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_write_lock(unsigned key)
{
write_lock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_write_unlock(unsigned key)
{
write_unlock(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_read_lock_bh(unsigned key)
{
read_lock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_read_unlock_bh(unsigned key)
{
read_unlock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_write_lock_bh(unsigned key)
{
write_lock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
static inline void ct_write_unlock_bh(unsigned key)
{
write_unlock_bh(&__ip_vs_conntbl_lock_array[key&CT_LOCKARRAY_MASK].l);
}
/*
* Returns hash value for IPVS connection entry
*/
static unsigned int ip_vs_conn_hashkey(struct net *net, int af, unsigned proto,
const union nf_inet_addr *addr,
__be16 port)
{
#ifdef CONFIG_IP_VS_IPV6
if (af == AF_INET6)
return (jhash_3words(jhash(addr, 16, ip_vs_conn_rnd),
(__force u32)port, proto, ip_vs_conn_rnd) ^
((size_t)net>>8)) & ip_vs_conn_tab_mask;
#endif
return (jhash_3words((__force u32)addr->ip, (__force u32)port, proto,
ip_vs_conn_rnd) ^
((size_t)net>>8)) & ip_vs_conn_tab_mask;
}
static unsigned int ip_vs_conn_hashkey_param(const struct ip_vs_conn_param *p,
bool inverse)
{
const union nf_inet_addr *addr;
__be16 port;
if (p->pe_data && p->pe->hashkey_raw)
return p->pe->hashkey_raw(p, ip_vs_conn_rnd, inverse) &
ip_vs_conn_tab_mask;
if (likely(!inverse)) {
addr = p->caddr;
port = p->cport;
} else {
addr = p->vaddr;
port = p->vport;
}
return ip_vs_conn_hashkey(p->net, p->af, p->protocol, addr, port);
}
static unsigned int ip_vs_conn_hashkey_conn(const struct ip_vs_conn *cp)
{
struct ip_vs_conn_param p;
ip_vs_conn_fill_param(ip_vs_conn_net(cp), cp->af, cp->protocol,
&cp->caddr, cp->cport, NULL, 0, &p);
if (cp->pe) {
p.pe = cp->pe;
p.pe_data = cp->pe_data;
p.pe_data_len = cp->pe_data_len;
}
return ip_vs_conn_hashkey_param(&p, false);
}
/*
* Hashes ip_vs_conn in ip_vs_conn_tab by netns,proto,addr,port.
* returns bool success.
*/
static inline int ip_vs_conn_hash(struct ip_vs_conn *cp)
{
unsigned hash;
int ret;
if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
return 0;
/* Hash by protocol, client address and port */
hash = ip_vs_conn_hashkey_conn(cp);
ct_write_lock(hash);
spin_lock(&cp->lock);
if (!(cp->flags & IP_VS_CONN_F_HASHED)) {
hlist_add_head(&cp->c_list, &ip_vs_conn_tab[hash]);
cp->flags |= IP_VS_CONN_F_HASHED;
atomic_inc(&cp->refcnt);
ret = 1;
} else {
pr_err("%s(): request for already hashed, called from %pF\n",
__func__, __builtin_return_address(0));
ret = 0;
}
spin_unlock(&cp->lock);
ct_write_unlock(hash);
return ret;
}
/*
* UNhashes ip_vs_conn from ip_vs_conn_tab.
* returns bool success.
*/
static inline int ip_vs_conn_unhash(struct ip_vs_conn *cp)
{
unsigned hash;
int ret;
/* unhash it and decrease its reference counter */
hash = ip_vs_conn_hashkey_conn(cp);
ct_write_lock(hash);
spin_lock(&cp->lock);
if (cp->flags & IP_VS_CONN_F_HASHED) {
hlist_del(&cp->c_list);
cp->flags &= ~IP_VS_CONN_F_HASHED;
atomic_dec(&cp->refcnt);
ret = 1;
} else
ret = 0;
spin_unlock(&cp->lock);
ct_write_unlock(hash);
return ret;
}
/*
* Gets ip_vs_conn associated with supplied parameters in the ip_vs_conn_tab.
* Called for pkts coming from OUTside-to-INside.
* p->caddr, p->cport: pkt source address (foreign host)
* p->vaddr, p->vport: pkt dest address (load balancer)
*/
static inline struct ip_vs_conn *
__ip_vs_conn_in_get(const struct ip_vs_conn_param *p)
{
unsigned hash;
struct ip_vs_conn *cp;
struct hlist_node *n;
hash = ip_vs_conn_hashkey_param(p, false);
ct_read_lock(hash);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[hash], c_list) {
if (cp->af == p->af &&
p->cport == cp->cport && p->vport == cp->vport &&
ip_vs_addr_equal(p->af, p->caddr, &cp->caddr) &&
ip_vs_addr_equal(p->af, p->vaddr, &cp->vaddr) &&
((!p->cport) ^ (!(cp->flags & IP_VS_CONN_F_NO_CPORT))) &&
p->protocol == cp->protocol &&
ip_vs_conn_net_eq(cp, p->net)) {
/* HIT */
atomic_inc(&cp->refcnt);
ct_read_unlock(hash);
return cp;
}
}
ct_read_unlock(hash);
return NULL;
}
struct ip_vs_conn *ip_vs_conn_in_get(const struct ip_vs_conn_param *p)
{
struct ip_vs_conn *cp;
cp = __ip_vs_conn_in_get(p);
if (!cp && atomic_read(&ip_vs_conn_no_cport_cnt)) {
struct ip_vs_conn_param cport_zero_p = *p;
cport_zero_p.cport = 0;
cp = __ip_vs_conn_in_get(&cport_zero_p);
}
IP_VS_DBG_BUF(9, "lookup/in %s %s:%d->%s:%d %s\n",
ip_vs_proto_name(p->protocol),
IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport),
cp ? "hit" : "not hit");
return cp;
}
static int
ip_vs_conn_fill_param_proto(int af, const struct sk_buff *skb,
const struct ip_vs_iphdr *iph,
unsigned int proto_off, int inverse,
struct ip_vs_conn_param *p)
{
__be16 _ports[2], *pptr;
struct net *net = skb_net(skb);
pptr = skb_header_pointer(skb, proto_off, sizeof(_ports), _ports);
if (pptr == NULL)
return 1;
if (likely(!inverse))
ip_vs_conn_fill_param(net, af, iph->protocol, &iph->saddr,
pptr[0], &iph->daddr, pptr[1], p);
else
ip_vs_conn_fill_param(net, af, iph->protocol, &iph->daddr,
pptr[1], &iph->saddr, pptr[0], p);
return 0;
}
struct ip_vs_conn *
ip_vs_conn_in_get_proto(int af, const struct sk_buff *skb,
const struct ip_vs_iphdr *iph,
unsigned int proto_off, int inverse)
{
struct ip_vs_conn_param p;
if (ip_vs_conn_fill_param_proto(af, skb, iph, proto_off, inverse, &p))
return NULL;
return ip_vs_conn_in_get(&p);
}
EXPORT_SYMBOL_GPL(ip_vs_conn_in_get_proto);
/* Get reference to connection template */
struct ip_vs_conn *ip_vs_ct_in_get(const struct ip_vs_conn_param *p)
{
unsigned hash;
struct ip_vs_conn *cp;
struct hlist_node *n;
hash = ip_vs_conn_hashkey_param(p, false);
ct_read_lock(hash);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[hash], c_list) {
if (!ip_vs_conn_net_eq(cp, p->net))
continue;
if (p->pe_data && p->pe->ct_match) {
if (p->pe == cp->pe && p->pe->ct_match(p, cp))
goto out;
continue;
}
if (cp->af == p->af &&
ip_vs_addr_equal(p->af, p->caddr, &cp->caddr) &&
/* protocol should only be IPPROTO_IP if
* p->vaddr is a fwmark */
ip_vs_addr_equal(p->protocol == IPPROTO_IP ? AF_UNSPEC :
p->af, p->vaddr, &cp->vaddr) &&
p->cport == cp->cport && p->vport == cp->vport &&
cp->flags & IP_VS_CONN_F_TEMPLATE &&
p->protocol == cp->protocol)
goto out;
}
cp = NULL;
out:
if (cp)
atomic_inc(&cp->refcnt);
ct_read_unlock(hash);
IP_VS_DBG_BUF(9, "template lookup/in %s %s:%d->%s:%d %s\n",
ip_vs_proto_name(p->protocol),
IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport),
cp ? "hit" : "not hit");
return cp;
}
/* Gets ip_vs_conn associated with supplied parameters in the ip_vs_conn_tab.
* Called for pkts coming from inside-to-OUTside.
* p->caddr, p->cport: pkt source address (inside host)
* p->vaddr, p->vport: pkt dest address (foreign host) */
struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p)
{
unsigned hash;
struct ip_vs_conn *cp, *ret=NULL;
struct hlist_node *n;
/*
* Check for "full" addressed entries
*/
hash = ip_vs_conn_hashkey_param(p, true);
ct_read_lock(hash);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[hash], c_list) {
if (cp->af == p->af &&
p->vport == cp->cport && p->cport == cp->dport &&
ip_vs_addr_equal(p->af, p->vaddr, &cp->caddr) &&
ip_vs_addr_equal(p->af, p->caddr, &cp->daddr) &&
p->protocol == cp->protocol &&
ip_vs_conn_net_eq(cp, p->net)) {
/* HIT */
atomic_inc(&cp->refcnt);
ret = cp;
break;
}
}
ct_read_unlock(hash);
IP_VS_DBG_BUF(9, "lookup/out %s %s:%d->%s:%d %s\n",
ip_vs_proto_name(p->protocol),
IP_VS_DBG_ADDR(p->af, p->caddr), ntohs(p->cport),
IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport),
ret ? "hit" : "not hit");
return ret;
}
struct ip_vs_conn *
ip_vs_conn_out_get_proto(int af, const struct sk_buff *skb,
const struct ip_vs_iphdr *iph,
unsigned int proto_off, int inverse)
{
struct ip_vs_conn_param p;
if (ip_vs_conn_fill_param_proto(af, skb, iph, proto_off, inverse, &p))
return NULL;
return ip_vs_conn_out_get(&p);
}
EXPORT_SYMBOL_GPL(ip_vs_conn_out_get_proto);
/*
* Put back the conn and restart its timer with its timeout
*/
void ip_vs_conn_put(struct ip_vs_conn *cp)
{
unsigned long t = (cp->flags & IP_VS_CONN_F_ONE_PACKET) ?
0 : cp->timeout;
mod_timer(&cp->timer, jiffies+t);
__ip_vs_conn_put(cp);
}
/*
* Fill a no_client_port connection with a client port number
*/
void ip_vs_conn_fill_cport(struct ip_vs_conn *cp, __be16 cport)
{
if (ip_vs_conn_unhash(cp)) {
spin_lock(&cp->lock);
if (cp->flags & IP_VS_CONN_F_NO_CPORT) {
atomic_dec(&ip_vs_conn_no_cport_cnt);
cp->flags &= ~IP_VS_CONN_F_NO_CPORT;
cp->cport = cport;
}
spin_unlock(&cp->lock);
/* hash on new dport */
ip_vs_conn_hash(cp);
}
}
/*
* Bind a connection entry with the corresponding packet_xmit.
* Called by ip_vs_conn_new.
*/
static inline void ip_vs_bind_xmit(struct ip_vs_conn *cp)
{
switch (IP_VS_FWD_METHOD(cp)) {
case IP_VS_CONN_F_MASQ:
cp->packet_xmit = ip_vs_nat_xmit;
break;
case IP_VS_CONN_F_TUNNEL:
cp->packet_xmit = ip_vs_tunnel_xmit;
break;
case IP_VS_CONN_F_DROUTE:
cp->packet_xmit = ip_vs_dr_xmit;
break;
case IP_VS_CONN_F_LOCALNODE:
cp->packet_xmit = ip_vs_null_xmit;
break;
case IP_VS_CONN_F_BYPASS:
cp->packet_xmit = ip_vs_bypass_xmit;
break;
}
}
#ifdef CONFIG_IP_VS_IPV6
static inline void ip_vs_bind_xmit_v6(struct ip_vs_conn *cp)
{
switch (IP_VS_FWD_METHOD(cp)) {
case IP_VS_CONN_F_MASQ:
cp->packet_xmit = ip_vs_nat_xmit_v6;
break;
case IP_VS_CONN_F_TUNNEL:
cp->packet_xmit = ip_vs_tunnel_xmit_v6;
break;
case IP_VS_CONN_F_DROUTE:
cp->packet_xmit = ip_vs_dr_xmit_v6;
break;
case IP_VS_CONN_F_LOCALNODE:
cp->packet_xmit = ip_vs_null_xmit;
break;
case IP_VS_CONN_F_BYPASS:
cp->packet_xmit = ip_vs_bypass_xmit_v6;
break;
}
}
#endif
static inline int ip_vs_dest_totalconns(struct ip_vs_dest *dest)
{
return atomic_read(&dest->activeconns)
+ atomic_read(&dest->inactconns);
}
/*
* Bind a connection entry with a virtual service destination
* Called just after a new connection entry is created.
*/
static inline void
ip_vs_bind_dest(struct ip_vs_conn *cp, struct ip_vs_dest *dest)
{
unsigned int conn_flags;
/* if dest is NULL, then return directly */
if (!dest)
return;
/* Increase the refcnt counter of the dest */
atomic_inc(&dest->refcnt);
conn_flags = atomic_read(&dest->conn_flags);
if (cp->protocol != IPPROTO_UDP)
conn_flags &= ~IP_VS_CONN_F_ONE_PACKET;
/* Bind with the destination and its corresponding transmitter */
if (cp->flags & IP_VS_CONN_F_SYNC) {
/* if the connection is not template and is created
* by sync, preserve the activity flag.
*/
if (!(cp->flags & IP_VS_CONN_F_TEMPLATE))
conn_flags &= ~IP_VS_CONN_F_INACTIVE;
/* connections inherit forwarding method from dest */
cp->flags &= ~IP_VS_CONN_F_FWD_MASK;
}
cp->flags |= conn_flags;
cp->dest = dest;
IP_VS_DBG_BUF(7, "Bind-dest %s c:%s:%d v:%s:%d "
"d:%s:%d fwd:%c s:%u conn->flags:%X conn->refcnt:%d "
"dest->refcnt:%d\n",
ip_vs_proto_name(cp->protocol),
IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport),
IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport),
IP_VS_DBG_ADDR(cp->af, &cp->daddr), ntohs(cp->dport),
ip_vs_fwd_tag(cp), cp->state,
cp->flags, atomic_read(&cp->refcnt),
atomic_read(&dest->refcnt));
/* Update the connection counters */
if (!(cp->flags & IP_VS_CONN_F_TEMPLATE)) {
/* It is a normal connection, so increase the inactive
connection counter because it is in TCP SYNRECV
state (inactive) or other protocol inacive state */
if ((cp->flags & IP_VS_CONN_F_SYNC) &&
(!(cp->flags & IP_VS_CONN_F_INACTIVE)))
atomic_inc(&dest->activeconns);
else
atomic_inc(&dest->inactconns);
} else {
/* It is a persistent connection/template, so increase
the persistent connection counter */
atomic_inc(&dest->persistconns);
}
if (dest->u_threshold != 0 &&
ip_vs_dest_totalconns(dest) >= dest->u_threshold)
dest->flags |= IP_VS_DEST_F_OVERLOAD;
}
/*
* Check if there is a destination for the connection, if so
* bind the connection to the destination.
*/
struct ip_vs_dest *ip_vs_try_bind_dest(struct ip_vs_conn *cp)
{
struct ip_vs_dest *dest;
if ((cp) && (!cp->dest)) {
dest = ip_vs_find_dest(ip_vs_conn_net(cp), cp->af, &cp->daddr,
cp->dport, &cp->vaddr, cp->vport,
cp->protocol, cp->fwmark, cp->flags);
ip_vs_bind_dest(cp, dest);
return dest;
} else
return NULL;
}
/*
* Unbind a connection entry with its VS destination
* Called by the ip_vs_conn_expire function.
*/
static inline void ip_vs_unbind_dest(struct ip_vs_conn *cp)
{
struct ip_vs_dest *dest = cp->dest;
if (!dest)
return;
IP_VS_DBG_BUF(7, "Unbind-dest %s c:%s:%d v:%s:%d "
"d:%s:%d fwd:%c s:%u conn->flags:%X conn->refcnt:%d "
"dest->refcnt:%d\n",
ip_vs_proto_name(cp->protocol),
IP_VS_DBG_ADDR(cp->af, &cp->caddr), ntohs(cp->cport),
IP_VS_DBG_ADDR(cp->af, &cp->vaddr), ntohs(cp->vport),
IP_VS_DBG_ADDR(cp->af, &cp->daddr), ntohs(cp->dport),
ip_vs_fwd_tag(cp), cp->state,
cp->flags, atomic_read(&cp->refcnt),
atomic_read(&dest->refcnt));
/* Update the connection counters */
if (!(cp->flags & IP_VS_CONN_F_TEMPLATE)) {
/* It is a normal connection, so decrease the inactconns
or activeconns counter */
if (cp->flags & IP_VS_CONN_F_INACTIVE) {
atomic_dec(&dest->inactconns);
} else {
atomic_dec(&dest->activeconns);
}
} else {
/* It is a persistent connection/template, so decrease
the persistent connection counter */
atomic_dec(&dest->persistconns);
}
if (dest->l_threshold != 0) {
if (ip_vs_dest_totalconns(dest) < dest->l_threshold)
dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
} else if (dest->u_threshold != 0) {
if (ip_vs_dest_totalconns(dest) * 4 < dest->u_threshold * 3)
dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
} else {
if (dest->flags & IP_VS_DEST_F_OVERLOAD)
dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
}
/*
* Simply decrease the refcnt of the dest, because the
* dest will be either in service's destination list
* or in the trash.
*/
atomic_dec(&dest->refcnt);
}
static int expire_quiescent_template(struct netns_ipvs *ipvs,
struct ip_vs_dest *dest)
{
#ifdef CONFIG_SYSCTL
return ipvs->sysctl_expire_quiescent_template &&
(atomic_read(&dest->weight) == 0);
#else
return 0;
#endif
}
/*
* Checking if the destination of a connection template is available.
* If available, return 1, otherwise invalidate this connection
* template and return 0.
*/
int ip_vs_check_template(struct ip_vs_conn *ct)
{
struct ip_vs_dest *dest = ct->dest;
struct netns_ipvs *ipvs = net_ipvs(ip_vs_conn_net(ct));
/*
* Checking the dest server status.
*/
if ((dest == NULL) ||
!(dest->flags & IP_VS_DEST_F_AVAILABLE) ||
expire_quiescent_template(ipvs, dest)) {
IP_VS_DBG_BUF(9, "check_template: dest not available for "
"protocol %s s:%s:%d v:%s:%d "
"-> d:%s:%d\n",
ip_vs_proto_name(ct->protocol),
IP_VS_DBG_ADDR(ct->af, &ct->caddr),
ntohs(ct->cport),
IP_VS_DBG_ADDR(ct->af, &ct->vaddr),
ntohs(ct->vport),
IP_VS_DBG_ADDR(ct->af, &ct->daddr),
ntohs(ct->dport));
/*
* Invalidate the connection template
*/
if (ct->vport != htons(0xffff)) {
if (ip_vs_conn_unhash(ct)) {
ct->dport = htons(0xffff);
ct->vport = htons(0xffff);
ct->cport = 0;
ip_vs_conn_hash(ct);
}
}
/*
* Simply decrease the refcnt of the template,
* don't restart its timer.
*/
atomic_dec(&ct->refcnt);
return 0;
}
return 1;
}
static void ip_vs_conn_expire(unsigned long data)
{
struct ip_vs_conn *cp = (struct ip_vs_conn *)data;
struct netns_ipvs *ipvs = net_ipvs(ip_vs_conn_net(cp));
cp->timeout = 60*HZ;
/*
* hey, I'm using it
*/
atomic_inc(&cp->refcnt);
/*
* do I control anybody?
*/
if (atomic_read(&cp->n_control))
goto expire_later;
/*
* unhash it if it is hashed in the conn table
*/
if (!ip_vs_conn_unhash(cp) && !(cp->flags & IP_VS_CONN_F_ONE_PACKET))
goto expire_later;
/*
* refcnt==1 implies I'm the only one referrer
*/
if (likely(atomic_read(&cp->refcnt) == 1)) {
/* delete the timer if it is activated by other users */
if (timer_pending(&cp->timer))
del_timer(&cp->timer);
/* does anybody control me? */
if (cp->control)
ip_vs_control_del(cp);
if (cp->flags & IP_VS_CONN_F_NFCT) {
ip_vs_conn_drop_conntrack(cp);
/* Do not access conntracks during subsys cleanup
* because nf_conntrack_find_get can not be used after
* conntrack cleanup for the net.
*/
smp_rmb();
if (ipvs->enable)
ip_vs_conn_drop_conntrack(cp);
}
ip_vs_pe_put(cp->pe);
kfree(cp->pe_data);
if (unlikely(cp->app != NULL))
ip_vs_unbind_app(cp);
ip_vs_unbind_dest(cp);
if (cp->flags & IP_VS_CONN_F_NO_CPORT)
atomic_dec(&ip_vs_conn_no_cport_cnt);
atomic_dec(&ipvs->conn_count);
kmem_cache_free(ip_vs_conn_cachep, cp);
return;
}
/* hash it back to the table */
ip_vs_conn_hash(cp);
expire_later:
IP_VS_DBG(7, "delayed: conn->refcnt-1=%d conn->n_control=%d\n",
atomic_read(&cp->refcnt)-1,
atomic_read(&cp->n_control));
ip_vs_conn_put(cp);
}
void ip_vs_conn_expire_now(struct ip_vs_conn *cp)
{
if (del_timer(&cp->timer))
mod_timer(&cp->timer, jiffies);
}
/*
* Create a new connection entry and hash it into the ip_vs_conn_tab
*/
struct ip_vs_conn *
ip_vs_conn_new(const struct ip_vs_conn_param *p,
const union nf_inet_addr *daddr, __be16 dport, unsigned flags,
struct ip_vs_dest *dest, __u32 fwmark)
{
struct ip_vs_conn *cp;
struct netns_ipvs *ipvs = net_ipvs(p->net);
struct ip_vs_proto_data *pd = ip_vs_proto_data_get(p->net,
p->protocol);
cp = kmem_cache_zalloc(ip_vs_conn_cachep, GFP_ATOMIC);
if (cp == NULL) {
IP_VS_ERR_RL("%s(): no memory\n", __func__);
return NULL;
}
INIT_HLIST_NODE(&cp->c_list);
setup_timer(&cp->timer, ip_vs_conn_expire, (unsigned long)cp);
ip_vs_conn_net_set(cp, p->net);
cp->af = p->af;
cp->protocol = p->protocol;
ip_vs_addr_copy(p->af, &cp->caddr, p->caddr);
cp->cport = p->cport;
ip_vs_addr_copy(p->af, &cp->vaddr, p->vaddr);
cp->vport = p->vport;
/* proto should only be IPPROTO_IP if d_addr is a fwmark */
ip_vs_addr_copy(p->protocol == IPPROTO_IP ? AF_UNSPEC : p->af,
&cp->daddr, daddr);
cp->dport = dport;
cp->flags = flags;
cp->fwmark = fwmark;
if (flags & IP_VS_CONN_F_TEMPLATE && p->pe) {
ip_vs_pe_get(p->pe);
cp->pe = p->pe;
cp->pe_data = p->pe_data;
cp->pe_data_len = p->pe_data_len;
}
spin_lock_init(&cp->lock);
/*
* Set the entry is referenced by the current thread before hashing
* it in the table, so that other thread run ip_vs_random_dropentry
* but cannot drop this entry.
*/
atomic_set(&cp->refcnt, 1);
atomic_set(&cp->n_control, 0);
atomic_set(&cp->in_pkts, 0);
atomic_inc(&ipvs->conn_count);
if (flags & IP_VS_CONN_F_NO_CPORT)
atomic_inc(&ip_vs_conn_no_cport_cnt);
/* Bind the connection with a destination server */
ip_vs_bind_dest(cp, dest);
/* Set its state and timeout */
cp->state = 0;
cp->timeout = 3*HZ;
/* Bind its packet transmitter */
#ifdef CONFIG_IP_VS_IPV6
if (p->af == AF_INET6)
ip_vs_bind_xmit_v6(cp);
else
#endif
ip_vs_bind_xmit(cp);
if (unlikely(pd && atomic_read(&pd->appcnt)))
ip_vs_bind_app(cp, pd->pp);
/*
* Allow conntrack to be preserved. By default, conntrack
* is created and destroyed for every packet.
* Sometimes keeping conntrack can be useful for
* IP_VS_CONN_F_ONE_PACKET too.
*/
if (ip_vs_conntrack_enabled(ipvs))
cp->flags |= IP_VS_CONN_F_NFCT;
/* Hash it in the ip_vs_conn_tab finally */
ip_vs_conn_hash(cp);
return cp;
}
/*
* /proc/net/ip_vs_conn entries
*/
#ifdef CONFIG_PROC_FS
struct ip_vs_iter_state {
struct seq_net_private p;
struct hlist_head *l;
};
static void *ip_vs_conn_array(struct seq_file *seq, loff_t pos)
{
int idx;
struct ip_vs_conn *cp;
struct ip_vs_iter_state *iter = seq->private;
struct hlist_node *n;
for (idx = 0; idx < ip_vs_conn_tab_size; idx++) {
ct_read_lock_bh(idx);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[idx], c_list) {
if (pos-- == 0) {
iter->l = &ip_vs_conn_tab[idx];
return cp;
}
}
ct_read_unlock_bh(idx);
}
return NULL;
}
static void *ip_vs_conn_seq_start(struct seq_file *seq, loff_t *pos)
{
struct ip_vs_iter_state *iter = seq->private;
iter->l = NULL;
return *pos ? ip_vs_conn_array(seq, *pos - 1) :SEQ_START_TOKEN;
}
static void *ip_vs_conn_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct ip_vs_conn *cp = v;
struct ip_vs_iter_state *iter = seq->private;
struct hlist_node *e;
struct hlist_head *l = iter->l;
int idx;
++*pos;
if (v == SEQ_START_TOKEN)
return ip_vs_conn_array(seq, 0);
/* more on same hash chain? */
if ((e = cp->c_list.next))
return hlist_entry(e, struct ip_vs_conn, c_list);
idx = l - ip_vs_conn_tab;
ct_read_unlock_bh(idx);
while (++idx < ip_vs_conn_tab_size) {
ct_read_lock_bh(idx);
hlist_for_each_entry(cp, e, &ip_vs_conn_tab[idx], c_list) {
iter->l = &ip_vs_conn_tab[idx];
return cp;
}
ct_read_unlock_bh(idx);
}
iter->l = NULL;
return NULL;
}
static void ip_vs_conn_seq_stop(struct seq_file *seq, void *v)
{
struct ip_vs_iter_state *iter = seq->private;
struct hlist_head *l = iter->l;
if (l)
ct_read_unlock_bh(l - ip_vs_conn_tab);
}
static int ip_vs_conn_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"Pro FromIP FPrt ToIP TPrt DestIP DPrt State Expires PEName PEData\n");
else {
const struct ip_vs_conn *cp = v;
struct net *net = seq_file_net(seq);
char pe_data[IP_VS_PENAME_MAXLEN + IP_VS_PEDATA_MAXLEN + 3];
size_t len = 0;
if (!ip_vs_conn_net_eq(cp, net))
return 0;
if (cp->pe_data) {
pe_data[0] = ' ';
len = strlen(cp->pe->name);
memcpy(pe_data + 1, cp->pe->name, len);
pe_data[len + 1] = ' ';
len += 2;
len += cp->pe->show_pe_data(cp, pe_data + len);
}
pe_data[len] = '\0';
#ifdef CONFIG_IP_VS_IPV6
if (cp->af == AF_INET6)
seq_printf(seq, "%-3s %pI6 %04X %pI6 %04X "
"%pI6 %04X %-11s %7lu%s\n",
ip_vs_proto_name(cp->protocol),
&cp->caddr.in6, ntohs(cp->cport),
&cp->vaddr.in6, ntohs(cp->vport),
&cp->daddr.in6, ntohs(cp->dport),
ip_vs_state_name(cp->protocol, cp->state),
(cp->timer.expires-jiffies)/HZ, pe_data);
else
#endif
seq_printf(seq,
"%-3s %08X %04X %08X %04X"
" %08X %04X %-11s %7lu%s\n",
ip_vs_proto_name(cp->protocol),
ntohl(cp->caddr.ip), ntohs(cp->cport),
ntohl(cp->vaddr.ip), ntohs(cp->vport),
ntohl(cp->daddr.ip), ntohs(cp->dport),
ip_vs_state_name(cp->protocol, cp->state),
(cp->timer.expires-jiffies)/HZ, pe_data);
}
return 0;
}
static const struct seq_operations ip_vs_conn_seq_ops = {
.start = ip_vs_conn_seq_start,
.next = ip_vs_conn_seq_next,
.stop = ip_vs_conn_seq_stop,
.show = ip_vs_conn_seq_show,
};
static int ip_vs_conn_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ip_vs_conn_seq_ops,
sizeof(struct ip_vs_iter_state));
}
static const struct file_operations ip_vs_conn_fops = {
.owner = THIS_MODULE,
.open = ip_vs_conn_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static const char *ip_vs_origin_name(unsigned flags)
{
if (flags & IP_VS_CONN_F_SYNC)
return "SYNC";
else
return "LOCAL";
}
static int ip_vs_conn_sync_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"Pro FromIP FPrt ToIP TPrt DestIP DPrt State Origin Expires\n");
else {
const struct ip_vs_conn *cp = v;
struct net *net = seq_file_net(seq);
if (!ip_vs_conn_net_eq(cp, net))
return 0;
#ifdef CONFIG_IP_VS_IPV6
if (cp->af == AF_INET6)
seq_printf(seq, "%-3s %pI6 %04X %pI6 %04X %pI6 %04X %-11s %-6s %7lu\n",
ip_vs_proto_name(cp->protocol),
&cp->caddr.in6, ntohs(cp->cport),
&cp->vaddr.in6, ntohs(cp->vport),
&cp->daddr.in6, ntohs(cp->dport),
ip_vs_state_name(cp->protocol, cp->state),
ip_vs_origin_name(cp->flags),
(cp->timer.expires-jiffies)/HZ);
else
#endif
seq_printf(seq,
"%-3s %08X %04X %08X %04X "
"%08X %04X %-11s %-6s %7lu\n",
ip_vs_proto_name(cp->protocol),
ntohl(cp->caddr.ip), ntohs(cp->cport),
ntohl(cp->vaddr.ip), ntohs(cp->vport),
ntohl(cp->daddr.ip), ntohs(cp->dport),
ip_vs_state_name(cp->protocol, cp->state),
ip_vs_origin_name(cp->flags),
(cp->timer.expires-jiffies)/HZ);
}
return 0;
}
static const struct seq_operations ip_vs_conn_sync_seq_ops = {
.start = ip_vs_conn_seq_start,
.next = ip_vs_conn_seq_next,
.stop = ip_vs_conn_seq_stop,
.show = ip_vs_conn_sync_seq_show,
};
static int ip_vs_conn_sync_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ip_vs_conn_sync_seq_ops,
sizeof(struct ip_vs_iter_state));
}
static const struct file_operations ip_vs_conn_sync_fops = {
.owner = THIS_MODULE,
.open = ip_vs_conn_sync_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
/*
* Randomly drop connection entries before running out of memory
*/
static inline int todrop_entry(struct ip_vs_conn *cp)
{
/*
* The drop rate array needs tuning for real environments.
* Called from timer bh only => no locking
*/
static const char todrop_rate[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
static char todrop_counter[9] = {0};
int i;
/* if the conn entry hasn't lasted for 60 seconds, don't drop it.
This will leave enough time for normal connection to get
through. */
if (time_before(cp->timeout + jiffies, cp->timer.expires + 60*HZ))
return 0;
/* Don't drop the entry if its number of incoming packets is not
located in [0, 8] */
i = atomic_read(&cp->in_pkts);
if (i > 8 || i < 0) return 0;
if (!todrop_rate[i]) return 0;
if (--todrop_counter[i] > 0) return 0;
todrop_counter[i] = todrop_rate[i];
return 1;
}
/* Called from keventd and must protect itself from softirqs */
void ip_vs_random_dropentry(struct net *net)
{
int idx;
struct ip_vs_conn *cp;
/*
* Randomly scan 1/32 of the whole table every second
*/
for (idx = 0; idx < (ip_vs_conn_tab_size>>5); idx++) {
unsigned hash = net_random() & ip_vs_conn_tab_mask;
struct hlist_node *n;
/*
* Lock is actually needed in this loop.
*/
ct_write_lock_bh(hash);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[hash], c_list) {
if (cp->flags & IP_VS_CONN_F_TEMPLATE)
/* connection template */
continue;
if (!ip_vs_conn_net_eq(cp, net))
continue;
if (cp->protocol == IPPROTO_TCP) {
switch(cp->state) {
case IP_VS_TCP_S_SYN_RECV:
case IP_VS_TCP_S_SYNACK:
break;
case IP_VS_TCP_S_ESTABLISHED:
if (todrop_entry(cp))
break;
continue;
default:
continue;
}
} else {
if (!todrop_entry(cp))
continue;
}
IP_VS_DBG(4, "del connection\n");
ip_vs_conn_expire_now(cp);
if (cp->control) {
IP_VS_DBG(4, "del conn template\n");
ip_vs_conn_expire_now(cp->control);
}
}
ct_write_unlock_bh(hash);
}
}
/*
* Flush all the connection entries in the ip_vs_conn_tab
*/
static void ip_vs_conn_flush(struct net *net)
{
int idx;
struct ip_vs_conn *cp;
struct netns_ipvs *ipvs = net_ipvs(net);
flush_again:
for (idx = 0; idx < ip_vs_conn_tab_size; idx++) {
struct hlist_node *n;
/*
* Lock is actually needed in this loop.
*/
ct_write_lock_bh(idx);
hlist_for_each_entry(cp, n, &ip_vs_conn_tab[idx], c_list) {
if (!ip_vs_conn_net_eq(cp, net))
continue;
IP_VS_DBG(4, "del connection\n");
ip_vs_conn_expire_now(cp);
if (cp->control) {
IP_VS_DBG(4, "del conn template\n");
ip_vs_conn_expire_now(cp->control);
}
}
ct_write_unlock_bh(idx);
}
/* the counter may be not NULL, because maybe some conn entries
are run by slow timer handler or unhashed but still referred */
if (atomic_read(&ipvs->conn_count) != 0) {
schedule();
goto flush_again;
}
}
/*
* per netns init and exit
*/
int __net_init ip_vs_conn_net_init(struct net *net)
{
struct netns_ipvs *ipvs = net_ipvs(net);
atomic_set(&ipvs->conn_count, 0);
proc_net_fops_create(net, "ip_vs_conn", 0, &ip_vs_conn_fops);
proc_net_fops_create(net, "ip_vs_conn_sync", 0, &ip_vs_conn_sync_fops);
return 0;
}
void __net_exit ip_vs_conn_net_cleanup(struct net *net)
{
/* flush all the connection entries first */
ip_vs_conn_flush(net);
proc_net_remove(net, "ip_vs_conn");
proc_net_remove(net, "ip_vs_conn_sync");
}
int __init ip_vs_conn_init(void)
{
int idx;
/* Compute size and mask */
ip_vs_conn_tab_size = 1 << ip_vs_conn_tab_bits;
ip_vs_conn_tab_mask = ip_vs_conn_tab_size - 1;
/*
* Allocate the connection hash table and initialize its list heads
*/
ip_vs_conn_tab = vmalloc(ip_vs_conn_tab_size * sizeof(*ip_vs_conn_tab));
if (!ip_vs_conn_tab)
return -ENOMEM;
/* Allocate ip_vs_conn slab cache */
ip_vs_conn_cachep = kmem_cache_create("ip_vs_conn",
sizeof(struct ip_vs_conn), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!ip_vs_conn_cachep) {
vfree(ip_vs_conn_tab);
return -ENOMEM;
}
pr_info("Connection hash table configured "
"(size=%d, memory=%ldKbytes)\n",
ip_vs_conn_tab_size,
(long)(ip_vs_conn_tab_size*sizeof(struct list_head))/1024);
IP_VS_DBG(0, "Each connection entry needs %Zd bytes at least\n",
sizeof(struct ip_vs_conn));
for (idx = 0; idx < ip_vs_conn_tab_size; idx++)
INIT_HLIST_HEAD(&ip_vs_conn_tab[idx]);
for (idx = 0; idx < CT_LOCKARRAY_SIZE; idx++) {
rwlock_init(&__ip_vs_conntbl_lock_array[idx].l);
}
/* calculate the random value for connection hash */
get_random_bytes(&ip_vs_conn_rnd, sizeof(ip_vs_conn_rnd));
return 0;
}
void ip_vs_conn_cleanup(void)
{
/* Release the empty cache */
kmem_cache_destroy(ip_vs_conn_cachep);
vfree(ip_vs_conn_tab);
}
| gpl-2.0 |
TheMeddlingMonk/android_kernel_toshiba_tostab03 | drivers/watchdog/wafer5823wdt.c | 5000 | 7383 | /*
* ICP Wafer 5823 Single Board Computer WDT driver
* http://www.icpamerica.com/wafer_5823.php
* May also work on other similar models
*
* (c) Copyright 2002 Justin Cormack <justin@street-vision.com>
*
* Release 0.02
*
* Based on advantechwdt.c which is based on wdt.c.
* Original copyright messages:
*
* (c) Copyright 1996-1997 Alan Cox <alan@lxorguk.ukuu.org.uk>,
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Neither Alan Cox nor CymruNet Ltd. admit liability nor provide
* warranty for any of this software. This material is provided
* "AS-IS" and at no charge.
*
* (c) Copyright 1995 Alan Cox <alan@lxorguk.ukuu.org.uk>
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/miscdevice.h>
#include <linux/watchdog.h>
#include <linux/fs.h>
#include <linux/ioport.h>
#include <linux/notifier.h>
#include <linux/reboot.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#define WATCHDOG_NAME "Wafer 5823 WDT"
#define PFX WATCHDOG_NAME ": "
#define WD_TIMO 60 /* 60 sec default timeout */
static unsigned long wafwdt_is_open;
static char expect_close;
static DEFINE_SPINLOCK(wafwdt_lock);
/*
* You must set these - there is no sane way to probe for this board.
*
* To enable, write the timeout value in seconds (1 to 255) to I/O
* port WDT_START, then read the port to start the watchdog. To pat
* the dog, read port WDT_STOP to stop the timer, then read WDT_START
* to restart it again.
*/
static int wdt_stop = 0x843;
static int wdt_start = 0x443;
static int timeout = WD_TIMO; /* in seconds */
module_param(timeout, int, 0);
MODULE_PARM_DESC(timeout,
"Watchdog timeout in seconds. 1 <= timeout <= 255, default="
__MODULE_STRING(WD_TIMO) ".");
static int nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, int, 0);
MODULE_PARM_DESC(nowayout,
"Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
static void wafwdt_ping(void)
{
/* pat watchdog */
spin_lock(&wafwdt_lock);
inb_p(wdt_stop);
inb_p(wdt_start);
spin_unlock(&wafwdt_lock);
}
static void wafwdt_start(void)
{
/* start up watchdog */
outb_p(timeout, wdt_start);
inb_p(wdt_start);
}
static void wafwdt_stop(void)
{
/* stop watchdog */
inb_p(wdt_stop);
}
static ssize_t wafwdt_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
/* See if we got the magic character 'V' and reload the timer */
if (count) {
if (!nowayout) {
size_t i;
/* In case it was set long ago */
expect_close = 0;
/* scan to see whether or not we got the magic
character */
for (i = 0; i != count; i++) {
char c;
if (get_user(c, buf + i))
return -EFAULT;
if (c == 'V')
expect_close = 42;
}
}
/* Well, anyhow someone wrote to us, we should
return that favour */
wafwdt_ping();
}
return count;
}
static long wafwdt_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int new_timeout;
void __user *argp = (void __user *)arg;
int __user *p = argp;
static const struct watchdog_info ident = {
.options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT |
WDIOF_MAGICCLOSE,
.firmware_version = 1,
.identity = "Wafer 5823 WDT",
};
switch (cmd) {
case WDIOC_GETSUPPORT:
if (copy_to_user(argp, &ident, sizeof(ident)))
return -EFAULT;
break;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
return put_user(0, p);
case WDIOC_SETOPTIONS:
{
int options, retval = -EINVAL;
if (get_user(options, p))
return -EFAULT;
if (options & WDIOS_DISABLECARD) {
wafwdt_start();
retval = 0;
}
if (options & WDIOS_ENABLECARD) {
wafwdt_stop();
retval = 0;
}
return retval;
}
case WDIOC_KEEPALIVE:
wafwdt_ping();
break;
case WDIOC_SETTIMEOUT:
if (get_user(new_timeout, p))
return -EFAULT;
if ((new_timeout < 1) || (new_timeout > 255))
return -EINVAL;
timeout = new_timeout;
wafwdt_stop();
wafwdt_start();
/* Fall */
case WDIOC_GETTIMEOUT:
return put_user(timeout, p);
default:
return -ENOTTY;
}
return 0;
}
static int wafwdt_open(struct inode *inode, struct file *file)
{
if (test_and_set_bit(0, &wafwdt_is_open))
return -EBUSY;
/*
* Activate
*/
wafwdt_start();
return nonseekable_open(inode, file);
}
static int wafwdt_close(struct inode *inode, struct file *file)
{
if (expect_close == 42)
wafwdt_stop();
else {
printk(KERN_CRIT PFX
"WDT device closed unexpectedly. WDT will not stop!\n");
wafwdt_ping();
}
clear_bit(0, &wafwdt_is_open);
expect_close = 0;
return 0;
}
/*
* Notifier for system down
*/
static int wafwdt_notify_sys(struct notifier_block *this, unsigned long code,
void *unused)
{
if (code == SYS_DOWN || code == SYS_HALT)
wafwdt_stop();
return NOTIFY_DONE;
}
/*
* Kernel Interfaces
*/
static const struct file_operations wafwdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.write = wafwdt_write,
.unlocked_ioctl = wafwdt_ioctl,
.open = wafwdt_open,
.release = wafwdt_close,
};
static struct miscdevice wafwdt_miscdev = {
.minor = WATCHDOG_MINOR,
.name = "watchdog",
.fops = &wafwdt_fops,
};
/*
* The WDT needs to learn about soft shutdowns in order to
* turn the timebomb registers off.
*/
static struct notifier_block wafwdt_notifier = {
.notifier_call = wafwdt_notify_sys,
};
static int __init wafwdt_init(void)
{
int ret;
printk(KERN_INFO
"WDT driver for Wafer 5823 single board computer initialising.\n");
if (timeout < 1 || timeout > 255) {
timeout = WD_TIMO;
printk(KERN_INFO PFX
"timeout value must be 1 <= x <= 255, using %d\n",
timeout);
}
if (wdt_stop != wdt_start) {
if (!request_region(wdt_stop, 1, "Wafer 5823 WDT")) {
printk(KERN_ERR PFX
"I/O address 0x%04x already in use\n",
wdt_stop);
ret = -EIO;
goto error;
}
}
if (!request_region(wdt_start, 1, "Wafer 5823 WDT")) {
printk(KERN_ERR PFX "I/O address 0x%04x already in use\n",
wdt_start);
ret = -EIO;
goto error2;
}
ret = register_reboot_notifier(&wafwdt_notifier);
if (ret != 0) {
printk(KERN_ERR PFX
"cannot register reboot notifier (err=%d)\n", ret);
goto error3;
}
ret = misc_register(&wafwdt_miscdev);
if (ret != 0) {
printk(KERN_ERR PFX
"cannot register miscdev on minor=%d (err=%d)\n",
WATCHDOG_MINOR, ret);
goto error4;
}
printk(KERN_INFO PFX "initialized. timeout=%d sec (nowayout=%d)\n",
timeout, nowayout);
return ret;
error4:
unregister_reboot_notifier(&wafwdt_notifier);
error3:
release_region(wdt_start, 1);
error2:
if (wdt_stop != wdt_start)
release_region(wdt_stop, 1);
error:
return ret;
}
static void __exit wafwdt_exit(void)
{
misc_deregister(&wafwdt_miscdev);
unregister_reboot_notifier(&wafwdt_notifier);
if (wdt_stop != wdt_start)
release_region(wdt_stop, 1);
release_region(wdt_start, 1);
}
module_init(wafwdt_init);
module_exit(wafwdt_exit);
MODULE_AUTHOR("Justin Cormack");
MODULE_DESCRIPTION("ICP Wafer 5823 Single Board Computer WDT driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
/* end of wafer5823wdt.c */
| gpl-2.0 |
LeroViten/LerNex-Ancora-Kernel | drivers/usb/misc/cypress_cy7c63.c | 7560 | 7282 | /*
* cypress_cy7c63.c
*
* Copyright (c) 2006-2007 Oliver Bock (bock@tfh-berlin.de)
*
* This driver is based on the Cypress USB Driver by Marcus Maul
* (cyport) and the 2.0 version of Greg Kroah-Hartman's
* USB Skeleton driver.
*
* This is a generic driver for the Cypress CY7C63xxx family.
* For the time being it enables you to read from and write to
* the single I/O ports of the device.
*
* Supported vendors: AK Modul-Bus Computer GmbH
* (Firmware "Port-Chip")
*
* Supported devices: CY7C63001A-PC
* CY7C63001C-PXC
* CY7C63001C-SXC
*
* Supported functions: Read/Write Ports
*
*
* For up-to-date information please visit:
* http://www.obock.de/kernel/cypress
*
* 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/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/usb.h>
#define DRIVER_AUTHOR "Oliver Bock (bock@tfh-berlin.de)"
#define DRIVER_DESC "Cypress CY7C63xxx USB driver"
#define CYPRESS_VENDOR_ID 0xa2c
#define CYPRESS_PRODUCT_ID 0x8
#define CYPRESS_READ_PORT 0x4
#define CYPRESS_WRITE_PORT 0x5
#define CYPRESS_READ_RAM 0x2
#define CYPRESS_WRITE_RAM 0x3
#define CYPRESS_READ_ROM 0x1
#define CYPRESS_READ_PORT_ID0 0
#define CYPRESS_WRITE_PORT_ID0 0
#define CYPRESS_READ_PORT_ID1 0x2
#define CYPRESS_WRITE_PORT_ID1 1
#define CYPRESS_MAX_REQSIZE 8
/* table of devices that work with this driver */
static const struct usb_device_id cypress_table[] = {
{ USB_DEVICE(CYPRESS_VENDOR_ID, CYPRESS_PRODUCT_ID) },
{ }
};
MODULE_DEVICE_TABLE(usb, cypress_table);
/* structure to hold all of our device specific stuff */
struct cypress {
struct usb_device * udev;
unsigned char port[2];
};
/* used to send usb control messages to device */
static int vendor_command(struct cypress *dev, unsigned char request,
unsigned char address, unsigned char data)
{
int retval = 0;
unsigned int pipe;
unsigned char *iobuf;
/* allocate some memory for the i/o buffer*/
iobuf = kzalloc(CYPRESS_MAX_REQSIZE, GFP_KERNEL);
if (!iobuf) {
dev_err(&dev->udev->dev, "Out of memory!\n");
retval = -ENOMEM;
goto error;
}
dev_dbg(&dev->udev->dev, "Sending usb_control_msg (data: %d)\n", data);
/* prepare usb control message and send it upstream */
pipe = usb_rcvctrlpipe(dev->udev, 0);
retval = usb_control_msg(dev->udev, pipe, request,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_OTHER,
address, data, iobuf, CYPRESS_MAX_REQSIZE,
USB_CTRL_GET_TIMEOUT);
/* store returned data (more READs to be added) */
switch (request) {
case CYPRESS_READ_PORT:
if (address == CYPRESS_READ_PORT_ID0) {
dev->port[0] = iobuf[1];
dev_dbg(&dev->udev->dev,
"READ_PORT0 returned: %d\n",
dev->port[0]);
}
else if (address == CYPRESS_READ_PORT_ID1) {
dev->port[1] = iobuf[1];
dev_dbg(&dev->udev->dev,
"READ_PORT1 returned: %d\n",
dev->port[1]);
}
break;
}
kfree(iobuf);
error:
return retval;
}
/* write port value */
static ssize_t write_port(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count,
int port_num, int write_id)
{
int value = -1;
int result = 0;
struct usb_interface *intf = to_usb_interface(dev);
struct cypress *cyp = usb_get_intfdata(intf);
dev_dbg(&cyp->udev->dev, "WRITE_PORT%d called\n", port_num);
/* validate input data */
if (sscanf(buf, "%d", &value) < 1) {
result = -EINVAL;
goto error;
}
if (value < 0 || value > 255) {
result = -EINVAL;
goto error;
}
result = vendor_command(cyp, CYPRESS_WRITE_PORT, write_id,
(unsigned char)value);
dev_dbg(&cyp->udev->dev, "Result of vendor_command: %d\n\n", result);
error:
return result < 0 ? result : count;
}
/* attribute callback handler (write) */
static ssize_t set_port0_handler(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return write_port(dev, attr, buf, count, 0, CYPRESS_WRITE_PORT_ID0);
}
/* attribute callback handler (write) */
static ssize_t set_port1_handler(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return write_port(dev, attr, buf, count, 1, CYPRESS_WRITE_PORT_ID1);
}
/* read port value */
static ssize_t read_port(struct device *dev, struct device_attribute *attr,
char *buf, int port_num, int read_id)
{
int result = 0;
struct usb_interface *intf = to_usb_interface(dev);
struct cypress *cyp = usb_get_intfdata(intf);
dev_dbg(&cyp->udev->dev, "READ_PORT%d called\n", port_num);
result = vendor_command(cyp, CYPRESS_READ_PORT, read_id, 0);
dev_dbg(&cyp->udev->dev, "Result of vendor_command: %d\n\n", result);
return sprintf(buf, "%d", cyp->port[port_num]);
}
/* attribute callback handler (read) */
static ssize_t get_port0_handler(struct device *dev,
struct device_attribute *attr, char *buf)
{
return read_port(dev, attr, buf, 0, CYPRESS_READ_PORT_ID0);
}
/* attribute callback handler (read) */
static ssize_t get_port1_handler(struct device *dev,
struct device_attribute *attr, char *buf)
{
return read_port(dev, attr, buf, 1, CYPRESS_READ_PORT_ID1);
}
static DEVICE_ATTR(port0, S_IRUGO | S_IWUSR, get_port0_handler, set_port0_handler);
static DEVICE_ATTR(port1, S_IRUGO | S_IWUSR, get_port1_handler, set_port1_handler);
static int cypress_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct cypress *dev = NULL;
int retval = -ENOMEM;
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (dev == NULL) {
dev_err(&interface->dev, "Out of memory!\n");
goto error_mem;
}
dev->udev = usb_get_dev(interface_to_usbdev(interface));
/* save our data pointer in this interface device */
usb_set_intfdata(interface, dev);
/* create device attribute files */
retval = device_create_file(&interface->dev, &dev_attr_port0);
if (retval)
goto error;
retval = device_create_file(&interface->dev, &dev_attr_port1);
if (retval)
goto error;
/* let the user know that the device is now attached */
dev_info(&interface->dev,
"Cypress CY7C63xxx device now attached\n");
return 0;
error:
device_remove_file(&interface->dev, &dev_attr_port0);
device_remove_file(&interface->dev, &dev_attr_port1);
usb_set_intfdata(interface, NULL);
usb_put_dev(dev->udev);
kfree(dev);
error_mem:
return retval;
}
static void cypress_disconnect(struct usb_interface *interface)
{
struct cypress *dev;
dev = usb_get_intfdata(interface);
/* remove device attribute files */
device_remove_file(&interface->dev, &dev_attr_port0);
device_remove_file(&interface->dev, &dev_attr_port1);
/* the intfdata can be set to NULL only after the
* device files have been removed */
usb_set_intfdata(interface, NULL);
usb_put_dev(dev->udev);
dev_info(&interface->dev,
"Cypress CY7C63xxx device now disconnected\n");
kfree(dev);
}
static struct usb_driver cypress_driver = {
.name = "cypress_cy7c63",
.probe = cypress_probe,
.disconnect = cypress_disconnect,
.id_table = cypress_table,
};
module_usb_driver(cypress_driver);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
| gpl-2.0 |
dtsinc/DTS-Sound-Integration_CAF-Android-kernel | sound/pci/asihpi/hpimsginit.c | 8328 | 3612 | /******************************************************************************
AudioScience HPI driver
Copyright (C) 1997-2011 AudioScience Inc. <support@audioscience.com>
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation;
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Hardware Programming Interface (HPI) Utility functions.
(C) Copyright AudioScience Inc. 2007
*******************************************************************************/
#include "hpi_internal.h"
#include "hpimsginit.h"
/* The actual message size for each object type */
static u16 msg_size[HPI_OBJ_MAXINDEX + 1] = HPI_MESSAGE_SIZE_BY_OBJECT;
/* The actual response size for each object type */
static u16 res_size[HPI_OBJ_MAXINDEX + 1] = HPI_RESPONSE_SIZE_BY_OBJECT;
/* Flag to enable alternate message type for SSX2 bypass. */
static u16 gwSSX2_bypass;
/** \internal
* initialize the HPI message structure
*/
static void hpi_init_message(struct hpi_message *phm, u16 object,
u16 function)
{
memset(phm, 0, sizeof(*phm));
if ((object > 0) && (object <= HPI_OBJ_MAXINDEX))
phm->size = msg_size[object];
else
phm->size = sizeof(*phm);
if (gwSSX2_bypass)
phm->type = HPI_TYPE_SSX2BYPASS_MESSAGE;
else
phm->type = HPI_TYPE_REQUEST;
phm->object = object;
phm->function = function;
phm->version = 0;
phm->adapter_index = HPI_ADAPTER_INDEX_INVALID;
/* Expect actual adapter index to be set by caller */
}
/** \internal
* initialize the HPI response structure
*/
void hpi_init_response(struct hpi_response *phr, u16 object, u16 function,
u16 error)
{
memset(phr, 0, sizeof(*phr));
phr->type = HPI_TYPE_RESPONSE;
if ((object > 0) && (object <= HPI_OBJ_MAXINDEX))
phr->size = res_size[object];
else
phr->size = sizeof(*phr);
phr->object = object;
phr->function = function;
phr->error = error;
phr->specific_error = 0;
phr->version = 0;
}
void hpi_init_message_response(struct hpi_message *phm,
struct hpi_response *phr, u16 object, u16 function)
{
hpi_init_message(phm, object, function);
/* default error return if the response is
not filled in by the callee */
hpi_init_response(phr, object, function,
HPI_ERROR_PROCESSING_MESSAGE);
}
static void hpi_init_messageV1(struct hpi_message_header *phm, u16 size,
u16 object, u16 function)
{
memset(phm, 0, sizeof(*phm));
if ((object > 0) && (object <= HPI_OBJ_MAXINDEX)) {
phm->size = size;
phm->type = HPI_TYPE_REQUEST;
phm->object = object;
phm->function = function;
phm->version = 1;
/* Expect adapter index to be set by caller */
}
}
void hpi_init_responseV1(struct hpi_response_header *phr, u16 size,
u16 object, u16 function)
{
memset(phr, 0, sizeof(*phr));
phr->size = size;
phr->version = 1;
phr->type = HPI_TYPE_RESPONSE;
phr->error = HPI_ERROR_PROCESSING_MESSAGE;
}
void hpi_init_message_responseV1(struct hpi_message_header *phm, u16 msg_size,
struct hpi_response_header *phr, u16 res_size, u16 object,
u16 function)
{
hpi_init_messageV1(phm, msg_size, object, function);
hpi_init_responseV1(phr, res_size, object, function);
}
| gpl-2.0 |
intervigilium/android_kernel_htc_msm8960 | drivers/scsi/imm.c | 8328 | 29624 | /* imm.c -- low level driver for the IOMEGA MatchMaker
* parallel port SCSI host adapter.
*
* (The IMM is the embedded controller in the ZIP Plus drive.)
*
* My unofficial company acronym list is 21 pages long:
* FLA: Four letter acronym with built in facility for
* future expansion to five letters.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/parport.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
/* The following #define is to avoid a clash with hosts.c */
#define IMM_PROBE_SPP 0x0001
#define IMM_PROBE_PS2 0x0002
#define IMM_PROBE_ECR 0x0010
#define IMM_PROBE_EPP17 0x0100
#define IMM_PROBE_EPP19 0x0200
typedef struct {
struct pardevice *dev; /* Parport device entry */
int base; /* Actual port address */
int base_hi; /* Hi Base address for ECP-ISA chipset */
int mode; /* Transfer mode */
struct scsi_cmnd *cur_cmd; /* Current queued command */
struct delayed_work imm_tq; /* Polling interrupt stuff */
unsigned long jstart; /* Jiffies at start */
unsigned failed:1; /* Failure flag */
unsigned dp:1; /* Data phase present */
unsigned rd:1; /* Read data in data phase */
unsigned wanted:1; /* Parport sharing busy flag */
wait_queue_head_t *waiting;
struct Scsi_Host *host;
struct list_head list;
} imm_struct;
static void imm_reset_pulse(unsigned int base);
static int device_check(imm_struct *dev);
#include "imm.h"
static inline imm_struct *imm_dev(struct Scsi_Host *host)
{
return *(imm_struct **)&host->hostdata;
}
static DEFINE_SPINLOCK(arbitration_lock);
static void got_it(imm_struct *dev)
{
dev->base = dev->dev->port->base;
if (dev->cur_cmd)
dev->cur_cmd->SCp.phase = 1;
else
wake_up(dev->waiting);
}
static void imm_wakeup(void *ref)
{
imm_struct *dev = (imm_struct *) ref;
unsigned long flags;
spin_lock_irqsave(&arbitration_lock, flags);
if (dev->wanted) {
parport_claim(dev->dev);
got_it(dev);
dev->wanted = 0;
}
spin_unlock_irqrestore(&arbitration_lock, flags);
}
static int imm_pb_claim(imm_struct *dev)
{
unsigned long flags;
int res = 1;
spin_lock_irqsave(&arbitration_lock, flags);
if (parport_claim(dev->dev) == 0) {
got_it(dev);
res = 0;
}
dev->wanted = res;
spin_unlock_irqrestore(&arbitration_lock, flags);
return res;
}
static void imm_pb_dismiss(imm_struct *dev)
{
unsigned long flags;
int wanted;
spin_lock_irqsave(&arbitration_lock, flags);
wanted = dev->wanted;
dev->wanted = 0;
spin_unlock_irqrestore(&arbitration_lock, flags);
if (!wanted)
parport_release(dev->dev);
}
static inline void imm_pb_release(imm_struct *dev)
{
parport_release(dev->dev);
}
/* This is to give the imm driver a way to modify the timings (and other
* parameters) by writing to the /proc/scsi/imm/0 file.
* Very simple method really... (Too simple, no error checking :( )
* Reason: Kernel hackers HATE having to unload and reload modules for
* testing...
* Also gives a method to use a script to obtain optimum timings (TODO)
*/
static inline int imm_proc_write(imm_struct *dev, char *buffer, int length)
{
unsigned long x;
if ((length > 5) && (strncmp(buffer, "mode=", 5) == 0)) {
x = simple_strtoul(buffer + 5, NULL, 0);
dev->mode = x;
return length;
}
printk("imm /proc: invalid variable\n");
return (-EINVAL);
}
static int imm_proc_info(struct Scsi_Host *host, char *buffer, char **start,
off_t offset, int length, int inout)
{
imm_struct *dev = imm_dev(host);
int len = 0;
if (inout)
return imm_proc_write(dev, buffer, length);
len += sprintf(buffer + len, "Version : %s\n", IMM_VERSION);
len +=
sprintf(buffer + len, "Parport : %s\n",
dev->dev->port->name);
len +=
sprintf(buffer + len, "Mode : %s\n",
IMM_MODE_STRING[dev->mode]);
/* Request for beyond end of buffer */
if (offset > len)
return 0;
*start = buffer + offset;
len -= offset;
if (len > length)
len = length;
return len;
}
#if IMM_DEBUG > 0
#define imm_fail(x,y) printk("imm: imm_fail(%i) from %s at line %d\n",\
y, __func__, __LINE__); imm_fail_func(x,y);
static inline void
imm_fail_func(imm_struct *dev, int error_code)
#else
static inline void
imm_fail(imm_struct *dev, int error_code)
#endif
{
/* If we fail a device then we trash status / message bytes */
if (dev->cur_cmd) {
dev->cur_cmd->result = error_code << 16;
dev->failed = 1;
}
}
/*
* Wait for the high bit to be set.
*
* In principle, this could be tied to an interrupt, but the adapter
* doesn't appear to be designed to support interrupts. We spin on
* the 0x80 ready bit.
*/
static unsigned char imm_wait(imm_struct *dev)
{
int k;
unsigned short ppb = dev->base;
unsigned char r;
w_ctr(ppb, 0x0c);
k = IMM_SPIN_TMO;
do {
r = r_str(ppb);
k--;
udelay(1);
}
while (!(r & 0x80) && (k));
/*
* STR register (LPT base+1) to SCSI mapping:
*
* STR imm imm
* ===================================
* 0x80 S_REQ S_REQ
* 0x40 !S_BSY (????)
* 0x20 !S_CD !S_CD
* 0x10 !S_IO !S_IO
* 0x08 (????) !S_BSY
*
* imm imm meaning
* ==================================
* 0xf0 0xb8 Bit mask
* 0xc0 0x88 ZIP wants more data
* 0xd0 0x98 ZIP wants to send more data
* 0xe0 0xa8 ZIP is expecting SCSI command data
* 0xf0 0xb8 end of transfer, ZIP is sending status
*/
w_ctr(ppb, 0x04);
if (k)
return (r & 0xb8);
/* Counter expired - Time out occurred */
imm_fail(dev, DID_TIME_OUT);
printk("imm timeout in imm_wait\n");
return 0; /* command timed out */
}
static int imm_negotiate(imm_struct * tmp)
{
/*
* The following is supposedly the IEEE 1284-1994 negotiate
* sequence. I have yet to obtain a copy of the above standard
* so this is a bit of a guess...
*
* A fair chunk of this is based on the Linux parport implementation
* of IEEE 1284.
*
* Return 0 if data available
* 1 if no data available
*/
unsigned short base = tmp->base;
unsigned char a, mode;
switch (tmp->mode) {
case IMM_NIBBLE:
mode = 0x00;
break;
case IMM_PS2:
mode = 0x01;
break;
default:
return 0;
}
w_ctr(base, 0x04);
udelay(5);
w_dtr(base, mode);
udelay(100);
w_ctr(base, 0x06);
udelay(5);
a = (r_str(base) & 0x20) ? 0 : 1;
udelay(5);
w_ctr(base, 0x07);
udelay(5);
w_ctr(base, 0x06);
if (a) {
printk
("IMM: IEEE1284 negotiate indicates no data available.\n");
imm_fail(tmp, DID_ERROR);
}
return a;
}
/*
* Clear EPP timeout bit.
*/
static inline void epp_reset(unsigned short ppb)
{
int i;
i = r_str(ppb);
w_str(ppb, i);
w_str(ppb, i & 0xfe);
}
/*
* Wait for empty ECP fifo (if we are in ECP fifo mode only)
*/
static inline void ecp_sync(imm_struct *dev)
{
int i, ppb_hi = dev->base_hi;
if (ppb_hi == 0)
return;
if ((r_ecr(ppb_hi) & 0xe0) == 0x60) { /* mode 011 == ECP fifo mode */
for (i = 0; i < 100; i++) {
if (r_ecr(ppb_hi) & 0x01)
return;
udelay(5);
}
printk("imm: ECP sync failed as data still present in FIFO.\n");
}
}
static int imm_byte_out(unsigned short base, const char *buffer, int len)
{
int i;
w_ctr(base, 0x4); /* apparently a sane mode */
for (i = len >> 1; i; i--) {
w_dtr(base, *buffer++);
w_ctr(base, 0x5); /* Drop STROBE low */
w_dtr(base, *buffer++);
w_ctr(base, 0x0); /* STROBE high + INIT low */
}
w_ctr(base, 0x4); /* apparently a sane mode */
return 1; /* All went well - we hope! */
}
static int imm_nibble_in(unsigned short base, char *buffer, int len)
{
unsigned char l;
int i;
/*
* The following is based on documented timing signals
*/
w_ctr(base, 0x4);
for (i = len; i; i--) {
w_ctr(base, 0x6);
l = (r_str(base) & 0xf0) >> 4;
w_ctr(base, 0x5);
*buffer++ = (r_str(base) & 0xf0) | l;
w_ctr(base, 0x4);
}
return 1; /* All went well - we hope! */
}
static int imm_byte_in(unsigned short base, char *buffer, int len)
{
int i;
/*
* The following is based on documented timing signals
*/
w_ctr(base, 0x4);
for (i = len; i; i--) {
w_ctr(base, 0x26);
*buffer++ = r_dtr(base);
w_ctr(base, 0x25);
}
return 1; /* All went well - we hope! */
}
static int imm_out(imm_struct *dev, char *buffer, int len)
{
unsigned short ppb = dev->base;
int r = imm_wait(dev);
/*
* Make sure that:
* a) the SCSI bus is BUSY (device still listening)
* b) the device is listening
*/
if ((r & 0x18) != 0x08) {
imm_fail(dev, DID_ERROR);
printk("IMM: returned SCSI status %2x\n", r);
return 0;
}
switch (dev->mode) {
case IMM_EPP_32:
case IMM_EPP_16:
case IMM_EPP_8:
epp_reset(ppb);
w_ctr(ppb, 0x4);
#ifdef CONFIG_SCSI_IZIP_EPP16
if (!(((long) buffer | len) & 0x01))
outsw(ppb + 4, buffer, len >> 1);
#else
if (!(((long) buffer | len) & 0x03))
outsl(ppb + 4, buffer, len >> 2);
#endif
else
outsb(ppb + 4, buffer, len);
w_ctr(ppb, 0xc);
r = !(r_str(ppb) & 0x01);
w_ctr(ppb, 0xc);
ecp_sync(dev);
break;
case IMM_NIBBLE:
case IMM_PS2:
/* 8 bit output, with a loop */
r = imm_byte_out(ppb, buffer, len);
break;
default:
printk("IMM: bug in imm_out()\n");
r = 0;
}
return r;
}
static int imm_in(imm_struct *dev, char *buffer, int len)
{
unsigned short ppb = dev->base;
int r = imm_wait(dev);
/*
* Make sure that:
* a) the SCSI bus is BUSY (device still listening)
* b) the device is sending data
*/
if ((r & 0x18) != 0x18) {
imm_fail(dev, DID_ERROR);
return 0;
}
switch (dev->mode) {
case IMM_NIBBLE:
/* 4 bit input, with a loop */
r = imm_nibble_in(ppb, buffer, len);
w_ctr(ppb, 0xc);
break;
case IMM_PS2:
/* 8 bit input, with a loop */
r = imm_byte_in(ppb, buffer, len);
w_ctr(ppb, 0xc);
break;
case IMM_EPP_32:
case IMM_EPP_16:
case IMM_EPP_8:
epp_reset(ppb);
w_ctr(ppb, 0x24);
#ifdef CONFIG_SCSI_IZIP_EPP16
if (!(((long) buffer | len) & 0x01))
insw(ppb + 4, buffer, len >> 1);
#else
if (!(((long) buffer | len) & 0x03))
insl(ppb + 4, buffer, len >> 2);
#endif
else
insb(ppb + 4, buffer, len);
w_ctr(ppb, 0x2c);
r = !(r_str(ppb) & 0x01);
w_ctr(ppb, 0x2c);
ecp_sync(dev);
break;
default:
printk("IMM: bug in imm_ins()\n");
r = 0;
break;
}
return r;
}
static int imm_cpp(unsigned short ppb, unsigned char b)
{
/*
* Comments on udelay values refer to the
* Command Packet Protocol (CPP) timing diagram.
*/
unsigned char s1, s2, s3;
w_ctr(ppb, 0x0c);
udelay(2); /* 1 usec - infinite */
w_dtr(ppb, 0xaa);
udelay(10); /* 7 usec - infinite */
w_dtr(ppb, 0x55);
udelay(10); /* 7 usec - infinite */
w_dtr(ppb, 0x00);
udelay(10); /* 7 usec - infinite */
w_dtr(ppb, 0xff);
udelay(10); /* 7 usec - infinite */
s1 = r_str(ppb) & 0xb8;
w_dtr(ppb, 0x87);
udelay(10); /* 7 usec - infinite */
s2 = r_str(ppb) & 0xb8;
w_dtr(ppb, 0x78);
udelay(10); /* 7 usec - infinite */
s3 = r_str(ppb) & 0x38;
/*
* Values for b are:
* 0000 00aa Assign address aa to current device
* 0010 00aa Select device aa in EPP Winbond mode
* 0010 10aa Select device aa in EPP mode
* 0011 xxxx Deselect all devices
* 0110 00aa Test device aa
* 1101 00aa Select device aa in ECP mode
* 1110 00aa Select device aa in Compatible mode
*/
w_dtr(ppb, b);
udelay(2); /* 1 usec - infinite */
w_ctr(ppb, 0x0c);
udelay(10); /* 7 usec - infinite */
w_ctr(ppb, 0x0d);
udelay(2); /* 1 usec - infinite */
w_ctr(ppb, 0x0c);
udelay(10); /* 7 usec - infinite */
w_dtr(ppb, 0xff);
udelay(10); /* 7 usec - infinite */
/*
* The following table is electrical pin values.
* (BSY is inverted at the CTR register)
*
* BSY ACK POut SEL Fault
* S1 0 X 1 1 1
* S2 1 X 0 1 1
* S3 L X 1 1 S
*
* L => Last device in chain
* S => Selected
*
* Observered values for S1,S2,S3 are:
* Disconnect => f8/58/78
* Connect => f8/58/70
*/
if ((s1 == 0xb8) && (s2 == 0x18) && (s3 == 0x30))
return 1; /* Connected */
if ((s1 == 0xb8) && (s2 == 0x18) && (s3 == 0x38))
return 0; /* Disconnected */
return -1; /* No device present */
}
static inline int imm_connect(imm_struct *dev, int flag)
{
unsigned short ppb = dev->base;
imm_cpp(ppb, 0xe0); /* Select device 0 in compatible mode */
imm_cpp(ppb, 0x30); /* Disconnect all devices */
if ((dev->mode == IMM_EPP_8) ||
(dev->mode == IMM_EPP_16) ||
(dev->mode == IMM_EPP_32))
return imm_cpp(ppb, 0x28); /* Select device 0 in EPP mode */
return imm_cpp(ppb, 0xe0); /* Select device 0 in compatible mode */
}
static void imm_disconnect(imm_struct *dev)
{
imm_cpp(dev->base, 0x30); /* Disconnect all devices */
}
static int imm_select(imm_struct *dev, int target)
{
int k;
unsigned short ppb = dev->base;
/*
* Firstly we want to make sure there is nothing
* holding onto the SCSI bus.
*/
w_ctr(ppb, 0xc);
k = IMM_SELECT_TMO;
do {
k--;
} while ((r_str(ppb) & 0x08) && (k));
if (!k)
return 0;
/*
* Now assert the SCSI ID (HOST and TARGET) on the data bus
*/
w_ctr(ppb, 0x4);
w_dtr(ppb, 0x80 | (1 << target));
udelay(1);
/*
* Deassert SELIN first followed by STROBE
*/
w_ctr(ppb, 0xc);
w_ctr(ppb, 0xd);
/*
* ACK should drop low while SELIN is deasserted.
* FAULT should drop low when the SCSI device latches the bus.
*/
k = IMM_SELECT_TMO;
do {
k--;
}
while (!(r_str(ppb) & 0x08) && (k));
/*
* Place the interface back into a sane state (status mode)
*/
w_ctr(ppb, 0xc);
return (k) ? 1 : 0;
}
static int imm_init(imm_struct *dev)
{
if (imm_connect(dev, 0) != 1)
return -EIO;
imm_reset_pulse(dev->base);
mdelay(1); /* Delay to allow devices to settle */
imm_disconnect(dev);
mdelay(1); /* Another delay to allow devices to settle */
return device_check(dev);
}
static inline int imm_send_command(struct scsi_cmnd *cmd)
{
imm_struct *dev = imm_dev(cmd->device->host);
int k;
/* NOTE: IMM uses byte pairs */
for (k = 0; k < cmd->cmd_len; k += 2)
if (!imm_out(dev, &cmd->cmnd[k], 2))
return 0;
return 1;
}
/*
* The bulk flag enables some optimisations in the data transfer loops,
* it should be true for any command that transfers data in integral
* numbers of sectors.
*
* The driver appears to remain stable if we speed up the parallel port
* i/o in this function, but not elsewhere.
*/
static int imm_completion(struct scsi_cmnd *cmd)
{
/* Return codes:
* -1 Error
* 0 Told to schedule
* 1 Finished data transfer
*/
imm_struct *dev = imm_dev(cmd->device->host);
unsigned short ppb = dev->base;
unsigned long start_jiffies = jiffies;
unsigned char r, v;
int fast, bulk, status;
v = cmd->cmnd[0];
bulk = ((v == READ_6) ||
(v == READ_10) || (v == WRITE_6) || (v == WRITE_10));
/*
* We only get here if the drive is ready to comunicate,
* hence no need for a full imm_wait.
*/
w_ctr(ppb, 0x0c);
r = (r_str(ppb) & 0xb8);
/*
* while (device is not ready to send status byte)
* loop;
*/
while (r != (unsigned char) 0xb8) {
/*
* If we have been running for more than a full timer tick
* then take a rest.
*/
if (time_after(jiffies, start_jiffies + 1))
return 0;
/*
* FAIL if:
* a) Drive status is screwy (!ready && !present)
* b) Drive is requesting/sending more data than expected
*/
if (((r & 0x88) != 0x88) || (cmd->SCp.this_residual <= 0)) {
imm_fail(dev, DID_ERROR);
return -1; /* ERROR_RETURN */
}
/* determine if we should use burst I/O */
if (dev->rd == 0) {
fast = (bulk
&& (cmd->SCp.this_residual >=
IMM_BURST_SIZE)) ? IMM_BURST_SIZE : 2;
status = imm_out(dev, cmd->SCp.ptr, fast);
} else {
fast = (bulk
&& (cmd->SCp.this_residual >=
IMM_BURST_SIZE)) ? IMM_BURST_SIZE : 1;
status = imm_in(dev, cmd->SCp.ptr, fast);
}
cmd->SCp.ptr += fast;
cmd->SCp.this_residual -= fast;
if (!status) {
imm_fail(dev, DID_BUS_BUSY);
return -1; /* ERROR_RETURN */
}
if (cmd->SCp.buffer && !cmd->SCp.this_residual) {
/* if scatter/gather, advance to the next segment */
if (cmd->SCp.buffers_residual--) {
cmd->SCp.buffer++;
cmd->SCp.this_residual =
cmd->SCp.buffer->length;
cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
/*
* Make sure that we transfer even number of bytes
* otherwise it makes imm_byte_out() messy.
*/
if (cmd->SCp.this_residual & 0x01)
cmd->SCp.this_residual++;
}
}
/* Now check to see if the drive is ready to comunicate */
w_ctr(ppb, 0x0c);
r = (r_str(ppb) & 0xb8);
/* If not, drop back down to the scheduler and wait a timer tick */
if (!(r & 0x80))
return 0;
}
return 1; /* FINISH_RETURN */
}
/*
* Since the IMM itself doesn't generate interrupts, we use
* the scheduler's task queue to generate a stream of call-backs and
* complete the request when the drive is ready.
*/
static void imm_interrupt(struct work_struct *work)
{
imm_struct *dev = container_of(work, imm_struct, imm_tq.work);
struct scsi_cmnd *cmd = dev->cur_cmd;
struct Scsi_Host *host = cmd->device->host;
unsigned long flags;
if (imm_engine(dev, cmd)) {
schedule_delayed_work(&dev->imm_tq, 1);
return;
}
/* Command must of completed hence it is safe to let go... */
#if IMM_DEBUG > 0
switch ((cmd->result >> 16) & 0xff) {
case DID_OK:
break;
case DID_NO_CONNECT:
printk("imm: no device at SCSI ID %i\n", cmd->device->id);
break;
case DID_BUS_BUSY:
printk("imm: BUS BUSY - EPP timeout detected\n");
break;
case DID_TIME_OUT:
printk("imm: unknown timeout\n");
break;
case DID_ABORT:
printk("imm: told to abort\n");
break;
case DID_PARITY:
printk("imm: parity error (???)\n");
break;
case DID_ERROR:
printk("imm: internal driver error\n");
break;
case DID_RESET:
printk("imm: told to reset device\n");
break;
case DID_BAD_INTR:
printk("imm: bad interrupt (???)\n");
break;
default:
printk("imm: bad return code (%02x)\n",
(cmd->result >> 16) & 0xff);
}
#endif
if (cmd->SCp.phase > 1)
imm_disconnect(dev);
imm_pb_dismiss(dev);
spin_lock_irqsave(host->host_lock, flags);
dev->cur_cmd = NULL;
cmd->scsi_done(cmd);
spin_unlock_irqrestore(host->host_lock, flags);
return;
}
static int imm_engine(imm_struct *dev, struct scsi_cmnd *cmd)
{
unsigned short ppb = dev->base;
unsigned char l = 0, h = 0;
int retv, x;
/* First check for any errors that may have occurred
* Here we check for internal errors
*/
if (dev->failed)
return 0;
switch (cmd->SCp.phase) {
case 0: /* Phase 0 - Waiting for parport */
if (time_after(jiffies, dev->jstart + HZ)) {
/*
* We waited more than a second
* for parport to call us
*/
imm_fail(dev, DID_BUS_BUSY);
return 0;
}
return 1; /* wait until imm_wakeup claims parport */
/* Phase 1 - Connected */
case 1:
imm_connect(dev, CONNECT_EPP_MAYBE);
cmd->SCp.phase++;
/* Phase 2 - We are now talking to the scsi bus */
case 2:
if (!imm_select(dev, scmd_id(cmd))) {
imm_fail(dev, DID_NO_CONNECT);
return 0;
}
cmd->SCp.phase++;
/* Phase 3 - Ready to accept a command */
case 3:
w_ctr(ppb, 0x0c);
if (!(r_str(ppb) & 0x80))
return 1;
if (!imm_send_command(cmd))
return 0;
cmd->SCp.phase++;
/* Phase 4 - Setup scatter/gather buffers */
case 4:
if (scsi_bufflen(cmd)) {
cmd->SCp.buffer = scsi_sglist(cmd);
cmd->SCp.this_residual = cmd->SCp.buffer->length;
cmd->SCp.ptr = sg_virt(cmd->SCp.buffer);
} else {
cmd->SCp.buffer = NULL;
cmd->SCp.this_residual = 0;
cmd->SCp.ptr = NULL;
}
cmd->SCp.buffers_residual = scsi_sg_count(cmd) - 1;
cmd->SCp.phase++;
if (cmd->SCp.this_residual & 0x01)
cmd->SCp.this_residual++;
/* Phase 5 - Pre-Data transfer stage */
case 5:
/* Spin lock for BUSY */
w_ctr(ppb, 0x0c);
if (!(r_str(ppb) & 0x80))
return 1;
/* Require negotiation for read requests */
x = (r_str(ppb) & 0xb8);
dev->rd = (x & 0x10) ? 1 : 0;
dev->dp = (x & 0x20) ? 0 : 1;
if ((dev->dp) && (dev->rd))
if (imm_negotiate(dev))
return 0;
cmd->SCp.phase++;
/* Phase 6 - Data transfer stage */
case 6:
/* Spin lock for BUSY */
w_ctr(ppb, 0x0c);
if (!(r_str(ppb) & 0x80))
return 1;
if (dev->dp) {
retv = imm_completion(cmd);
if (retv == -1)
return 0;
if (retv == 0)
return 1;
}
cmd->SCp.phase++;
/* Phase 7 - Post data transfer stage */
case 7:
if ((dev->dp) && (dev->rd)) {
if ((dev->mode == IMM_NIBBLE) || (dev->mode == IMM_PS2)) {
w_ctr(ppb, 0x4);
w_ctr(ppb, 0xc);
w_ctr(ppb, 0xe);
w_ctr(ppb, 0x4);
}
}
cmd->SCp.phase++;
/* Phase 8 - Read status/message */
case 8:
/* Check for data overrun */
if (imm_wait(dev) != (unsigned char) 0xb8) {
imm_fail(dev, DID_ERROR);
return 0;
}
if (imm_negotiate(dev))
return 0;
if (imm_in(dev, &l, 1)) { /* read status byte */
/* Check for optional message byte */
if (imm_wait(dev) == (unsigned char) 0xb8)
imm_in(dev, &h, 1);
cmd->result = (DID_OK << 16) + (l & STATUS_MASK);
}
if ((dev->mode == IMM_NIBBLE) || (dev->mode == IMM_PS2)) {
w_ctr(ppb, 0x4);
w_ctr(ppb, 0xc);
w_ctr(ppb, 0xe);
w_ctr(ppb, 0x4);
}
return 0; /* Finished */
break;
default:
printk("imm: Invalid scsi phase\n");
}
return 0;
}
static int imm_queuecommand_lck(struct scsi_cmnd *cmd,
void (*done)(struct scsi_cmnd *))
{
imm_struct *dev = imm_dev(cmd->device->host);
if (dev->cur_cmd) {
printk("IMM: bug in imm_queuecommand\n");
return 0;
}
dev->failed = 0;
dev->jstart = jiffies;
dev->cur_cmd = cmd;
cmd->scsi_done = done;
cmd->result = DID_ERROR << 16; /* default return code */
cmd->SCp.phase = 0; /* bus free */
schedule_delayed_work(&dev->imm_tq, 0);
imm_pb_claim(dev);
return 0;
}
static DEF_SCSI_QCMD(imm_queuecommand)
/*
* Apparently the disk->capacity attribute is off by 1 sector
* for all disk drives. We add the one here, but it should really
* be done in sd.c. Even if it gets fixed there, this will still
* work.
*/
static int imm_biosparam(struct scsi_device *sdev, struct block_device *dev,
sector_t capacity, int ip[])
{
ip[0] = 0x40;
ip[1] = 0x20;
ip[2] = ((unsigned long) capacity + 1) / (ip[0] * ip[1]);
if (ip[2] > 1024) {
ip[0] = 0xff;
ip[1] = 0x3f;
ip[2] = ((unsigned long) capacity + 1) / (ip[0] * ip[1]);
}
return 0;
}
static int imm_abort(struct scsi_cmnd *cmd)
{
imm_struct *dev = imm_dev(cmd->device->host);
/*
* There is no method for aborting commands since Iomega
* have tied the SCSI_MESSAGE line high in the interface
*/
switch (cmd->SCp.phase) {
case 0: /* Do not have access to parport */
case 1: /* Have not connected to interface */
dev->cur_cmd = NULL; /* Forget the problem */
return SUCCESS;
break;
default: /* SCSI command sent, can not abort */
return FAILED;
break;
}
}
static void imm_reset_pulse(unsigned int base)
{
w_ctr(base, 0x04);
w_dtr(base, 0x40);
udelay(1);
w_ctr(base, 0x0c);
w_ctr(base, 0x0d);
udelay(50);
w_ctr(base, 0x0c);
w_ctr(base, 0x04);
}
static int imm_reset(struct scsi_cmnd *cmd)
{
imm_struct *dev = imm_dev(cmd->device->host);
if (cmd->SCp.phase)
imm_disconnect(dev);
dev->cur_cmd = NULL; /* Forget the problem */
imm_connect(dev, CONNECT_NORMAL);
imm_reset_pulse(dev->base);
mdelay(1); /* device settle delay */
imm_disconnect(dev);
mdelay(1); /* device settle delay */
return SUCCESS;
}
static int device_check(imm_struct *dev)
{
/* This routine looks for a device and then attempts to use EPP
to send a command. If all goes as planned then EPP is available. */
static char cmd[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
int loop, old_mode, status, k, ppb = dev->base;
unsigned char l;
old_mode = dev->mode;
for (loop = 0; loop < 8; loop++) {
/* Attempt to use EPP for Test Unit Ready */
if ((ppb & 0x0007) == 0x0000)
dev->mode = IMM_EPP_32;
second_pass:
imm_connect(dev, CONNECT_EPP_MAYBE);
/* Select SCSI device */
if (!imm_select(dev, loop)) {
imm_disconnect(dev);
continue;
}
printk("imm: Found device at ID %i, Attempting to use %s\n",
loop, IMM_MODE_STRING[dev->mode]);
/* Send SCSI command */
status = 1;
w_ctr(ppb, 0x0c);
for (l = 0; (l < 3) && (status); l++)
status = imm_out(dev, &cmd[l << 1], 2);
if (!status) {
imm_disconnect(dev);
imm_connect(dev, CONNECT_EPP_MAYBE);
imm_reset_pulse(dev->base);
udelay(1000);
imm_disconnect(dev);
udelay(1000);
if (dev->mode == IMM_EPP_32) {
dev->mode = old_mode;
goto second_pass;
}
printk("imm: Unable to establish communication\n");
return -EIO;
}
w_ctr(ppb, 0x0c);
k = 1000000; /* 1 Second */
do {
l = r_str(ppb);
k--;
udelay(1);
} while (!(l & 0x80) && (k));
l &= 0xb8;
if (l != 0xb8) {
imm_disconnect(dev);
imm_connect(dev, CONNECT_EPP_MAYBE);
imm_reset_pulse(dev->base);
udelay(1000);
imm_disconnect(dev);
udelay(1000);
if (dev->mode == IMM_EPP_32) {
dev->mode = old_mode;
goto second_pass;
}
printk
("imm: Unable to establish communication\n");
return -EIO;
}
imm_disconnect(dev);
printk
("imm: Communication established at 0x%x with ID %i using %s\n",
ppb, loop, IMM_MODE_STRING[dev->mode]);
imm_connect(dev, CONNECT_EPP_MAYBE);
imm_reset_pulse(dev->base);
udelay(1000);
imm_disconnect(dev);
udelay(1000);
return 0;
}
printk("imm: No devices found\n");
return -ENODEV;
}
/*
* imm cannot deal with highmem, so this causes all IO pages for this host
* to reside in low memory (hence mapped)
*/
static int imm_adjust_queue(struct scsi_device *device)
{
blk_queue_bounce_limit(device->request_queue, BLK_BOUNCE_HIGH);
return 0;
}
static struct scsi_host_template imm_template = {
.module = THIS_MODULE,
.proc_name = "imm",
.proc_info = imm_proc_info,
.name = "Iomega VPI2 (imm) interface",
.queuecommand = imm_queuecommand,
.eh_abort_handler = imm_abort,
.eh_bus_reset_handler = imm_reset,
.eh_host_reset_handler = imm_reset,
.bios_param = imm_biosparam,
.this_id = 7,
.sg_tablesize = SG_ALL,
.cmd_per_lun = 1,
.use_clustering = ENABLE_CLUSTERING,
.can_queue = 1,
.slave_alloc = imm_adjust_queue,
};
/***************************************************************************
* Parallel port probing routines *
***************************************************************************/
static LIST_HEAD(imm_hosts);
static int __imm_attach(struct parport *pb)
{
struct Scsi_Host *host;
imm_struct *dev;
DECLARE_WAIT_QUEUE_HEAD_ONSTACK(waiting);
DEFINE_WAIT(wait);
int ports;
int modes, ppb;
int err = -ENOMEM;
init_waitqueue_head(&waiting);
dev = kzalloc(sizeof(imm_struct), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->base = -1;
dev->mode = IMM_AUTODETECT;
INIT_LIST_HEAD(&dev->list);
dev->dev = parport_register_device(pb, "imm", NULL, imm_wakeup,
NULL, 0, dev);
if (!dev->dev)
goto out;
/* Claim the bus so it remembers what we do to the control
* registers. [ CTR and ECP ]
*/
err = -EBUSY;
dev->waiting = &waiting;
prepare_to_wait(&waiting, &wait, TASK_UNINTERRUPTIBLE);
if (imm_pb_claim(dev))
schedule_timeout(3 * HZ);
if (dev->wanted) {
printk(KERN_ERR "imm%d: failed to claim parport because "
"a pardevice is owning the port for too long "
"time!\n", pb->number);
imm_pb_dismiss(dev);
dev->waiting = NULL;
finish_wait(&waiting, &wait);
goto out1;
}
dev->waiting = NULL;
finish_wait(&waiting, &wait);
ppb = dev->base = dev->dev->port->base;
dev->base_hi = dev->dev->port->base_hi;
w_ctr(ppb, 0x0c);
modes = dev->dev->port->modes;
/* Mode detection works up the chain of speed
* This avoids a nasty if-then-else-if-... tree
*/
dev->mode = IMM_NIBBLE;
if (modes & PARPORT_MODE_TRISTATE)
dev->mode = IMM_PS2;
/* Done configuration */
err = imm_init(dev);
imm_pb_release(dev);
if (err)
goto out1;
/* now the glue ... */
if (dev->mode == IMM_NIBBLE || dev->mode == IMM_PS2)
ports = 3;
else
ports = 8;
INIT_DELAYED_WORK(&dev->imm_tq, imm_interrupt);
err = -ENOMEM;
host = scsi_host_alloc(&imm_template, sizeof(imm_struct *));
if (!host)
goto out1;
host->io_port = pb->base;
host->n_io_port = ports;
host->dma_channel = -1;
host->unique_id = pb->number;
*(imm_struct **)&host->hostdata = dev;
dev->host = host;
list_add_tail(&dev->list, &imm_hosts);
err = scsi_add_host(host, NULL);
if (err)
goto out2;
scsi_scan_host(host);
return 0;
out2:
list_del_init(&dev->list);
scsi_host_put(host);
out1:
parport_unregister_device(dev->dev);
out:
kfree(dev);
return err;
}
static void imm_attach(struct parport *pb)
{
__imm_attach(pb);
}
static void imm_detach(struct parport *pb)
{
imm_struct *dev;
list_for_each_entry(dev, &imm_hosts, list) {
if (dev->dev->port == pb) {
list_del_init(&dev->list);
scsi_remove_host(dev->host);
scsi_host_put(dev->host);
parport_unregister_device(dev->dev);
kfree(dev);
break;
}
}
}
static struct parport_driver imm_driver = {
.name = "imm",
.attach = imm_attach,
.detach = imm_detach,
};
static int __init imm_driver_init(void)
{
printk("imm: Version %s\n", IMM_VERSION);
return parport_register_driver(&imm_driver);
}
static void __exit imm_driver_exit(void)
{
parport_unregister_driver(&imm_driver);
}
module_init(imm_driver_init);
module_exit(imm_driver_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
Elite-Kernels/Elite_angler | arch/alpha/lib/fpreg.c | 13704 | 6107 | /*
* arch/alpha/lib/fpreg.c
*
* (C) Copyright 1998 Linus Torvalds
*/
#if defined(CONFIG_ALPHA_EV6) || defined(CONFIG_ALPHA_EV67)
#define STT(reg,val) asm volatile ("ftoit $f"#reg",%0" : "=r"(val));
#else
#define STT(reg,val) asm volatile ("stt $f"#reg",%0" : "=m"(val));
#endif
unsigned long
alpha_read_fp_reg (unsigned long reg)
{
unsigned long val;
switch (reg) {
case 0: STT( 0, val); break;
case 1: STT( 1, val); break;
case 2: STT( 2, val); break;
case 3: STT( 3, val); break;
case 4: STT( 4, val); break;
case 5: STT( 5, val); break;
case 6: STT( 6, val); break;
case 7: STT( 7, val); break;
case 8: STT( 8, val); break;
case 9: STT( 9, val); break;
case 10: STT(10, val); break;
case 11: STT(11, val); break;
case 12: STT(12, val); break;
case 13: STT(13, val); break;
case 14: STT(14, val); break;
case 15: STT(15, val); break;
case 16: STT(16, val); break;
case 17: STT(17, val); break;
case 18: STT(18, val); break;
case 19: STT(19, val); break;
case 20: STT(20, val); break;
case 21: STT(21, val); break;
case 22: STT(22, val); break;
case 23: STT(23, val); break;
case 24: STT(24, val); break;
case 25: STT(25, val); break;
case 26: STT(26, val); break;
case 27: STT(27, val); break;
case 28: STT(28, val); break;
case 29: STT(29, val); break;
case 30: STT(30, val); break;
case 31: STT(31, val); break;
default: return 0;
}
return val;
}
#if defined(CONFIG_ALPHA_EV6) || defined(CONFIG_ALPHA_EV67)
#define LDT(reg,val) asm volatile ("itoft %0,$f"#reg : : "r"(val));
#else
#define LDT(reg,val) asm volatile ("ldt $f"#reg",%0" : : "m"(val));
#endif
void
alpha_write_fp_reg (unsigned long reg, unsigned long val)
{
switch (reg) {
case 0: LDT( 0, val); break;
case 1: LDT( 1, val); break;
case 2: LDT( 2, val); break;
case 3: LDT( 3, val); break;
case 4: LDT( 4, val); break;
case 5: LDT( 5, val); break;
case 6: LDT( 6, val); break;
case 7: LDT( 7, val); break;
case 8: LDT( 8, val); break;
case 9: LDT( 9, val); break;
case 10: LDT(10, val); break;
case 11: LDT(11, val); break;
case 12: LDT(12, val); break;
case 13: LDT(13, val); break;
case 14: LDT(14, val); break;
case 15: LDT(15, val); break;
case 16: LDT(16, val); break;
case 17: LDT(17, val); break;
case 18: LDT(18, val); break;
case 19: LDT(19, val); break;
case 20: LDT(20, val); break;
case 21: LDT(21, val); break;
case 22: LDT(22, val); break;
case 23: LDT(23, val); break;
case 24: LDT(24, val); break;
case 25: LDT(25, val); break;
case 26: LDT(26, val); break;
case 27: LDT(27, val); break;
case 28: LDT(28, val); break;
case 29: LDT(29, val); break;
case 30: LDT(30, val); break;
case 31: LDT(31, val); break;
}
}
#if defined(CONFIG_ALPHA_EV6) || defined(CONFIG_ALPHA_EV67)
#define STS(reg,val) asm volatile ("ftois $f"#reg",%0" : "=r"(val));
#else
#define STS(reg,val) asm volatile ("sts $f"#reg",%0" : "=m"(val));
#endif
unsigned long
alpha_read_fp_reg_s (unsigned long reg)
{
unsigned long val;
switch (reg) {
case 0: STS( 0, val); break;
case 1: STS( 1, val); break;
case 2: STS( 2, val); break;
case 3: STS( 3, val); break;
case 4: STS( 4, val); break;
case 5: STS( 5, val); break;
case 6: STS( 6, val); break;
case 7: STS( 7, val); break;
case 8: STS( 8, val); break;
case 9: STS( 9, val); break;
case 10: STS(10, val); break;
case 11: STS(11, val); break;
case 12: STS(12, val); break;
case 13: STS(13, val); break;
case 14: STS(14, val); break;
case 15: STS(15, val); break;
case 16: STS(16, val); break;
case 17: STS(17, val); break;
case 18: STS(18, val); break;
case 19: STS(19, val); break;
case 20: STS(20, val); break;
case 21: STS(21, val); break;
case 22: STS(22, val); break;
case 23: STS(23, val); break;
case 24: STS(24, val); break;
case 25: STS(25, val); break;
case 26: STS(26, val); break;
case 27: STS(27, val); break;
case 28: STS(28, val); break;
case 29: STS(29, val); break;
case 30: STS(30, val); break;
case 31: STS(31, val); break;
default: return 0;
}
return val;
}
#if defined(CONFIG_ALPHA_EV6) || defined(CONFIG_ALPHA_EV67)
#define LDS(reg,val) asm volatile ("itofs %0,$f"#reg : : "r"(val));
#else
#define LDS(reg,val) asm volatile ("lds $f"#reg",%0" : : "m"(val));
#endif
void
alpha_write_fp_reg_s (unsigned long reg, unsigned long val)
{
switch (reg) {
case 0: LDS( 0, val); break;
case 1: LDS( 1, val); break;
case 2: LDS( 2, val); break;
case 3: LDS( 3, val); break;
case 4: LDS( 4, val); break;
case 5: LDS( 5, val); break;
case 6: LDS( 6, val); break;
case 7: LDS( 7, val); break;
case 8: LDS( 8, val); break;
case 9: LDS( 9, val); break;
case 10: LDS(10, val); break;
case 11: LDS(11, val); break;
case 12: LDS(12, val); break;
case 13: LDS(13, val); break;
case 14: LDS(14, val); break;
case 15: LDS(15, val); break;
case 16: LDS(16, val); break;
case 17: LDS(17, val); break;
case 18: LDS(18, val); break;
case 19: LDS(19, val); break;
case 20: LDS(20, val); break;
case 21: LDS(21, val); break;
case 22: LDS(22, val); break;
case 23: LDS(23, val); break;
case 24: LDS(24, val); break;
case 25: LDS(25, val); break;
case 26: LDS(26, val); break;
case 27: LDS(27, val); break;
case 28: LDS(28, val); break;
case 29: LDS(29, val); break;
case 30: LDS(30, val); break;
case 31: LDS(31, val); break;
}
}
| gpl-2.0 |
dalingrin/Nook_Color_Kernel_Overclock | net/ipv4/icmp.c | 137 | 29038 | /*
* NET3: Implementation of the ICMP protocol layer.
*
* Alan Cox, <alan@lxorguk.ukuu.org.uk>
*
* 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.
*
* Some of the function names and the icmp unreach table for this
* module were derived from [icmp.c 1.0.11 06/02/93] by
* Ross Biro, Fred N. van Kempen, Mark Evans, Alan Cox, Gerhard Koerting.
* Other than that this module is a complete rewrite.
*
* Fixes:
* Clemens Fruhwirth : introduce global icmp rate limiting
* with icmp type masking ability instead
* of broken per type icmp timeouts.
* Mike Shaver : RFC1122 checks.
* Alan Cox : Multicast ping reply as self.
* Alan Cox : Fix atomicity lockup in ip_build_xmit
* call.
* Alan Cox : Added 216,128 byte paths to the MTU
* code.
* Martin Mares : RFC1812 checks.
* Martin Mares : Can be configured to follow redirects
* if acting as a router _without_ a
* routing protocol (RFC 1812).
* Martin Mares : Echo requests may be configured to
* be ignored (RFC 1812).
* Martin Mares : Limitation of ICMP error message
* transmit rate (RFC 1812).
* Martin Mares : TOS and Precedence set correctly
* (RFC 1812).
* Martin Mares : Now copying as much data from the
* original packet as we can without
* exceeding 576 bytes (RFC 1812).
* Willy Konynenberg : Transparent proxying support.
* Keith Owens : RFC1191 correction for 4.2BSD based
* path MTU bug.
* Thomas Quinot : ICMP Dest Unreach codes up to 15 are
* valid (RFC 1812).
* Andi Kleen : Check all packet lengths properly
* and moved all kfree_skb() up to
* icmp_rcv.
* Andi Kleen : Move the rate limit bookkeeping
* into the dest entry and use a token
* bucket filter (thanks to ANK). Make
* the rates sysctl configurable.
* Yu Tianli : Fixed two ugly bugs in icmp_send
* - IP option length was accounted wrongly
* - ICMP header length was not accounted
* at all.
* Tristan Greaves : Added sysctl option to ignore bogus
* broadcast responses from broken routers.
*
* To Fix:
*
* - Should use skb_pull() instead of all the manual checking.
* This would also greatly simply some upper layer error handlers. --AK
*
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/fcntl.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/inetdevice.h>
#include <linux/netdevice.h>
#include <linux/string.h>
#include <linux/netfilter_ipv4.h>
#include <net/snmp.h>
#include <net/ip.h>
#include <net/route.h>
#include <net/protocol.h>
#include <net/icmp.h>
#include <net/tcp.h>
#include <net/udp.h>
#include <net/raw.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <net/checksum.h>
#include <net/xfrm.h>
#include <net/inet_common.h>
/*
* Build xmit assembly blocks
*/
struct icmp_bxm {
struct sk_buff *skb;
int offset;
int data_len;
struct {
struct icmphdr icmph;
__be32 times[3];
} data;
int head_len;
struct ip_options replyopts;
unsigned char optbuf[40];
};
/* An array of errno for error messages from dest unreach. */
/* RFC 1122: 3.2.2.1 States that NET_UNREACH, HOST_UNREACH and SR_FAILED MUST be considered 'transient errs'. */
struct icmp_err icmp_err_convert[] = {
{
.errno = ENETUNREACH, /* ICMP_NET_UNREACH */
.fatal = 0,
},
{
.errno = EHOSTUNREACH, /* ICMP_HOST_UNREACH */
.fatal = 0,
},
{
.errno = ENOPROTOOPT /* ICMP_PROT_UNREACH */,
.fatal = 1,
},
{
.errno = ECONNREFUSED, /* ICMP_PORT_UNREACH */
.fatal = 1,
},
{
.errno = EMSGSIZE, /* ICMP_FRAG_NEEDED */
.fatal = 0,
},
{
.errno = EOPNOTSUPP, /* ICMP_SR_FAILED */
.fatal = 0,
},
{
.errno = ENETUNREACH, /* ICMP_NET_UNKNOWN */
.fatal = 1,
},
{
.errno = EHOSTDOWN, /* ICMP_HOST_UNKNOWN */
.fatal = 1,
},
{
.errno = ENONET, /* ICMP_HOST_ISOLATED */
.fatal = 1,
},
{
.errno = ENETUNREACH, /* ICMP_NET_ANO */
.fatal = 1,
},
{
.errno = EHOSTUNREACH, /* ICMP_HOST_ANO */
.fatal = 1,
},
{
.errno = ENETUNREACH, /* ICMP_NET_UNR_TOS */
.fatal = 0,
},
{
.errno = EHOSTUNREACH, /* ICMP_HOST_UNR_TOS */
.fatal = 0,
},
{
.errno = EHOSTUNREACH, /* ICMP_PKT_FILTERED */
.fatal = 1,
},
{
.errno = EHOSTUNREACH, /* ICMP_PREC_VIOLATION */
.fatal = 1,
},
{
.errno = EHOSTUNREACH, /* ICMP_PREC_CUTOFF */
.fatal = 1,
},
};
/*
* ICMP control array. This specifies what to do with each ICMP.
*/
struct icmp_control {
void (*handler)(struct sk_buff *skb);
short error; /* This ICMP is classed as an error message */
};
static const struct icmp_control icmp_pointers[NR_ICMP_TYPES+1];
/*
* The ICMP socket(s). This is the most convenient way to flow control
* our ICMP output as well as maintain a clean interface throughout
* all layers. All Socketless IP sends will soon be gone.
*
* On SMP we have one ICMP socket per-cpu.
*/
static struct sock *icmp_sk(struct net *net)
{
return net->ipv4.icmp_sk[smp_processor_id()];
}
static inline struct sock *icmp_xmit_lock(struct net *net)
{
struct sock *sk;
local_bh_disable();
sk = icmp_sk(net);
if (unlikely(!spin_trylock(&sk->sk_lock.slock))) {
/* This can happen if the output path signals a
* dst_link_failure() for an outgoing ICMP packet.
*/
local_bh_enable();
return NULL;
}
return sk;
}
static inline void icmp_xmit_unlock(struct sock *sk)
{
spin_unlock_bh(&sk->sk_lock.slock);
}
/*
* Send an ICMP frame.
*/
/*
* Check transmit rate limitation for given message.
* The rate information is held in the destination cache now.
* This function is generic and could be used for other purposes
* too. It uses a Token bucket filter as suggested by Alexey Kuznetsov.
*
* Note that the same dst_entry fields are modified by functions in
* route.c too, but these work for packet destinations while xrlim_allow
* works for icmp destinations. This means the rate limiting information
* for one "ip object" is shared - and these ICMPs are twice limited:
* by source and by destination.
*
* RFC 1812: 4.3.2.8 SHOULD be able to limit error message rate
* SHOULD allow setting of rate limits
*
* Shared between ICMPv4 and ICMPv6.
*/
#define XRLIM_BURST_FACTOR 6
int xrlim_allow(struct dst_entry *dst, int timeout)
{
unsigned long now, token = dst->rate_tokens;
int rc = 0;
now = jiffies;
token += now - dst->rate_last;
dst->rate_last = now;
if (token > XRLIM_BURST_FACTOR * timeout)
token = XRLIM_BURST_FACTOR * timeout;
if (token >= timeout) {
token -= timeout;
rc = 1;
}
dst->rate_tokens = token;
return rc;
}
static inline int icmpv4_xrlim_allow(struct net *net, struct rtable *rt,
int type, int code)
{
struct dst_entry *dst = &rt->u.dst;
int rc = 1;
if (type > NR_ICMP_TYPES)
goto out;
/* Don't limit PMTU discovery. */
if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
goto out;
/* No rate limit on loopback */
if (dst->dev && (dst->dev->flags&IFF_LOOPBACK))
goto out;
/* Limit if icmp type is enabled in ratemask. */
if ((1 << type) & net->ipv4.sysctl_icmp_ratemask)
rc = xrlim_allow(dst, net->ipv4.sysctl_icmp_ratelimit);
out:
return rc;
}
/*
* Maintain the counters used in the SNMP statistics for outgoing ICMP
*/
void icmp_out_count(struct net *net, unsigned char type)
{
ICMPMSGOUT_INC_STATS(net, type);
ICMP_INC_STATS(net, ICMP_MIB_OUTMSGS);
}
/*
* Checksum each fragment, and on the first include the headers and final
* checksum.
*/
static int icmp_glue_bits(void *from, char *to, int offset, int len, int odd,
struct sk_buff *skb)
{
struct icmp_bxm *icmp_param = (struct icmp_bxm *)from;
__wsum csum;
csum = skb_copy_and_csum_bits(icmp_param->skb,
icmp_param->offset + offset,
to, len, 0);
skb->csum = csum_block_add(skb->csum, csum, odd);
if (icmp_pointers[icmp_param->data.icmph.type].error)
nf_ct_attach(skb, icmp_param->skb);
return 0;
}
static void icmp_push_reply(struct icmp_bxm *icmp_param,
struct ipcm_cookie *ipc, struct rtable **rt)
{
struct sock *sk;
struct sk_buff *skb;
sk = icmp_sk(dev_net((*rt)->u.dst.dev));
if (ip_append_data(sk, icmp_glue_bits, icmp_param,
icmp_param->data_len+icmp_param->head_len,
icmp_param->head_len,
ipc, rt, MSG_DONTWAIT) < 0)
ip_flush_pending_frames(sk);
else if ((skb = skb_peek(&sk->sk_write_queue)) != NULL) {
struct icmphdr *icmph = icmp_hdr(skb);
__wsum csum = 0;
struct sk_buff *skb1;
skb_queue_walk(&sk->sk_write_queue, skb1) {
csum = csum_add(csum, skb1->csum);
}
csum = csum_partial_copy_nocheck((void *)&icmp_param->data,
(char *)icmph,
icmp_param->head_len, csum);
icmph->checksum = csum_fold(csum);
skb->ip_summed = CHECKSUM_NONE;
ip_push_pending_frames(sk);
}
}
/*
* Driving logic for building and sending ICMP messages.
*/
static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb)
{
struct ipcm_cookie ipc;
struct rtable *rt = skb->rtable;
struct net *net = dev_net(rt->u.dst.dev);
struct sock *sk;
struct inet_sock *inet;
__be32 daddr;
if (ip_options_echo(&icmp_param->replyopts, skb))
return;
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
inet = inet_sk(sk);
icmp_param->data.icmph.checksum = 0;
inet->tos = ip_hdr(skb)->tos;
daddr = ipc.addr = rt->rt_src;
ipc.opt = NULL;
if (icmp_param->replyopts.optlen) {
ipc.opt = &icmp_param->replyopts;
if (ipc.opt->srr)
daddr = icmp_param->replyopts.faddr;
}
{
struct flowi fl = { .nl_u = { .ip4_u =
{ .daddr = daddr,
.saddr = rt->rt_spec_dst,
.tos = RT_TOS(ip_hdr(skb)->tos) } },
.proto = IPPROTO_ICMP };
security_skb_classify_flow(skb, &fl);
if (ip_route_output_key(net, &rt, &fl))
goto out_unlock;
}
if (icmpv4_xrlim_allow(net, rt, icmp_param->data.icmph.type,
icmp_param->data.icmph.code))
icmp_push_reply(icmp_param, &ipc, &rt);
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
}
/*
* Send an ICMP message in response to a situation
*
* RFC 1122: 3.2.2 MUST send at least the IP header and 8 bytes of header.
* MAY send more (we do).
* MUST NOT change this header information.
* MUST NOT reply to a multicast/broadcast IP address.
* MUST NOT reply to a multicast/broadcast MAC address.
* MUST reply to only the first fragment.
*/
void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info)
{
struct iphdr *iph;
int room;
struct icmp_bxm icmp_param;
struct rtable *rt = skb_in->rtable;
struct ipcm_cookie ipc;
__be32 saddr;
u8 tos;
struct net *net;
struct sock *sk;
if (!rt)
goto out;
net = dev_net(rt->u.dst.dev);
/*
* Find the original header. It is expected to be valid, of course.
* Check this, icmp_send is called from the most obscure devices
* sometimes.
*/
iph = ip_hdr(skb_in);
if ((u8 *)iph < skb_in->head ||
(skb_in->network_header + sizeof(*iph)) > skb_in->tail)
goto out;
/*
* No replies to physical multicast/broadcast
*/
if (skb_in->pkt_type != PACKET_HOST)
goto out;
/*
* Now check at the protocol level
*/
if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
goto out;
/*
* Only reply to fragment 0. We byte re-order the constant
* mask for efficiency.
*/
if (iph->frag_off & htons(IP_OFFSET))
goto out;
/*
* If we send an ICMP error to an ICMP error a mess would result..
*/
if (icmp_pointers[type].error) {
/*
* We are an error, check if we are replying to an
* ICMP error
*/
if (iph->protocol == IPPROTO_ICMP) {
u8 _inner_type, *itp;
itp = skb_header_pointer(skb_in,
skb_network_header(skb_in) +
(iph->ihl << 2) +
offsetof(struct icmphdr,
type) -
skb_in->data,
sizeof(_inner_type),
&_inner_type);
if (itp == NULL)
goto out;
/*
* Assume any unknown ICMP type is an error. This
* isn't specified by the RFC, but think about it..
*/
if (*itp > NR_ICMP_TYPES ||
icmp_pointers[*itp].error)
goto out;
}
}
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
/*
* Construct source address and options.
*/
saddr = iph->daddr;
if (!(rt->rt_flags & RTCF_LOCAL)) {
struct net_device *dev = NULL;
if (rt->fl.iif &&
net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr)
dev = dev_get_by_index(net, rt->fl.iif);
if (dev) {
saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK);
dev_put(dev);
} else
saddr = 0;
}
tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) |
IPTOS_PREC_INTERNETCONTROL) :
iph->tos;
if (ip_options_echo(&icmp_param.replyopts, skb_in))
goto out_unlock;
/*
* Prepare data for ICMP header.
*/
icmp_param.data.icmph.type = type;
icmp_param.data.icmph.code = code;
icmp_param.data.icmph.un.gateway = info;
icmp_param.data.icmph.checksum = 0;
icmp_param.skb = skb_in;
icmp_param.offset = skb_network_offset(skb_in);
inet_sk(sk)->tos = tos;
ipc.addr = iph->saddr;
ipc.opt = &icmp_param.replyopts;
{
struct flowi fl = {
.nl_u = {
.ip4_u = {
.daddr = icmp_param.replyopts.srr ?
icmp_param.replyopts.faddr :
iph->saddr,
.saddr = saddr,
.tos = RT_TOS(tos)
}
},
.proto = IPPROTO_ICMP,
.uli_u = {
.icmpt = {
.type = type,
.code = code
}
}
};
int err;
struct rtable *rt2;
security_skb_classify_flow(skb_in, &fl);
if (__ip_route_output_key(net, &rt, &fl))
goto out_unlock;
/* No need to clone since we're just using its address. */
rt2 = rt;
err = xfrm_lookup(net, (struct dst_entry **)&rt, &fl, NULL, 0);
switch (err) {
case 0:
if (rt != rt2)
goto route_done;
break;
case -EPERM:
rt = NULL;
break;
default:
goto out_unlock;
}
if (xfrm_decode_session_reverse(skb_in, &fl, AF_INET))
goto relookup_failed;
if (inet_addr_type(net, fl.fl4_src) == RTN_LOCAL)
err = __ip_route_output_key(net, &rt2, &fl);
else {
struct flowi fl2 = {};
struct dst_entry *odst;
fl2.fl4_dst = fl.fl4_src;
if (ip_route_output_key(net, &rt2, &fl2))
goto relookup_failed;
/* Ugh! */
odst = skb_in->dst;
err = ip_route_input(skb_in, fl.fl4_dst, fl.fl4_src,
RT_TOS(tos), rt2->u.dst.dev);
dst_release(&rt2->u.dst);
rt2 = skb_in->rtable;
skb_in->dst = odst;
}
if (err)
goto relookup_failed;
err = xfrm_lookup(net, (struct dst_entry **)&rt2, &fl, NULL,
XFRM_LOOKUP_ICMP);
switch (err) {
case 0:
dst_release(&rt->u.dst);
rt = rt2;
break;
case -EPERM:
goto ende;
default:
relookup_failed:
if (!rt)
goto out_unlock;
break;
}
}
route_done:
if (!icmpv4_xrlim_allow(net, rt, type, code))
goto ende;
/* RFC says return as much as we can without exceeding 576 bytes. */
room = dst_mtu(&rt->u.dst);
if (room > 576)
room = 576;
room -= sizeof(struct iphdr) + icmp_param.replyopts.optlen;
room -= sizeof(struct icmphdr);
icmp_param.data_len = skb_in->len - icmp_param.offset;
if (icmp_param.data_len > room)
icmp_param.data_len = room;
icmp_param.head_len = sizeof(struct icmphdr);
icmp_push_reply(&icmp_param, &ipc, &rt);
ende:
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
out:;
}
/*
* Handle ICMP_DEST_UNREACH, ICMP_TIME_EXCEED, and ICMP_QUENCH.
*/
static void icmp_unreach(struct sk_buff *skb)
{
struct iphdr *iph;
struct icmphdr *icmph;
int hash, protocol;
struct net_protocol *ipprot;
u32 info = 0;
struct net *net;
net = dev_net(skb->dst->dev);
/*
* Incomplete header ?
* Only checks for the IP header, there should be an
* additional check for longer headers in upper levels.
*/
if (!pskb_may_pull(skb, sizeof(struct iphdr)))
goto out_err;
icmph = icmp_hdr(skb);
iph = (struct iphdr *)skb->data;
if (iph->ihl < 5) /* Mangled header, drop. */
goto out_err;
if (icmph->type == ICMP_DEST_UNREACH) {
switch (icmph->code & 15) {
case ICMP_NET_UNREACH:
case ICMP_HOST_UNREACH:
case ICMP_PROT_UNREACH:
case ICMP_PORT_UNREACH:
break;
case ICMP_FRAG_NEEDED:
if (ipv4_config.no_pmtu_disc) {
LIMIT_NETDEBUG(KERN_INFO "ICMP: %pI4: fragmentation needed and DF set.\n",
&iph->daddr);
} else {
info = ip_rt_frag_needed(net, iph,
ntohs(icmph->un.frag.mtu),
skb->dev);
if (!info)
goto out;
}
break;
case ICMP_SR_FAILED:
LIMIT_NETDEBUG(KERN_INFO "ICMP: %pI4: Source Route Failed.\n",
&iph->daddr);
break;
default:
break;
}
if (icmph->code > NR_ICMP_UNREACH)
goto out;
} else if (icmph->type == ICMP_PARAMETERPROB)
info = ntohl(icmph->un.gateway) >> 24;
/*
* Throw it at our lower layers
*
* RFC 1122: 3.2.2 MUST extract the protocol ID from the passed
* header.
* RFC 1122: 3.2.2.1 MUST pass ICMP unreach messages to the
* transport layer.
* RFC 1122: 3.2.2.2 MUST pass ICMP time expired messages to
* transport layer.
*/
/*
* Check the other end isnt violating RFC 1122. Some routers send
* bogus responses to broadcast frames. If you see this message
* first check your netmask matches at both ends, if it does then
* get the other vendor to fix their kit.
*/
if (!net->ipv4.sysctl_icmp_ignore_bogus_error_responses &&
inet_addr_type(net, iph->daddr) == RTN_BROADCAST) {
if (net_ratelimit())
printk(KERN_WARNING "%pI4 sent an invalid ICMP "
"type %u, code %u "
"error to a broadcast: %pI4 on %s\n",
&ip_hdr(skb)->saddr,
icmph->type, icmph->code,
&iph->daddr,
skb->dev->name);
goto out;
}
/* Checkin full IP header plus 8 bytes of protocol to
* avoid additional coding at protocol handlers.
*/
if (!pskb_may_pull(skb, iph->ihl * 4 + 8))
goto out;
iph = (struct iphdr *)skb->data;
protocol = iph->protocol;
/*
* Deliver ICMP message to raw sockets. Pretty useless feature?
*/
raw_icmp_error(skb, protocol, info);
hash = protocol & (MAX_INET_PROTOS - 1);
rcu_read_lock();
ipprot = rcu_dereference(inet_protos[hash]);
if (ipprot && ipprot->err_handler)
ipprot->err_handler(skb, info);
rcu_read_unlock();
out:
return;
out_err:
ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS);
goto out;
}
/*
* Handle ICMP_REDIRECT.
*/
static void icmp_redirect(struct sk_buff *skb)
{
struct iphdr *iph;
if (skb->len < sizeof(struct iphdr))
goto out_err;
/*
* Get the copied header of the packet that caused the redirect
*/
if (!pskb_may_pull(skb, sizeof(struct iphdr)))
goto out;
iph = (struct iphdr *)skb->data;
switch (icmp_hdr(skb)->code & 7) {
case ICMP_REDIR_NET:
case ICMP_REDIR_NETTOS:
/*
* As per RFC recommendations now handle it as a host redirect.
*/
case ICMP_REDIR_HOST:
case ICMP_REDIR_HOSTTOS:
ip_rt_redirect(ip_hdr(skb)->saddr, iph->daddr,
icmp_hdr(skb)->un.gateway,
iph->saddr, skb->dev);
break;
}
out:
return;
out_err:
ICMP_INC_STATS_BH(dev_net(skb->dev), ICMP_MIB_INERRORS);
goto out;
}
/*
* Handle ICMP_ECHO ("ping") requests.
*
* RFC 1122: 3.2.2.6 MUST have an echo server that answers ICMP echo
* requests.
* RFC 1122: 3.2.2.6 Data received in the ICMP_ECHO request MUST be
* included in the reply.
* RFC 1812: 4.3.3.6 SHOULD have a config option for silently ignoring
* echo requests, MUST have default=NOT.
* See also WRT handling of options once they are done and working.
*/
static void icmp_echo(struct sk_buff *skb)
{
struct net *net;
net = dev_net(skb->dst->dev);
if (!net->ipv4.sysctl_icmp_echo_ignore_all) {
struct icmp_bxm icmp_param;
icmp_param.data.icmph = *icmp_hdr(skb);
icmp_param.data.icmph.type = ICMP_ECHOREPLY;
icmp_param.skb = skb;
icmp_param.offset = 0;
icmp_param.data_len = skb->len;
icmp_param.head_len = sizeof(struct icmphdr);
icmp_reply(&icmp_param, skb);
}
}
/*
* Handle ICMP Timestamp requests.
* RFC 1122: 3.2.2.8 MAY implement ICMP timestamp requests.
* SHOULD be in the kernel for minimum random latency.
* MUST be accurate to a few minutes.
* MUST be updated at least at 15Hz.
*/
static void icmp_timestamp(struct sk_buff *skb)
{
struct timespec tv;
struct icmp_bxm icmp_param;
/*
* Too short.
*/
if (skb->len < 4)
goto out_err;
/*
* Fill in the current time as ms since midnight UT:
*/
getnstimeofday(&tv);
icmp_param.data.times[1] = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC +
tv.tv_nsec / NSEC_PER_MSEC);
icmp_param.data.times[2] = icmp_param.data.times[1];
if (skb_copy_bits(skb, 0, &icmp_param.data.times[0], 4))
BUG();
icmp_param.data.icmph = *icmp_hdr(skb);
icmp_param.data.icmph.type = ICMP_TIMESTAMPREPLY;
icmp_param.data.icmph.code = 0;
icmp_param.skb = skb;
icmp_param.offset = 0;
icmp_param.data_len = 0;
icmp_param.head_len = sizeof(struct icmphdr) + 12;
icmp_reply(&icmp_param, skb);
out:
return;
out_err:
ICMP_INC_STATS_BH(dev_net(skb->dst->dev), ICMP_MIB_INERRORS);
goto out;
}
/*
* Handle ICMP_ADDRESS_MASK requests. (RFC950)
*
* RFC1122 (3.2.2.9). A host MUST only send replies to
* ADDRESS_MASK requests if it's been configured as an address mask
* agent. Receiving a request doesn't constitute implicit permission to
* act as one. Of course, implementing this correctly requires (SHOULD)
* a way to turn the functionality on and off. Another one for sysctl(),
* I guess. -- MS
*
* RFC1812 (4.3.3.9). A router MUST implement it.
* A router SHOULD have switch turning it on/off.
* This switch MUST be ON by default.
*
* Gratuitous replies, zero-source replies are not implemented,
* that complies with RFC. DO NOT implement them!!! All the idea
* of broadcast addrmask replies as specified in RFC950 is broken.
* The problem is that it is not uncommon to have several prefixes
* on one physical interface. Moreover, addrmask agent can even be
* not aware of existing another prefixes.
* If source is zero, addrmask agent cannot choose correct prefix.
* Gratuitous mask announcements suffer from the same problem.
* RFC1812 explains it, but still allows to use ADDRMASK,
* that is pretty silly. --ANK
*
* All these rules are so bizarre, that I removed kernel addrmask
* support at all. It is wrong, it is obsolete, nobody uses it in
* any case. --ANK
*
* Furthermore you can do it with a usermode address agent program
* anyway...
*/
static void icmp_address(struct sk_buff *skb)
{
#if 0
if (net_ratelimit())
printk(KERN_DEBUG "a guy asks for address mask. Who is it?\n");
#endif
}
/*
* RFC1812 (4.3.3.9). A router SHOULD listen all replies, and complain
* loudly if an inconsistency is found.
*/
static void icmp_address_reply(struct sk_buff *skb)
{
struct rtable *rt = skb->rtable;
struct net_device *dev = skb->dev;
struct in_device *in_dev;
struct in_ifaddr *ifa;
if (skb->len < 4 || !(rt->rt_flags&RTCF_DIRECTSRC))
goto out;
in_dev = in_dev_get(dev);
if (!in_dev)
goto out;
rcu_read_lock();
if (in_dev->ifa_list &&
IN_DEV_LOG_MARTIANS(in_dev) &&
IN_DEV_FORWARD(in_dev)) {
__be32 _mask, *mp;
mp = skb_header_pointer(skb, 0, sizeof(_mask), &_mask);
BUG_ON(mp == NULL);
for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next) {
if (*mp == ifa->ifa_mask &&
inet_ifa_match(rt->rt_src, ifa))
break;
}
if (!ifa && net_ratelimit()) {
printk(KERN_INFO "Wrong address mask %pI4 from %s/%pI4\n",
mp, dev->name, &rt->rt_src);
}
}
rcu_read_unlock();
in_dev_put(in_dev);
out:;
}
static void icmp_discard(struct sk_buff *skb)
{
}
/*
* Deal with incoming ICMP packets.
*/
int icmp_rcv(struct sk_buff *skb)
{
struct icmphdr *icmph;
struct rtable *rt = skb->rtable;
struct net *net = dev_net(rt->u.dst.dev);
if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
struct sec_path *sp = skb_sec_path(skb);
int nh;
if (!(sp && sp->xvec[sp->len - 1]->props.flags &
XFRM_STATE_ICMP))
goto drop;
if (!pskb_may_pull(skb, sizeof(*icmph) + sizeof(struct iphdr)))
goto drop;
nh = skb_network_offset(skb);
skb_set_network_header(skb, sizeof(*icmph));
if (!xfrm4_policy_check_reverse(NULL, XFRM_POLICY_IN, skb))
goto drop;
skb_set_network_header(skb, nh);
}
ICMP_INC_STATS_BH(net, ICMP_MIB_INMSGS);
switch (skb->ip_summed) {
case CHECKSUM_COMPLETE:
if (!csum_fold(skb->csum))
break;
/* fall through */
case CHECKSUM_NONE:
skb->csum = 0;
if (__skb_checksum_complete(skb))
goto error;
}
if (!pskb_pull(skb, sizeof(*icmph)))
goto error;
icmph = icmp_hdr(skb);
ICMPMSGIN_INC_STATS_BH(net, icmph->type);
/*
* 18 is the highest 'known' ICMP type. Anything else is a mystery
*
* RFC 1122: 3.2.2 Unknown ICMP messages types MUST be silently
* discarded.
*/
if (icmph->type > NR_ICMP_TYPES)
goto error;
/*
* Parse the ICMP message
*/
if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) {
/*
* RFC 1122: 3.2.2.6 An ICMP_ECHO to broadcast MAY be
* silently ignored (we let user decide with a sysctl).
* RFC 1122: 3.2.2.8 An ICMP_TIMESTAMP MAY be silently
* discarded if to broadcast/multicast.
*/
if ((icmph->type == ICMP_ECHO ||
icmph->type == ICMP_TIMESTAMP) &&
net->ipv4.sysctl_icmp_echo_ignore_broadcasts) {
goto error;
}
if (icmph->type != ICMP_ECHO &&
icmph->type != ICMP_TIMESTAMP &&
icmph->type != ICMP_ADDRESS &&
icmph->type != ICMP_ADDRESSREPLY) {
goto error;
}
}
icmp_pointers[icmph->type].handler(skb);
drop:
kfree_skb(skb);
return 0;
error:
ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS);
goto drop;
}
/*
* This table is the definition of how we handle ICMP.
*/
static const struct icmp_control icmp_pointers[NR_ICMP_TYPES + 1] = {
[ICMP_ECHOREPLY] = {
.handler = icmp_discard,
},
[1] = {
.handler = icmp_discard,
.error = 1,
},
[2] = {
.handler = icmp_discard,
.error = 1,
},
[ICMP_DEST_UNREACH] = {
.handler = icmp_unreach,
.error = 1,
},
[ICMP_SOURCE_QUENCH] = {
.handler = icmp_unreach,
.error = 1,
},
[ICMP_REDIRECT] = {
.handler = icmp_redirect,
.error = 1,
},
[6] = {
.handler = icmp_discard,
.error = 1,
},
[7] = {
.handler = icmp_discard,
.error = 1,
},
[ICMP_ECHO] = {
.handler = icmp_echo,
},
[9] = {
.handler = icmp_discard,
.error = 1,
},
[10] = {
.handler = icmp_discard,
.error = 1,
},
[ICMP_TIME_EXCEEDED] = {
.handler = icmp_unreach,
.error = 1,
},
[ICMP_PARAMETERPROB] = {
.handler = icmp_unreach,
.error = 1,
},
[ICMP_TIMESTAMP] = {
.handler = icmp_timestamp,
},
[ICMP_TIMESTAMPREPLY] = {
.handler = icmp_discard,
},
[ICMP_INFO_REQUEST] = {
.handler = icmp_discard,
},
[ICMP_INFO_REPLY] = {
.handler = icmp_discard,
},
[ICMP_ADDRESS] = {
.handler = icmp_address,
},
[ICMP_ADDRESSREPLY] = {
.handler = icmp_address_reply,
},
};
static void __net_exit icmp_sk_exit(struct net *net)
{
int i;
for_each_possible_cpu(i)
inet_ctl_sock_destroy(net->ipv4.icmp_sk[i]);
kfree(net->ipv4.icmp_sk);
net->ipv4.icmp_sk = NULL;
}
static int __net_init icmp_sk_init(struct net *net)
{
int i, err;
net->ipv4.icmp_sk =
kzalloc(nr_cpu_ids * sizeof(struct sock *), GFP_KERNEL);
if (net->ipv4.icmp_sk == NULL)
return -ENOMEM;
for_each_possible_cpu(i) {
struct sock *sk;
err = inet_ctl_sock_create(&sk, PF_INET,
SOCK_RAW, IPPROTO_ICMP, net);
if (err < 0)
goto fail;
net->ipv4.icmp_sk[i] = sk;
/* Enough space for 2 64K ICMP packets, including
* sk_buff struct overhead.
*/
sk->sk_sndbuf =
(2 * ((64 * 1024) + sizeof(struct sk_buff)));
inet_sk(sk)->pmtudisc = IP_PMTUDISC_DONT;
}
/* Control parameters for ECHO replies. */
net->ipv4.sysctl_icmp_echo_ignore_all = 0;
net->ipv4.sysctl_icmp_echo_ignore_broadcasts = 1;
/* Control parameter - ignore bogus broadcast responses? */
net->ipv4.sysctl_icmp_ignore_bogus_error_responses = 1;
/*
* Configurable global rate limit.
*
* ratelimit defines tokens/packet consumed for dst->rate_token
* bucket ratemask defines which icmp types are ratelimited by
* setting it's bit position.
*
* default:
* dest unreachable (3), source quench (4),
* time exceeded (11), parameter problem (12)
*/
net->ipv4.sysctl_icmp_ratelimit = 1 * HZ;
net->ipv4.sysctl_icmp_ratemask = 0x1818;
net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr = 0;
return 0;
fail:
for_each_possible_cpu(i)
inet_ctl_sock_destroy(net->ipv4.icmp_sk[i]);
kfree(net->ipv4.icmp_sk);
return err;
}
static struct pernet_operations __net_initdata icmp_sk_ops = {
.init = icmp_sk_init,
.exit = icmp_sk_exit,
};
int __init icmp_init(void)
{
return register_pernet_subsys(&icmp_sk_ops);
}
EXPORT_SYMBOL(icmp_err_convert);
EXPORT_SYMBOL(icmp_send);
EXPORT_SYMBOL(xrlim_allow);
| gpl-2.0 |
rachitrawat/Vengeance-Kernel-MSM7x30 | drivers/staging/hv/blkvsc_drv.c | 393 | 39945 | /*
* Copyright (c) 2009, Microsoft Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307 USA.
*
* Authors:
* Haiyang Zhang <haiyangz@microsoft.com>
* Hank Janssen <hjanssen@microsoft.com>
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/blkdev.h>
#include <linux/major.h>
#include <linux/delay.h>
#include <linux/hdreg.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_eh.h>
#include <scsi/scsi_dbg.h>
#include "osd.h"
#include "logging.h"
#include "vmbus.h"
#include "StorVscApi.h"
#define BLKVSC_MINORS 64
enum blkvsc_device_type {
UNKNOWN_DEV_TYPE,
HARDDISK_TYPE,
DVD_TYPE,
};
/*
* This request ties the struct request and struct
* blkvsc_request/hv_storvsc_request together A struct request may be
* represented by 1 or more struct blkvsc_request
*/
struct blkvsc_request_group {
int outstanding;
int status;
struct list_head blkvsc_req_list; /* list of blkvsc_requests */
};
struct blkvsc_request {
/* blkvsc_request_group.blkvsc_req_list */
struct list_head req_entry;
/* block_device_context.pending_list */
struct list_head pend_entry;
/* This may be null if we generate a request internally */
struct request *req;
struct block_device_context *dev;
/* The group this request is part of. Maybe null */
struct blkvsc_request_group *group;
wait_queue_head_t wevent;
int cond;
int write;
sector_t sector_start;
unsigned long sector_count;
unsigned char sense_buffer[SCSI_SENSE_BUFFERSIZE];
unsigned char cmd_len;
unsigned char cmnd[MAX_COMMAND_SIZE];
struct hv_storvsc_request request;
/*
* !!!DO NOT ADD ANYTHING BELOW HERE!!! Otherwise, memory can overlap,
* because - The extension buffer falls right here and is pointed to by
* request.Extension;
* Which sounds like a horrible idea, who designed this?
*/
};
/* Per device structure */
struct block_device_context {
/* point back to our device context */
struct device_context *device_ctx;
struct kmem_cache *request_pool;
spinlock_t lock;
struct gendisk *gd;
enum blkvsc_device_type device_type;
struct list_head pending_list;
unsigned char device_id[64];
unsigned int device_id_len;
int num_outstanding_reqs;
int shutting_down;
int media_not_present;
unsigned int sector_size;
sector_t capacity;
unsigned int port;
unsigned char path;
unsigned char target;
int users;
};
/* Per driver */
struct blkvsc_driver_context {
/* !! These must be the first 2 fields !! */
/* FIXME this is a bug! */
struct driver_context drv_ctx;
struct storvsc_driver_object drv_obj;
};
/* Static decl */
static int blkvsc_probe(struct device *dev);
static int blkvsc_remove(struct device *device);
static void blkvsc_shutdown(struct device *device);
static int blkvsc_open(struct block_device *bdev, fmode_t mode);
static int blkvsc_release(struct gendisk *disk, fmode_t mode);
static int blkvsc_media_changed(struct gendisk *gd);
static int blkvsc_revalidate_disk(struct gendisk *gd);
static int blkvsc_getgeo(struct block_device *bd, struct hd_geometry *hg);
static int blkvsc_ioctl(struct block_device *bd, fmode_t mode,
unsigned cmd, unsigned long argument);
static void blkvsc_request(struct request_queue *queue);
static void blkvsc_request_completion(struct hv_storvsc_request *request);
static int blkvsc_do_request(struct block_device_context *blkdev,
struct request *req);
static int blkvsc_submit_request(struct blkvsc_request *blkvsc_req,
void (*request_completion)(struct hv_storvsc_request *));
static void blkvsc_init_rw(struct blkvsc_request *blkvsc_req);
static void blkvsc_cmd_completion(struct hv_storvsc_request *request);
static int blkvsc_do_inquiry(struct block_device_context *blkdev);
static int blkvsc_do_read_capacity(struct block_device_context *blkdev);
static int blkvsc_do_read_capacity16(struct block_device_context *blkdev);
static int blkvsc_do_flush(struct block_device_context *blkdev);
static int blkvsc_cancel_pending_reqs(struct block_device_context *blkdev);
static int blkvsc_do_pending_reqs(struct block_device_context *blkdev);
static int blkvsc_ringbuffer_size = BLKVSC_RING_BUFFER_SIZE;
/* The one and only one */
static struct blkvsc_driver_context g_blkvsc_drv;
static struct block_device_operations block_ops = {
.owner = THIS_MODULE,
.open = blkvsc_open,
.release = blkvsc_release,
.media_changed = blkvsc_media_changed,
.revalidate_disk = blkvsc_revalidate_disk,
.getgeo = blkvsc_getgeo,
.ioctl = blkvsc_ioctl,
};
/**
* blkvsc_drv_init - BlkVsc driver initialization.
*/
static int blkvsc_drv_init(int (*drv_init)(struct hv_driver *drv))
{
struct storvsc_driver_object *storvsc_drv_obj = &g_blkvsc_drv.drv_obj;
struct driver_context *drv_ctx = &g_blkvsc_drv.drv_ctx;
int ret;
DPRINT_ENTER(BLKVSC_DRV);
vmbus_get_interface(&storvsc_drv_obj->Base.VmbusChannelInterface);
storvsc_drv_obj->RingBufferSize = blkvsc_ringbuffer_size;
/* Callback to client driver to complete the initialization */
drv_init(&storvsc_drv_obj->Base);
drv_ctx->driver.name = storvsc_drv_obj->Base.name;
memcpy(&drv_ctx->class_id, &storvsc_drv_obj->Base.deviceType,
sizeof(struct hv_guid));
drv_ctx->probe = blkvsc_probe;
drv_ctx->remove = blkvsc_remove;
drv_ctx->shutdown = blkvsc_shutdown;
/* The driver belongs to vmbus */
ret = vmbus_child_driver_register(drv_ctx);
DPRINT_EXIT(BLKVSC_DRV);
return ret;
}
static int blkvsc_drv_exit_cb(struct device *dev, void *data)
{
struct device **curr = (struct device **)data;
*curr = dev;
return 1; /* stop iterating */
}
static void blkvsc_drv_exit(void)
{
struct storvsc_driver_object *storvsc_drv_obj = &g_blkvsc_drv.drv_obj;
struct driver_context *drv_ctx = &g_blkvsc_drv.drv_ctx;
struct device *current_dev;
int ret;
DPRINT_ENTER(BLKVSC_DRV);
while (1) {
current_dev = NULL;
/* Get the device */
ret = driver_for_each_device(&drv_ctx->driver, NULL,
(void *) ¤t_dev,
blkvsc_drv_exit_cb);
if (ret)
DPRINT_WARN(BLKVSC_DRV,
"driver_for_each_device returned %d", ret);
if (current_dev == NULL)
break;
/* Initiate removal from the top-down */
device_unregister(current_dev);
}
if (storvsc_drv_obj->Base.OnCleanup)
storvsc_drv_obj->Base.OnCleanup(&storvsc_drv_obj->Base);
vmbus_child_driver_unregister(drv_ctx);
DPRINT_EXIT(BLKVSC_DRV);
return;
}
/**
* blkvsc_probe - Add a new device for this driver
*/
static int blkvsc_probe(struct device *device)
{
struct driver_context *driver_ctx =
driver_to_driver_context(device->driver);
struct blkvsc_driver_context *blkvsc_drv_ctx =
(struct blkvsc_driver_context *)driver_ctx;
struct storvsc_driver_object *storvsc_drv_obj =
&blkvsc_drv_ctx->drv_obj;
struct device_context *device_ctx = device_to_device_context(device);
struct hv_device *device_obj = &device_ctx->device_obj;
struct block_device_context *blkdev = NULL;
struct storvsc_device_info device_info;
int major = 0;
int devnum = 0;
int ret = 0;
static int ide0_registered;
static int ide1_registered;
DPRINT_ENTER(BLKVSC_DRV);
DPRINT_DBG(BLKVSC_DRV, "blkvsc_probe - enter");
if (!storvsc_drv_obj->Base.OnDeviceAdd) {
DPRINT_ERR(BLKVSC_DRV, "OnDeviceAdd() not set");
ret = -1;
goto Cleanup;
}
blkdev = kzalloc(sizeof(struct block_device_context), GFP_KERNEL);
if (!blkdev) {
ret = -ENOMEM;
goto Cleanup;
}
INIT_LIST_HEAD(&blkdev->pending_list);
/* Initialize what we can here */
spin_lock_init(&blkdev->lock);
ASSERT(sizeof(struct blkvsc_request_group) <=
sizeof(struct blkvsc_request));
blkdev->request_pool = kmem_cache_create(dev_name(&device_ctx->device),
sizeof(struct blkvsc_request) +
storvsc_drv_obj->RequestExtSize, 0,
SLAB_HWCACHE_ALIGN, NULL);
if (!blkdev->request_pool) {
ret = -ENOMEM;
goto Cleanup;
}
/* Call to the vsc driver to add the device */
ret = storvsc_drv_obj->Base.OnDeviceAdd(device_obj, &device_info);
if (ret != 0) {
DPRINT_ERR(BLKVSC_DRV, "unable to add blkvsc device");
goto Cleanup;
}
blkdev->device_ctx = device_ctx;
/* this identified the device 0 or 1 */
blkdev->target = device_info.TargetId;
/* this identified the ide ctrl 0 or 1 */
blkdev->path = device_info.PathId;
dev_set_drvdata(device, blkdev);
/* Calculate the major and device num */
if (blkdev->path == 0) {
major = IDE0_MAJOR;
devnum = blkdev->path + blkdev->target; /* 0 or 1 */
if (!ide0_registered) {
ret = register_blkdev(major, "ide");
if (ret != 0) {
DPRINT_ERR(BLKVSC_DRV,
"register_blkdev() failed! ret %d",
ret);
goto Remove;
}
ide0_registered = 1;
}
} else if (blkdev->path == 1) {
major = IDE1_MAJOR;
devnum = blkdev->path + blkdev->target + 1; /* 2 or 3 */
if (!ide1_registered) {
ret = register_blkdev(major, "ide");
if (ret != 0) {
DPRINT_ERR(BLKVSC_DRV,
"register_blkdev() failed! ret %d",
ret);
goto Remove;
}
ide1_registered = 1;
}
} else {
DPRINT_ERR(BLKVSC_DRV, "invalid pathid");
ret = -1;
goto Cleanup;
}
DPRINT_INFO(BLKVSC_DRV, "blkvsc registered for major %d!!", major);
blkdev->gd = alloc_disk(BLKVSC_MINORS);
if (!blkdev->gd) {
DPRINT_ERR(BLKVSC_DRV, "register_blkdev() failed! ret %d", ret);
ret = -1;
goto Cleanup;
}
blkdev->gd->queue = blk_init_queue(blkvsc_request, &blkdev->lock);
blk_queue_max_segment_size(blkdev->gd->queue, PAGE_SIZE);
blk_queue_max_phys_segments(blkdev->gd->queue,
MAX_MULTIPAGE_BUFFER_COUNT);
blk_queue_max_hw_segments(blkdev->gd->queue,
MAX_MULTIPAGE_BUFFER_COUNT);
blk_queue_segment_boundary(blkdev->gd->queue, PAGE_SIZE-1);
blk_queue_bounce_limit(blkdev->gd->queue, BLK_BOUNCE_ANY);
blk_queue_dma_alignment(blkdev->gd->queue, 511);
blkdev->gd->major = major;
if (devnum == 1 || devnum == 3)
blkdev->gd->first_minor = BLKVSC_MINORS;
else
blkdev->gd->first_minor = 0;
blkdev->gd->fops = &block_ops;
blkdev->gd->private_data = blkdev;
sprintf(blkdev->gd->disk_name, "hd%c", 'a' + devnum);
blkvsc_do_inquiry(blkdev);
if (blkdev->device_type == DVD_TYPE) {
set_disk_ro(blkdev->gd, 1);
blkdev->gd->flags |= GENHD_FL_REMOVABLE;
blkvsc_do_read_capacity(blkdev);
} else {
blkvsc_do_read_capacity16(blkdev);
}
set_capacity(blkdev->gd, blkdev->capacity * (blkdev->sector_size/512));
blk_queue_logical_block_size(blkdev->gd->queue, blkdev->sector_size);
/* go! */
add_disk(blkdev->gd);
DPRINT_INFO(BLKVSC_DRV, "%s added!! capacity %lu sector_size %d",
blkdev->gd->disk_name, (unsigned long)blkdev->capacity,
blkdev->sector_size);
return ret;
Remove:
storvsc_drv_obj->Base.OnDeviceRemove(device_obj);
Cleanup:
if (blkdev) {
if (blkdev->request_pool) {
kmem_cache_destroy(blkdev->request_pool);
blkdev->request_pool = NULL;
}
kfree(blkdev);
blkdev = NULL;
}
DPRINT_EXIT(BLKVSC_DRV);
return ret;
}
static void blkvsc_shutdown(struct device *device)
{
struct block_device_context *blkdev = dev_get_drvdata(device);
unsigned long flags;
if (!blkdev)
return;
DPRINT_DBG(BLKVSC_DRV, "blkvsc_shutdown - users %d disk %s\n",
blkdev->users, blkdev->gd->disk_name);
spin_lock_irqsave(&blkdev->lock, flags);
blkdev->shutting_down = 1;
blk_stop_queue(blkdev->gd->queue);
spin_unlock_irqrestore(&blkdev->lock, flags);
while (blkdev->num_outstanding_reqs) {
DPRINT_INFO(STORVSC, "waiting for %d requests to complete...",
blkdev->num_outstanding_reqs);
udelay(100);
}
blkvsc_do_flush(blkdev);
spin_lock_irqsave(&blkdev->lock, flags);
blkvsc_cancel_pending_reqs(blkdev);
spin_unlock_irqrestore(&blkdev->lock, flags);
}
static int blkvsc_do_flush(struct block_device_context *blkdev)
{
struct blkvsc_request *blkvsc_req;
DPRINT_DBG(BLKVSC_DRV, "blkvsc_do_flush()\n");
if (blkdev->device_type != HARDDISK_TYPE)
return 0;
blkvsc_req = kmem_cache_alloc(blkdev->request_pool, GFP_KERNEL);
if (!blkvsc_req)
return -ENOMEM;
memset(blkvsc_req, 0, sizeof(struct blkvsc_request));
init_waitqueue_head(&blkvsc_req->wevent);
blkvsc_req->dev = blkdev;
blkvsc_req->req = NULL;
blkvsc_req->write = 0;
blkvsc_req->request.DataBuffer.PfnArray[0] = 0;
blkvsc_req->request.DataBuffer.Offset = 0;
blkvsc_req->request.DataBuffer.Length = 0;
blkvsc_req->cmnd[0] = SYNCHRONIZE_CACHE;
blkvsc_req->cmd_len = 10;
/*
* Set this here since the completion routine may be invoked and
* completed before we return
*/
blkvsc_req->cond = 0;
blkvsc_submit_request(blkvsc_req, blkvsc_cmd_completion);
wait_event_interruptible(blkvsc_req->wevent, blkvsc_req->cond);
kmem_cache_free(blkvsc_req->dev->request_pool, blkvsc_req);
return 0;
}
/* Do a scsi INQUIRY cmd here to get the device type (ie disk or dvd) */
static int blkvsc_do_inquiry(struct block_device_context *blkdev)
{
struct blkvsc_request *blkvsc_req;
struct page *page_buf;
unsigned char *buf;
unsigned char device_type;
DPRINT_DBG(BLKVSC_DRV, "blkvsc_do_inquiry()\n");
blkvsc_req = kmem_cache_alloc(blkdev->request_pool, GFP_KERNEL);
if (!blkvsc_req)
return -ENOMEM;
memset(blkvsc_req, 0, sizeof(struct blkvsc_request));
page_buf = alloc_page(GFP_KERNEL);
if (!page_buf) {
kmem_cache_free(blkvsc_req->dev->request_pool, blkvsc_req);
return -ENOMEM;
}
init_waitqueue_head(&blkvsc_req->wevent);
blkvsc_req->dev = blkdev;
blkvsc_req->req = NULL;
blkvsc_req->write = 0;
blkvsc_req->request.DataBuffer.PfnArray[0] = page_to_pfn(page_buf);
blkvsc_req->request.DataBuffer.Offset = 0;
blkvsc_req->request.DataBuffer.Length = 64;
blkvsc_req->cmnd[0] = INQUIRY;
blkvsc_req->cmnd[1] = 0x1; /* Get product data */
blkvsc_req->cmnd[2] = 0x83; /* mode page 83 */
blkvsc_req->cmnd[4] = 64;
blkvsc_req->cmd_len = 6;
/*
* Set this here since the completion routine may be invoked and
* completed before we return
*/
blkvsc_req->cond = 0;
blkvsc_submit_request(blkvsc_req, blkvsc_cmd_completion);
DPRINT_DBG(BLKVSC_DRV, "waiting %p to complete - cond %d\n",
blkvsc_req, blkvsc_req->cond);
wait_event_interruptible(blkvsc_req->wevent, blkvsc_req->cond);
buf = kmap(page_buf);
/* print_hex_dump_bytes("", DUMP_PREFIX_NONE, buf, 64); */
/* be to le */
device_type = buf[0] & 0x1F;
if (device_type == 0x0) {
blkdev->device_type = HARDDISK_TYPE;
} else if (device_type == 0x5) {
blkdev->device_type = DVD_TYPE;
} else {
/* TODO: this is currently unsupported device type */
blkdev->device_type = UNKNOWN_DEV_TYPE;
}
DPRINT_DBG(BLKVSC_DRV, "device type %d \n", device_type);
blkdev->device_id_len = buf[7];
if (blkdev->device_id_len > 64)
blkdev->device_id_len = 64;
memcpy(blkdev->device_id, &buf[8], blkdev->device_id_len);
/* printk_hex_dump_bytes("", DUMP_PREFIX_NONE, blkdev->device_id,
* blkdev->device_id_len); */
kunmap(page_buf);
__free_page(page_buf);
kmem_cache_free(blkvsc_req->dev->request_pool, blkvsc_req);
return 0;
}
/* Do a scsi READ_CAPACITY cmd here to get the size of the disk */
static int blkvsc_do_read_capacity(struct block_device_context *blkdev)
{
struct blkvsc_request *blkvsc_req;
struct page *page_buf;
unsigned char *buf;
struct scsi_sense_hdr sense_hdr;
DPRINT_DBG(BLKVSC_DRV, "blkvsc_do_read_capacity()\n");
blkdev->sector_size = 0;
blkdev->capacity = 0;
blkdev->media_not_present = 0; /* assume a disk is present */
blkvsc_req = kmem_cache_alloc(blkdev->request_pool, GFP_KERNEL);
if (!blkvsc_req)
return -ENOMEM;
memset(blkvsc_req, 0, sizeof(struct blkvsc_request));
page_buf = alloc_page(GFP_KERNEL);
if (!page_buf) {
kmem_cache_free(blkvsc_req->dev->request_pool, blkvsc_req);
return -ENOMEM;
}
init_waitqueue_head(&blkvsc_req->wevent);
blkvsc_req->dev = blkdev;
blkvsc_req->req = NULL;
blkvsc_req->write = 0;
blkvsc_req->request.DataBuffer.PfnArray[0] = page_to_pfn(page_buf);
blkvsc_req->request.DataBuffer.Offset = 0;
blkvsc_req->request.DataBuffer.Length = 8;
blkvsc_req->cmnd[0] = READ_CAPACITY;
blkvsc_req->cmd_len = 16;
/*
* Set this here since the completion routine may be invoked
* and completed before we return
*/
blkvsc_req->cond = 0;
blkvsc_submit_request(blkvsc_req, blkvsc_cmd_completion);
DPRINT_DBG(BLKVSC_DRV, "waiting %p to complete - cond %d\n",
blkvsc_req, blkvsc_req->cond);
wait_event_interruptible(blkvsc_req->wevent, blkvsc_req->cond);
/* check error */
if (blkvsc_req->request.Status) {
scsi_normalize_sense(blkvsc_req->sense_buffer,
SCSI_SENSE_BUFFERSIZE, &sense_hdr);
if (sense_hdr.asc == 0x3A) {
/* Medium not present */
blkdev->media_not_present = 1;
}
return 0;
}
buf = kmap(page_buf);
/* be to le */
blkdev->capacity = ((buf[0] << 24) | (buf[1] << 16) |
(buf[2] << 8) | buf[3]) + 1;
blkdev->sector_size = (buf[4] << 24) | (buf[5] << 16) |
(buf[6] << 8) | buf[7];
kunmap(page_buf);
__free_page(page_buf);
kmem_cache_free(blkvsc_req->dev->request_pool, blkvsc_req);
return 0;
}
static int blkvsc_do_read_capacity16(struct block_device_context *blkdev)
{
struct blkvsc_request *blkvsc_req;
struct page *page_buf;
unsigned char *buf;
struct scsi_sense_hdr sense_hdr;
DPRINT_DBG(BLKVSC_DRV, "blkvsc_do_read_capacity16()\n");
blkdev->sector_size = 0;
blkdev->capacity = 0;
blkdev->media_not_present = 0; /* assume a disk is present */
blkvsc_req = kmem_cache_alloc(blkdev->request_pool, GFP_KERNEL);
if (!blkvsc_req)
return -ENOMEM;
memset(blkvsc_req, 0, sizeof(struct blkvsc_request));
page_buf = alloc_page(GFP_KERNEL);
if (!page_buf) {
kmem_cache_free(blkvsc_req->dev->request_pool, blkvsc_req);
return -ENOMEM;
}
init_waitqueue_head(&blkvsc_req->wevent);
blkvsc_req->dev = blkdev;
blkvsc_req->req = NULL;
blkvsc_req->write = 0;
blkvsc_req->request.DataBuffer.PfnArray[0] = page_to_pfn(page_buf);
blkvsc_req->request.DataBuffer.Offset = 0;
blkvsc_req->request.DataBuffer.Length = 12;
blkvsc_req->cmnd[0] = 0x9E; /* READ_CAPACITY16; */
blkvsc_req->cmd_len = 16;
/*
* Set this here since the completion routine may be invoked
* and completed before we return
*/
blkvsc_req->cond = 0;
blkvsc_submit_request(blkvsc_req, blkvsc_cmd_completion);
DPRINT_DBG(BLKVSC_DRV, "waiting %p to complete - cond %d\n",
blkvsc_req, blkvsc_req->cond);
wait_event_interruptible(blkvsc_req->wevent, blkvsc_req->cond);
/* check error */
if (blkvsc_req->request.Status) {
scsi_normalize_sense(blkvsc_req->sense_buffer,
SCSI_SENSE_BUFFERSIZE, &sense_hdr);
if (sense_hdr.asc == 0x3A) {
/* Medium not present */
blkdev->media_not_present = 1;
}
return 0;
}
buf = kmap(page_buf);
/* be to le */
blkdev->capacity = be64_to_cpu(*(unsigned long long *) &buf[0]) + 1;
blkdev->sector_size = be32_to_cpu(*(unsigned int *)&buf[8]);
#if 0
blkdev->capacity = ((buf[0] << 24) | (buf[1] << 16) |
(buf[2] << 8) | buf[3]) + 1;
blkdev->sector_size = (buf[4] << 24) | (buf[5] << 16) |
(buf[6] << 8) | buf[7];
#endif
kunmap(page_buf);
__free_page(page_buf);
kmem_cache_free(blkvsc_req->dev->request_pool, blkvsc_req);
return 0;
}
/**
* blkvsc_remove() - Callback when our device is removed
*/
static int blkvsc_remove(struct device *device)
{
struct driver_context *driver_ctx =
driver_to_driver_context(device->driver);
struct blkvsc_driver_context *blkvsc_drv_ctx =
(struct blkvsc_driver_context *)driver_ctx;
struct storvsc_driver_object *storvsc_drv_obj =
&blkvsc_drv_ctx->drv_obj;
struct device_context *device_ctx = device_to_device_context(device);
struct hv_device *device_obj = &device_ctx->device_obj;
struct block_device_context *blkdev = dev_get_drvdata(device);
unsigned long flags;
int ret;
DPRINT_ENTER(BLKVSC_DRV);
DPRINT_DBG(BLKVSC_DRV, "blkvsc_remove()\n");
if (!storvsc_drv_obj->Base.OnDeviceRemove) {
DPRINT_EXIT(BLKVSC_DRV);
return -1;
}
/*
* Call to the vsc driver to let it know that the device is being
* removed
*/
ret = storvsc_drv_obj->Base.OnDeviceRemove(device_obj);
if (ret != 0) {
/* TODO: */
DPRINT_ERR(BLKVSC_DRV,
"unable to remove blkvsc device (ret %d)", ret);
}
/* Get to a known state */
spin_lock_irqsave(&blkdev->lock, flags);
blkdev->shutting_down = 1;
blk_stop_queue(blkdev->gd->queue);
spin_unlock_irqrestore(&blkdev->lock, flags);
while (blkdev->num_outstanding_reqs) {
DPRINT_INFO(STORVSC, "waiting for %d requests to complete...",
blkdev->num_outstanding_reqs);
udelay(100);
}
blkvsc_do_flush(blkdev);
spin_lock_irqsave(&blkdev->lock, flags);
blkvsc_cancel_pending_reqs(blkdev);
spin_unlock_irqrestore(&blkdev->lock, flags);
blk_cleanup_queue(blkdev->gd->queue);
del_gendisk(blkdev->gd);
kmem_cache_destroy(blkdev->request_pool);
kfree(blkdev);
DPRINT_EXIT(BLKVSC_DRV);
return ret;
}
static void blkvsc_init_rw(struct blkvsc_request *blkvsc_req)
{
ASSERT(blkvsc_req->req);
ASSERT(blkvsc_req->sector_count <= (MAX_MULTIPAGE_BUFFER_COUNT*8));
blkvsc_req->cmd_len = 16;
if (blkvsc_req->sector_start > 0xffffffff) {
if (rq_data_dir(blkvsc_req->req)) {
blkvsc_req->write = 1;
blkvsc_req->cmnd[0] = WRITE_16;
} else {
blkvsc_req->write = 0;
blkvsc_req->cmnd[0] = READ_16;
}
blkvsc_req->cmnd[1] |= blk_fua_rq(blkvsc_req->req) ? 0x8 : 0;
*(unsigned long long *)&blkvsc_req->cmnd[2] =
cpu_to_be64(blkvsc_req->sector_start);
*(unsigned int *)&blkvsc_req->cmnd[10] =
cpu_to_be32(blkvsc_req->sector_count);
} else if ((blkvsc_req->sector_count > 0xff) ||
(blkvsc_req->sector_start > 0x1fffff)) {
if (rq_data_dir(blkvsc_req->req)) {
blkvsc_req->write = 1;
blkvsc_req->cmnd[0] = WRITE_10;
} else {
blkvsc_req->write = 0;
blkvsc_req->cmnd[0] = READ_10;
}
blkvsc_req->cmnd[1] |= blk_fua_rq(blkvsc_req->req) ? 0x8 : 0;
*(unsigned int *)&blkvsc_req->cmnd[2] =
cpu_to_be32(blkvsc_req->sector_start);
*(unsigned short *)&blkvsc_req->cmnd[7] =
cpu_to_be16(blkvsc_req->sector_count);
} else {
if (rq_data_dir(blkvsc_req->req)) {
blkvsc_req->write = 1;
blkvsc_req->cmnd[0] = WRITE_6;
} else {
blkvsc_req->write = 0;
blkvsc_req->cmnd[0] = READ_6;
}
*(unsigned int *)&blkvsc_req->cmnd[1] =
cpu_to_be32(blkvsc_req->sector_start) >> 8;
blkvsc_req->cmnd[1] &= 0x1f;
blkvsc_req->cmnd[4] = (unsigned char)blkvsc_req->sector_count;
}
}
static int blkvsc_submit_request(struct blkvsc_request *blkvsc_req,
void (*request_completion)(struct hv_storvsc_request *))
{
struct block_device_context *blkdev = blkvsc_req->dev;
struct device_context *device_ctx = blkdev->device_ctx;
struct driver_context *driver_ctx =
driver_to_driver_context(device_ctx->device.driver);
struct blkvsc_driver_context *blkvsc_drv_ctx =
(struct blkvsc_driver_context *)driver_ctx;
struct storvsc_driver_object *storvsc_drv_obj =
&blkvsc_drv_ctx->drv_obj;
struct hv_storvsc_request *storvsc_req;
int ret;
DPRINT_DBG(BLKVSC_DRV, "blkvsc_submit_request() - "
"req %p type %s start_sector %lu count %ld offset %d "
"len %d\n", blkvsc_req,
(blkvsc_req->write) ? "WRITE" : "READ",
(unsigned long) blkvsc_req->sector_start,
blkvsc_req->sector_count,
blkvsc_req->request.DataBuffer.Offset,
blkvsc_req->request.DataBuffer.Length);
#if 0
for (i = 0; i < (blkvsc_req->request.DataBuffer.Length >> 12); i++) {
DPRINT_DBG(BLKVSC_DRV, "blkvsc_submit_request() - "
"req %p pfn[%d] %llx\n",
blkvsc_req, i,
blkvsc_req->request.DataBuffer.PfnArray[i]);
}
#endif
storvsc_req = &blkvsc_req->request;
storvsc_req->Extension = (void *)((unsigned long)blkvsc_req +
sizeof(struct blkvsc_request));
storvsc_req->Type = blkvsc_req->write ? WRITE_TYPE : READ_TYPE;
storvsc_req->OnIOCompletion = request_completion;
storvsc_req->Context = blkvsc_req;
storvsc_req->Host = blkdev->port;
storvsc_req->Bus = blkdev->path;
storvsc_req->TargetId = blkdev->target;
storvsc_req->LunId = 0; /* this is not really used at all */
storvsc_req->CdbLen = blkvsc_req->cmd_len;
storvsc_req->Cdb = blkvsc_req->cmnd;
storvsc_req->SenseBuffer = blkvsc_req->sense_buffer;
storvsc_req->SenseBufferSize = SCSI_SENSE_BUFFERSIZE;
ret = storvsc_drv_obj->OnIORequest(&blkdev->device_ctx->device_obj,
&blkvsc_req->request);
if (ret == 0)
blkdev->num_outstanding_reqs++;
return ret;
}
/*
* We break the request into 1 or more blkvsc_requests and submit
* them. If we cant submit them all, we put them on the
* pending_list. The blkvsc_request() will work on the pending_list.
*/
static int blkvsc_do_request(struct block_device_context *blkdev,
struct request *req)
{
struct bio *bio = NULL;
struct bio_vec *bvec = NULL;
struct bio_vec *prev_bvec = NULL;
struct blkvsc_request *blkvsc_req = NULL;
struct blkvsc_request *tmp;
int databuf_idx = 0;
int seg_idx = 0;
sector_t start_sector;
unsigned long num_sectors = 0;
int ret = 0;
int pending = 0;
struct blkvsc_request_group *group = NULL;
DPRINT_DBG(BLKVSC_DRV, "blkdev %p req %p sect %lu \n", blkdev, req,
(unsigned long)blk_rq_pos(req));
/* Create a group to tie req to list of blkvsc_reqs */
group = kmem_cache_alloc(blkdev->request_pool, GFP_ATOMIC);
if (!group)
return -ENOMEM;
INIT_LIST_HEAD(&group->blkvsc_req_list);
group->outstanding = group->status = 0;
start_sector = blk_rq_pos(req);
/* foreach bio in the request */
if (req->bio) {
for (bio = req->bio; bio; bio = bio->bi_next) {
/*
* Map this bio into an existing or new storvsc request
*/
bio_for_each_segment(bvec, bio, seg_idx) {
DPRINT_DBG(BLKVSC_DRV, "bio_for_each_segment() "
"- req %p bio %p bvec %p seg_idx %d "
"databuf_idx %d\n", req, bio, bvec,
seg_idx, databuf_idx);
/* Get a new storvsc request */
/* 1st-time */
if ((!blkvsc_req) ||
(databuf_idx >= MAX_MULTIPAGE_BUFFER_COUNT)
/* hole at the begin of page */
|| (bvec->bv_offset != 0) ||
/* hold at the end of page */
(prev_bvec &&
(prev_bvec->bv_len != PAGE_SIZE))) {
/* submit the prev one */
if (blkvsc_req) {
blkvsc_req->sector_start = start_sector;
sector_div(blkvsc_req->sector_start, (blkdev->sector_size >> 9));
blkvsc_req->sector_count = num_sectors / (blkdev->sector_size >> 9);
blkvsc_init_rw(blkvsc_req);
}
/*
* Create new blkvsc_req to represent
* the current bvec
*/
blkvsc_req = kmem_cache_alloc(blkdev->request_pool, GFP_ATOMIC);
if (!blkvsc_req) {
/* free up everything */
list_for_each_entry_safe(
blkvsc_req, tmp,
&group->blkvsc_req_list,
req_entry) {
list_del(&blkvsc_req->req_entry);
kmem_cache_free(blkdev->request_pool, blkvsc_req);
}
kmem_cache_free(blkdev->request_pool, group);
return -ENOMEM;
}
memset(blkvsc_req, 0,
sizeof(struct blkvsc_request));
blkvsc_req->dev = blkdev;
blkvsc_req->req = req;
blkvsc_req->request.DataBuffer.Offset = bvec->bv_offset;
blkvsc_req->request.DataBuffer.Length = 0;
/* Add to the group */
blkvsc_req->group = group;
blkvsc_req->group->outstanding++;
list_add_tail(&blkvsc_req->req_entry,
&blkvsc_req->group->blkvsc_req_list);
start_sector += num_sectors;
num_sectors = 0;
databuf_idx = 0;
}
/* Add the curr bvec/segment to the curr blkvsc_req */
blkvsc_req->request.DataBuffer.PfnArray[databuf_idx] = page_to_pfn(bvec->bv_page);
blkvsc_req->request.DataBuffer.Length += bvec->bv_len;
prev_bvec = bvec;
databuf_idx++;
num_sectors += bvec->bv_len >> 9;
} /* bio_for_each_segment */
} /* rq_for_each_bio */
}
/* Handle the last one */
if (blkvsc_req) {
DPRINT_DBG(BLKVSC_DRV, "blkdev %p req %p group %p count %d\n",
blkdev, req, blkvsc_req->group,
blkvsc_req->group->outstanding);
blkvsc_req->sector_start = start_sector;
sector_div(blkvsc_req->sector_start,
(blkdev->sector_size >> 9));
blkvsc_req->sector_count = num_sectors /
(blkdev->sector_size >> 9);
blkvsc_init_rw(blkvsc_req);
}
list_for_each_entry(blkvsc_req, &group->blkvsc_req_list, req_entry) {
if (pending) {
DPRINT_DBG(BLKVSC_DRV, "adding blkvsc_req to "
"pending_list - blkvsc_req %p start_sect %lu"
" sect_count %ld (%lu %ld)\n", blkvsc_req,
(unsigned long)blkvsc_req->sector_start,
blkvsc_req->sector_count,
(unsigned long)start_sector,
(unsigned long)num_sectors);
list_add_tail(&blkvsc_req->pend_entry,
&blkdev->pending_list);
} else {
ret = blkvsc_submit_request(blkvsc_req,
blkvsc_request_completion);
if (ret == -1) {
pending = 1;
list_add_tail(&blkvsc_req->pend_entry,
&blkdev->pending_list);
}
DPRINT_DBG(BLKVSC_DRV, "submitted blkvsc_req %p "
"start_sect %lu sect_count %ld (%lu %ld) "
"ret %d\n", blkvsc_req,
(unsigned long)blkvsc_req->sector_start,
blkvsc_req->sector_count,
(unsigned long)start_sector,
num_sectors, ret);
}
}
return pending;
}
static void blkvsc_cmd_completion(struct hv_storvsc_request *request)
{
struct blkvsc_request *blkvsc_req =
(struct blkvsc_request *)request->Context;
struct block_device_context *blkdev =
(struct block_device_context *)blkvsc_req->dev;
struct scsi_sense_hdr sense_hdr;
DPRINT_DBG(BLKVSC_DRV, "blkvsc_cmd_completion() - req %p\n",
blkvsc_req);
blkdev->num_outstanding_reqs--;
if (blkvsc_req->request.Status)
if (scsi_normalize_sense(blkvsc_req->sense_buffer,
SCSI_SENSE_BUFFERSIZE, &sense_hdr))
scsi_print_sense_hdr("blkvsc", &sense_hdr);
blkvsc_req->cond = 1;
wake_up_interruptible(&blkvsc_req->wevent);
}
static void blkvsc_request_completion(struct hv_storvsc_request *request)
{
struct blkvsc_request *blkvsc_req =
(struct blkvsc_request *)request->Context;
struct block_device_context *blkdev =
(struct block_device_context *)blkvsc_req->dev;
unsigned long flags;
struct blkvsc_request *comp_req, *tmp;
ASSERT(blkvsc_req->group);
DPRINT_DBG(BLKVSC_DRV, "blkdev %p blkvsc_req %p group %p type %s "
"sect_start %lu sect_count %ld len %d group outstd %d "
"total outstd %d\n",
blkdev, blkvsc_req, blkvsc_req->group,
(blkvsc_req->write) ? "WRITE" : "READ",
(unsigned long)blkvsc_req->sector_start,
blkvsc_req->sector_count,
blkvsc_req->request.DataBuffer.Length,
blkvsc_req->group->outstanding,
blkdev->num_outstanding_reqs);
spin_lock_irqsave(&blkdev->lock, flags);
blkdev->num_outstanding_reqs--;
blkvsc_req->group->outstanding--;
/*
* Only start processing when all the blkvsc_reqs are
* completed. This guarantees no out-of-order blkvsc_req
* completion when calling end_that_request_first()
*/
if (blkvsc_req->group->outstanding == 0) {
list_for_each_entry_safe(comp_req, tmp,
&blkvsc_req->group->blkvsc_req_list,
req_entry) {
DPRINT_DBG(BLKVSC_DRV, "completing blkvsc_req %p "
"sect_start %lu sect_count %ld \n",
comp_req,
(unsigned long)comp_req->sector_start,
comp_req->sector_count);
list_del(&comp_req->req_entry);
if (!__blk_end_request(comp_req->req,
(!comp_req->request.Status ? 0 : -EIO),
comp_req->sector_count * blkdev->sector_size)) {
/*
* All the sectors have been xferred ie the
* request is done
*/
DPRINT_DBG(BLKVSC_DRV, "req %p COMPLETED\n",
comp_req->req);
kmem_cache_free(blkdev->request_pool,
comp_req->group);
}
kmem_cache_free(blkdev->request_pool, comp_req);
}
if (!blkdev->shutting_down) {
blkvsc_do_pending_reqs(blkdev);
blk_start_queue(blkdev->gd->queue);
blkvsc_request(blkdev->gd->queue);
}
}
spin_unlock_irqrestore(&blkdev->lock, flags);
}
static int blkvsc_cancel_pending_reqs(struct block_device_context *blkdev)
{
struct blkvsc_request *pend_req, *tmp;
struct blkvsc_request *comp_req, *tmp2;
int ret = 0;
DPRINT_DBG(BLKVSC_DRV, "blkvsc_cancel_pending_reqs()");
/* Flush the pending list first */
list_for_each_entry_safe(pend_req, tmp, &blkdev->pending_list,
pend_entry) {
/*
* The pend_req could be part of a partially completed
* request. If so, complete those req first until we
* hit the pend_req
*/
list_for_each_entry_safe(comp_req, tmp2,
&pend_req->group->blkvsc_req_list,
req_entry) {
DPRINT_DBG(BLKVSC_DRV, "completing blkvsc_req %p "
"sect_start %lu sect_count %ld \n",
comp_req,
(unsigned long) comp_req->sector_start,
comp_req->sector_count);
if (comp_req == pend_req)
break;
list_del(&comp_req->req_entry);
if (comp_req->req) {
ret = __blk_end_request(comp_req->req,
(!comp_req->request.Status ? 0 : -EIO),
comp_req->sector_count *
blkdev->sector_size);
ASSERT(ret != 0);
}
kmem_cache_free(blkdev->request_pool, comp_req);
}
DPRINT_DBG(BLKVSC_DRV, "cancelling pending request - %p\n",
pend_req);
list_del(&pend_req->pend_entry);
list_del(&pend_req->req_entry);
if (comp_req->req) {
if (!__blk_end_request(pend_req->req, -EIO,
pend_req->sector_count *
blkdev->sector_size)) {
/*
* All the sectors have been xferred ie the
* request is done
*/
DPRINT_DBG(BLKVSC_DRV,
"blkvsc_cancel_pending_reqs() - "
"req %p COMPLETED\n", pend_req->req);
kmem_cache_free(blkdev->request_pool,
pend_req->group);
}
}
kmem_cache_free(blkdev->request_pool, pend_req);
}
return ret;
}
static int blkvsc_do_pending_reqs(struct block_device_context *blkdev)
{
struct blkvsc_request *pend_req, *tmp;
int ret = 0;
/* Flush the pending list first */
list_for_each_entry_safe(pend_req, tmp, &blkdev->pending_list,
pend_entry) {
DPRINT_DBG(BLKVSC_DRV, "working off pending_list - %p\n",
pend_req);
ret = blkvsc_submit_request(pend_req,
blkvsc_request_completion);
if (ret != 0)
break;
else
list_del(&pend_req->pend_entry);
}
return ret;
}
static void blkvsc_request(struct request_queue *queue)
{
struct block_device_context *blkdev = NULL;
struct request *req;
int ret = 0;
DPRINT_DBG(BLKVSC_DRV, "- enter \n");
while ((req = blk_peek_request(queue)) != NULL) {
DPRINT_DBG(BLKVSC_DRV, "- req %p\n", req);
blkdev = req->rq_disk->private_data;
if (blkdev->shutting_down || !blk_fs_request(req) ||
blkdev->media_not_present) {
__blk_end_request_cur(req, 0);
continue;
}
ret = blkvsc_do_pending_reqs(blkdev);
if (ret != 0) {
DPRINT_DBG(BLKVSC_DRV,
"- stop queue - pending_list not empty\n");
blk_stop_queue(queue);
break;
}
blk_start_request(req);
ret = blkvsc_do_request(blkdev, req);
if (ret > 0) {
DPRINT_DBG(BLKVSC_DRV, "- stop queue - no room\n");
blk_stop_queue(queue);
break;
} else if (ret < 0) {
DPRINT_DBG(BLKVSC_DRV, "- stop queue - no mem\n");
blk_requeue_request(queue, req);
blk_stop_queue(queue);
break;
}
}
}
static int blkvsc_open(struct block_device *bdev, fmode_t mode)
{
struct block_device_context *blkdev = bdev->bd_disk->private_data;
DPRINT_DBG(BLKVSC_DRV, "- users %d disk %s\n", blkdev->users,
blkdev->gd->disk_name);
spin_lock(&blkdev->lock);
if (!blkdev->users && blkdev->device_type == DVD_TYPE) {
spin_unlock(&blkdev->lock);
check_disk_change(bdev);
spin_lock(&blkdev->lock);
}
blkdev->users++;
spin_unlock(&blkdev->lock);
return 0;
}
static int blkvsc_release(struct gendisk *disk, fmode_t mode)
{
struct block_device_context *blkdev = disk->private_data;
DPRINT_DBG(BLKVSC_DRV, "- users %d disk %s\n", blkdev->users,
blkdev->gd->disk_name);
spin_lock(&blkdev->lock);
if (blkdev->users == 1) {
spin_unlock(&blkdev->lock);
blkvsc_do_flush(blkdev);
spin_lock(&blkdev->lock);
}
blkdev->users--;
spin_unlock(&blkdev->lock);
return 0;
}
static int blkvsc_media_changed(struct gendisk *gd)
{
DPRINT_DBG(BLKVSC_DRV, "- enter\n");
return 1;
}
static int blkvsc_revalidate_disk(struct gendisk *gd)
{
struct block_device_context *blkdev = gd->private_data;
DPRINT_DBG(BLKVSC_DRV, "- enter\n");
if (blkdev->device_type == DVD_TYPE) {
blkvsc_do_read_capacity(blkdev);
set_capacity(blkdev->gd, blkdev->capacity *
(blkdev->sector_size/512));
blk_queue_logical_block_size(gd->queue, blkdev->sector_size);
}
return 0;
}
static int blkvsc_getgeo(struct block_device *bd, struct hd_geometry *hg)
{
sector_t total_sectors = get_capacity(bd->bd_disk);
sector_t cylinder_times_heads = 0;
sector_t temp = 0;
int sectors_per_track = 0;
int heads = 0;
int cylinders = 0;
int rem = 0;
if (total_sectors > (65535 * 16 * 255))
total_sectors = (65535 * 16 * 255);
if (total_sectors >= (65535 * 16 * 63)) {
sectors_per_track = 255;
heads = 16;
cylinder_times_heads = total_sectors;
/* sector_div stores the quotient in cylinder_times_heads */
rem = sector_div(cylinder_times_heads, sectors_per_track);
} else {
sectors_per_track = 17;
cylinder_times_heads = total_sectors;
/* sector_div stores the quotient in cylinder_times_heads */
rem = sector_div(cylinder_times_heads, sectors_per_track);
temp = cylinder_times_heads + 1023;
/* sector_div stores the quotient in temp */
rem = sector_div(temp, 1024);
heads = temp;
if (heads < 4)
heads = 4;
if (cylinder_times_heads >= (heads * 1024) || (heads > 16)) {
sectors_per_track = 31;
heads = 16;
cylinder_times_heads = total_sectors;
/*
* sector_div stores the quotient in
* cylinder_times_heads
*/
rem = sector_div(cylinder_times_heads,
sectors_per_track);
}
if (cylinder_times_heads >= (heads * 1024)) {
sectors_per_track = 63;
heads = 16;
cylinder_times_heads = total_sectors;
/*
* sector_div stores the quotient in
* cylinder_times_heads
*/
rem = sector_div(cylinder_times_heads,
sectors_per_track);
}
}
temp = cylinder_times_heads;
/* sector_div stores the quotient in temp */
rem = sector_div(temp, heads);
cylinders = temp;
hg->heads = heads;
hg->sectors = sectors_per_track;
hg->cylinders = cylinders;
DPRINT_INFO(BLKVSC_DRV, "CHS (%d, %d, %d)", cylinders, heads,
sectors_per_track);
return 0;
}
static int blkvsc_ioctl(struct block_device *bd, fmode_t mode,
unsigned cmd, unsigned long argument)
{
/* struct block_device_context *blkdev = bd->bd_disk->private_data; */
int ret;
switch (cmd) {
/*
* TODO: I think there is certain format for HDIO_GET_IDENTITY rather
* than just a GUID. Commented it out for now.
*/
#if 0
case HDIO_GET_IDENTITY:
DPRINT_INFO(BLKVSC_DRV, "HDIO_GET_IDENTITY\n");
if (copy_to_user((void __user *)arg, blkdev->device_id,
blkdev->device_id_len))
ret = -EFAULT;
break;
#endif
default:
ret = -EINVAL;
break;
}
return ret;
}
static int __init blkvsc_init(void)
{
int ret;
ASSERT(sizeof(sector_t) == 8); /* Make sure CONFIG_LBD is set */
DPRINT_ENTER(BLKVSC_DRV);
DPRINT_INFO(BLKVSC_DRV, "Blkvsc initializing....");
ret = blkvsc_drv_init(BlkVscInitialize);
DPRINT_EXIT(BLKVSC_DRV);
return ret;
}
static void __exit blkvsc_exit(void)
{
DPRINT_ENTER(BLKVSC_DRV);
blkvsc_drv_exit();
DPRINT_ENTER(BLKVSC_DRV);
}
MODULE_LICENSE("GPL");
module_param(blkvsc_ringbuffer_size, int, S_IRUGO);
module_init(blkvsc_init);
module_exit(blkvsc_exit);
| gpl-2.0 |
windxixi/ef39s_kernel | drivers/input/touchscreen/eeti_ts.c | 905 | 8002 | /*
* Touch Screen driver for EETI's I2C connected touch screen panels
* Copyright (c) 2009 Daniel Mack <daniel@caiaq.de>
*
* See EETI's software guide for the protocol specification:
* http://home.eeti.com.tw/web20/eg/guide.htm
*
* Based on migor_ts.c
* Copyright (c) 2008 Magnus Damm
* Copyright (c) 2007 Ujjwal Pande <ujjwal@kenati.com>
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This file is 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/timer.h>
#include <linux/gpio.h>
#include <linux/input/eeti_ts.h>
#include <linux/slab.h>
static int flip_x;
module_param(flip_x, bool, 0644);
MODULE_PARM_DESC(flip_x, "flip x coordinate");
static int flip_y;
module_param(flip_y, bool, 0644);
MODULE_PARM_DESC(flip_y, "flip y coordinate");
struct eeti_ts_priv {
struct i2c_client *client;
struct input_dev *input;
struct work_struct work;
struct mutex mutex;
int irq, irq_active_high;
};
#define EETI_TS_BITDEPTH (11)
#define EETI_MAXVAL ((1 << (EETI_TS_BITDEPTH + 1)) - 1)
#define REPORT_BIT_PRESSED (1 << 0)
#define REPORT_BIT_AD0 (1 << 1)
#define REPORT_BIT_AD1 (1 << 2)
#define REPORT_BIT_HAS_PRESSURE (1 << 6)
#define REPORT_RES_BITS(v) (((v) >> 1) + EETI_TS_BITDEPTH)
static inline int eeti_ts_irq_active(struct eeti_ts_priv *priv)
{
return gpio_get_value(irq_to_gpio(priv->irq)) == priv->irq_active_high;
}
static void eeti_ts_read(struct work_struct *work)
{
char buf[6];
unsigned int x, y, res, pressed, to = 100;
struct eeti_ts_priv *priv =
container_of(work, struct eeti_ts_priv, work);
mutex_lock(&priv->mutex);
while (eeti_ts_irq_active(priv) && --to)
i2c_master_recv(priv->client, buf, sizeof(buf));
if (!to) {
dev_err(&priv->client->dev,
"unable to clear IRQ - line stuck?\n");
goto out;
}
/* drop non-report packets */
if (!(buf[0] & 0x80))
goto out;
pressed = buf[0] & REPORT_BIT_PRESSED;
res = REPORT_RES_BITS(buf[0] & (REPORT_BIT_AD0 | REPORT_BIT_AD1));
x = buf[2] | (buf[1] << 8);
y = buf[4] | (buf[3] << 8);
/* fix the range to 11 bits */
x >>= res - EETI_TS_BITDEPTH;
y >>= res - EETI_TS_BITDEPTH;
if (flip_x)
x = EETI_MAXVAL - x;
if (flip_y)
y = EETI_MAXVAL - y;
if (buf[0] & REPORT_BIT_HAS_PRESSURE)
input_report_abs(priv->input, ABS_PRESSURE, buf[5]);
input_report_abs(priv->input, ABS_X, x);
input_report_abs(priv->input, ABS_Y, y);
input_report_key(priv->input, BTN_TOUCH, !!pressed);
input_sync(priv->input);
out:
mutex_unlock(&priv->mutex);
}
static irqreturn_t eeti_ts_isr(int irq, void *dev_id)
{
struct eeti_ts_priv *priv = dev_id;
/* postpone I2C transactions as we are atomic */
schedule_work(&priv->work);
return IRQ_HANDLED;
}
static void eeti_ts_start(struct eeti_ts_priv *priv)
{
enable_irq(priv->irq);
/* Read the events once to arm the IRQ */
eeti_ts_read(&priv->work);
}
static void eeti_ts_stop(struct eeti_ts_priv *priv)
{
disable_irq(priv->irq);
cancel_work_sync(&priv->work);
}
static int eeti_ts_open(struct input_dev *dev)
{
struct eeti_ts_priv *priv = input_get_drvdata(dev);
eeti_ts_start(priv);
return 0;
}
static void eeti_ts_close(struct input_dev *dev)
{
struct eeti_ts_priv *priv = input_get_drvdata(dev);
eeti_ts_stop(priv);
}
static int __devinit eeti_ts_probe(struct i2c_client *client,
const struct i2c_device_id *idp)
{
struct eeti_ts_platform_data *pdata;
struct eeti_ts_priv *priv;
struct input_dev *input;
unsigned int irq_flags;
int err = -ENOMEM;
/*
* In contrast to what's described in the datasheet, there seems
* to be no way of probing the presence of that device using I2C
* commands. So we need to blindly believe it is there, and wait
* for interrupts to occur.
*/
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv) {
dev_err(&client->dev, "failed to allocate driver data\n");
goto err0;
}
mutex_init(&priv->mutex);
input = input_allocate_device();
if (!input) {
dev_err(&client->dev, "Failed to allocate input device.\n");
goto err1;
}
input->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(input, ABS_X, 0, EETI_MAXVAL, 0, 0);
input_set_abs_params(input, ABS_Y, 0, EETI_MAXVAL, 0, 0);
input_set_abs_params(input, ABS_PRESSURE, 0, 0xff, 0, 0);
input->name = client->name;
input->id.bustype = BUS_I2C;
input->dev.parent = &client->dev;
input->open = eeti_ts_open;
input->close = eeti_ts_close;
priv->client = client;
priv->input = input;
priv->irq = client->irq;
pdata = client->dev.platform_data;
if (pdata)
priv->irq_active_high = pdata->irq_active_high;
irq_flags = priv->irq_active_high ?
IRQF_TRIGGER_RISING : IRQF_TRIGGER_FALLING;
INIT_WORK(&priv->work, eeti_ts_read);
i2c_set_clientdata(client, priv);
input_set_drvdata(input, priv);
err = input_register_device(input);
if (err)
goto err1;
err = request_irq(priv->irq, eeti_ts_isr, irq_flags,
client->name, priv);
if (err) {
dev_err(&client->dev, "Unable to request touchscreen IRQ.\n");
goto err2;
}
/*
* Disable the device for now. It will be enabled once the
* input device is opened.
*/
eeti_ts_stop(priv);
device_init_wakeup(&client->dev, 0);
return 0;
err2:
input_unregister_device(input);
input = NULL; /* so we dont try to free it below */
err1:
input_free_device(input);
kfree(priv);
err0:
return err;
}
static int __devexit eeti_ts_remove(struct i2c_client *client)
{
struct eeti_ts_priv *priv = i2c_get_clientdata(client);
free_irq(priv->irq, priv);
/*
* eeti_ts_stop() leaves IRQ disabled. We need to re-enable it
* so that device still works if we reload the driver.
*/
enable_irq(priv->irq);
input_unregister_device(priv->input);
kfree(priv);
return 0;
}
#ifdef CONFIG_PM
static int eeti_ts_suspend(struct i2c_client *client, pm_message_t mesg)
{
struct eeti_ts_priv *priv = i2c_get_clientdata(client);
struct input_dev *input_dev = priv->input;
mutex_lock(&input_dev->mutex);
if (input_dev->users)
eeti_ts_stop(priv);
mutex_unlock(&input_dev->mutex);
if (device_may_wakeup(&client->dev))
enable_irq_wake(priv->irq);
return 0;
}
static int eeti_ts_resume(struct i2c_client *client)
{
struct eeti_ts_priv *priv = i2c_get_clientdata(client);
struct input_dev *input_dev = priv->input;
if (device_may_wakeup(&client->dev))
disable_irq_wake(priv->irq);
mutex_lock(&input_dev->mutex);
if (input_dev->users)
eeti_ts_start(priv);
mutex_unlock(&input_dev->mutex);
return 0;
}
#else
#define eeti_ts_suspend NULL
#define eeti_ts_resume NULL
#endif
static const struct i2c_device_id eeti_ts_id[] = {
{ "eeti_ts", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, eeti_ts_id);
static struct i2c_driver eeti_ts_driver = {
.driver = {
.name = "eeti_ts",
},
.probe = eeti_ts_probe,
.remove = __devexit_p(eeti_ts_remove),
.suspend = eeti_ts_suspend,
.resume = eeti_ts_resume,
.id_table = eeti_ts_id,
};
static int __init eeti_ts_init(void)
{
return i2c_add_driver(&eeti_ts_driver);
}
static void __exit eeti_ts_exit(void)
{
i2c_del_driver(&eeti_ts_driver);
}
MODULE_DESCRIPTION("EETI Touchscreen driver");
MODULE_AUTHOR("Daniel Mack <daniel@caiaq.de>");
MODULE_LICENSE("GPL");
module_init(eeti_ts_init);
module_exit(eeti_ts_exit);
| gpl-2.0 |
jiankangshiye/linux-2.6.39-9G45 | arch/s390/kernel/compat_linux.c | 1929 | 17723 | /*
* arch/s390x/kernel/linux32.c
*
* S390 version
* Copyright (C) 2000 IBM Deutschland Entwicklung GmbH, IBM Corporation
* Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com),
* Gerhard Tonn (ton@de.ibm.com)
* Thomas Spatzier (tspat@de.ibm.com)
*
* Conversion between 31bit and 64bit native syscalls.
*
* Heavily inspired by the 32-bit Sparc compat code which is
* Copyright (C) 1997,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu)
*
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/file.h>
#include <linux/signal.h>
#include <linux/resource.h>
#include <linux/times.h>
#include <linux/smp.h>
#include <linux/sem.h>
#include <linux/msg.h>
#include <linux/shm.h>
#include <linux/uio.h>
#include <linux/quota.h>
#include <linux/module.h>
#include <linux/poll.h>
#include <linux/personality.h>
#include <linux/stat.h>
#include <linux/filter.h>
#include <linux/highmem.h>
#include <linux/highuid.h>
#include <linux/mman.h>
#include <linux/ipv6.h>
#include <linux/in.h>
#include <linux/icmpv6.h>
#include <linux/syscalls.h>
#include <linux/sysctl.h>
#include <linux/binfmts.h>
#include <linux/capability.h>
#include <linux/compat.h>
#include <linux/vfs.h>
#include <linux/ptrace.h>
#include <linux/fadvise.h>
#include <linux/ipc.h>
#include <linux/slab.h>
#include <asm/types.h>
#include <asm/uaccess.h>
#include <net/scm.h>
#include <net/sock.h>
#include "compat_linux.h"
long psw_user32_bits = (PSW_BASE32_BITS | PSW_MASK_DAT | PSW_ASC_HOME |
PSW_MASK_IO | PSW_MASK_EXT | PSW_MASK_MCHECK |
PSW_MASK_PSTATE | PSW_DEFAULT_KEY);
long psw32_user_bits = (PSW32_BASE_BITS | PSW32_MASK_DAT | PSW32_ASC_HOME |
PSW32_MASK_IO | PSW32_MASK_EXT | PSW32_MASK_MCHECK |
PSW32_MASK_PSTATE);
/* For this source file, we want overflow handling. */
#undef high2lowuid
#undef high2lowgid
#undef low2highuid
#undef low2highgid
#undef SET_UID16
#undef SET_GID16
#undef NEW_TO_OLD_UID
#undef NEW_TO_OLD_GID
#undef SET_OLDSTAT_UID
#undef SET_OLDSTAT_GID
#undef SET_STAT_UID
#undef SET_STAT_GID
#define high2lowuid(uid) ((uid) > 65535) ? (u16)overflowuid : (u16)(uid)
#define high2lowgid(gid) ((gid) > 65535) ? (u16)overflowgid : (u16)(gid)
#define low2highuid(uid) ((uid) == (u16)-1) ? (uid_t)-1 : (uid_t)(uid)
#define low2highgid(gid) ((gid) == (u16)-1) ? (gid_t)-1 : (gid_t)(gid)
#define SET_UID16(var, uid) var = high2lowuid(uid)
#define SET_GID16(var, gid) var = high2lowgid(gid)
#define NEW_TO_OLD_UID(uid) high2lowuid(uid)
#define NEW_TO_OLD_GID(gid) high2lowgid(gid)
#define SET_OLDSTAT_UID(stat, uid) (stat).st_uid = high2lowuid(uid)
#define SET_OLDSTAT_GID(stat, gid) (stat).st_gid = high2lowgid(gid)
#define SET_STAT_UID(stat, uid) (stat).st_uid = high2lowuid(uid)
#define SET_STAT_GID(stat, gid) (stat).st_gid = high2lowgid(gid)
asmlinkage long sys32_chown16(const char __user * filename, u16 user, u16 group)
{
return sys_chown(filename, low2highuid(user), low2highgid(group));
}
asmlinkage long sys32_lchown16(const char __user * filename, u16 user, u16 group)
{
return sys_lchown(filename, low2highuid(user), low2highgid(group));
}
asmlinkage long sys32_fchown16(unsigned int fd, u16 user, u16 group)
{
return sys_fchown(fd, low2highuid(user), low2highgid(group));
}
asmlinkage long sys32_setregid16(u16 rgid, u16 egid)
{
return sys_setregid(low2highgid(rgid), low2highgid(egid));
}
asmlinkage long sys32_setgid16(u16 gid)
{
return sys_setgid((gid_t)gid);
}
asmlinkage long sys32_setreuid16(u16 ruid, u16 euid)
{
return sys_setreuid(low2highuid(ruid), low2highuid(euid));
}
asmlinkage long sys32_setuid16(u16 uid)
{
return sys_setuid((uid_t)uid);
}
asmlinkage long sys32_setresuid16(u16 ruid, u16 euid, u16 suid)
{
return sys_setresuid(low2highuid(ruid), low2highuid(euid),
low2highuid(suid));
}
asmlinkage long sys32_getresuid16(u16 __user *ruid, u16 __user *euid, u16 __user *suid)
{
int retval;
if (!(retval = put_user(high2lowuid(current->cred->uid), ruid)) &&
!(retval = put_user(high2lowuid(current->cred->euid), euid)))
retval = put_user(high2lowuid(current->cred->suid), suid);
return retval;
}
asmlinkage long sys32_setresgid16(u16 rgid, u16 egid, u16 sgid)
{
return sys_setresgid(low2highgid(rgid), low2highgid(egid),
low2highgid(sgid));
}
asmlinkage long sys32_getresgid16(u16 __user *rgid, u16 __user *egid, u16 __user *sgid)
{
int retval;
if (!(retval = put_user(high2lowgid(current->cred->gid), rgid)) &&
!(retval = put_user(high2lowgid(current->cred->egid), egid)))
retval = put_user(high2lowgid(current->cred->sgid), sgid);
return retval;
}
asmlinkage long sys32_setfsuid16(u16 uid)
{
return sys_setfsuid((uid_t)uid);
}
asmlinkage long sys32_setfsgid16(u16 gid)
{
return sys_setfsgid((gid_t)gid);
}
static int groups16_to_user(u16 __user *grouplist, struct group_info *group_info)
{
int i;
u16 group;
for (i = 0; i < group_info->ngroups; i++) {
group = (u16)GROUP_AT(group_info, i);
if (put_user(group, grouplist+i))
return -EFAULT;
}
return 0;
}
static int groups16_from_user(struct group_info *group_info, u16 __user *grouplist)
{
int i;
u16 group;
for (i = 0; i < group_info->ngroups; i++) {
if (get_user(group, grouplist+i))
return -EFAULT;
GROUP_AT(group_info, i) = (gid_t)group;
}
return 0;
}
asmlinkage long sys32_getgroups16(int gidsetsize, u16 __user *grouplist)
{
int i;
if (gidsetsize < 0)
return -EINVAL;
get_group_info(current->cred->group_info);
i = current->cred->group_info->ngroups;
if (gidsetsize) {
if (i > gidsetsize) {
i = -EINVAL;
goto out;
}
if (groups16_to_user(grouplist, current->cred->group_info)) {
i = -EFAULT;
goto out;
}
}
out:
put_group_info(current->cred->group_info);
return i;
}
asmlinkage long sys32_setgroups16(int gidsetsize, u16 __user *grouplist)
{
struct group_info *group_info;
int retval;
if (!capable(CAP_SETGID))
return -EPERM;
if ((unsigned)gidsetsize > NGROUPS_MAX)
return -EINVAL;
group_info = groups_alloc(gidsetsize);
if (!group_info)
return -ENOMEM;
retval = groups16_from_user(group_info, grouplist);
if (retval) {
put_group_info(group_info);
return retval;
}
retval = set_current_groups(group_info);
put_group_info(group_info);
return retval;
}
asmlinkage long sys32_getuid16(void)
{
return high2lowuid(current->cred->uid);
}
asmlinkage long sys32_geteuid16(void)
{
return high2lowuid(current->cred->euid);
}
asmlinkage long sys32_getgid16(void)
{
return high2lowgid(current->cred->gid);
}
asmlinkage long sys32_getegid16(void)
{
return high2lowgid(current->cred->egid);
}
/*
* sys32_ipc() is the de-multiplexer for the SysV IPC calls in 32bit emulation.
*
* This is really horribly ugly.
*/
#ifdef CONFIG_SYSVIPC
asmlinkage long sys32_ipc(u32 call, int first, int second, int third, u32 ptr)
{
if (call >> 16) /* hack for backward compatibility */
return -EINVAL;
call &= 0xffff;
switch (call) {
case SEMTIMEDOP:
return compat_sys_semtimedop(first, compat_ptr(ptr),
second, compat_ptr(third));
case SEMOP:
/* struct sembuf is the same on 32 and 64bit :)) */
return sys_semtimedop(first, compat_ptr(ptr),
second, NULL);
case SEMGET:
return sys_semget(first, second, third);
case SEMCTL:
return compat_sys_semctl(first, second, third,
compat_ptr(ptr));
case MSGSND:
return compat_sys_msgsnd(first, second, third,
compat_ptr(ptr));
case MSGRCV:
return compat_sys_msgrcv(first, second, 0, third,
0, compat_ptr(ptr));
case MSGGET:
return sys_msgget((key_t) first, second);
case MSGCTL:
return compat_sys_msgctl(first, second, compat_ptr(ptr));
case SHMAT:
return compat_sys_shmat(first, second, third,
0, compat_ptr(ptr));
case SHMDT:
return sys_shmdt(compat_ptr(ptr));
case SHMGET:
return sys_shmget(first, (unsigned)second, third);
case SHMCTL:
return compat_sys_shmctl(first, second, compat_ptr(ptr));
}
return -ENOSYS;
}
#endif
asmlinkage long sys32_truncate64(const char __user * path, unsigned long high, unsigned long low)
{
if ((int)high < 0)
return -EINVAL;
else
return sys_truncate(path, (high << 32) | low);
}
asmlinkage long sys32_ftruncate64(unsigned int fd, unsigned long high, unsigned long low)
{
if ((int)high < 0)
return -EINVAL;
else
return sys_ftruncate(fd, (high << 32) | low);
}
asmlinkage long sys32_sched_rr_get_interval(compat_pid_t pid,
struct compat_timespec __user *interval)
{
struct timespec t;
int ret;
mm_segment_t old_fs = get_fs ();
set_fs (KERNEL_DS);
ret = sys_sched_rr_get_interval(pid,
(struct timespec __force __user *) &t);
set_fs (old_fs);
if (put_compat_timespec(&t, interval))
return -EFAULT;
return ret;
}
asmlinkage long sys32_rt_sigprocmask(int how, compat_sigset_t __user *set,
compat_sigset_t __user *oset, size_t sigsetsize)
{
sigset_t s;
compat_sigset_t s32;
int ret;
mm_segment_t old_fs = get_fs();
if (set) {
if (copy_from_user (&s32, set, sizeof(compat_sigset_t)))
return -EFAULT;
switch (_NSIG_WORDS) {
case 4: s.sig[3] = s32.sig[6] | (((long)s32.sig[7]) << 32);
case 3: s.sig[2] = s32.sig[4] | (((long)s32.sig[5]) << 32);
case 2: s.sig[1] = s32.sig[2] | (((long)s32.sig[3]) << 32);
case 1: s.sig[0] = s32.sig[0] | (((long)s32.sig[1]) << 32);
}
}
set_fs (KERNEL_DS);
ret = sys_rt_sigprocmask(how,
set ? (sigset_t __force __user *) &s : NULL,
oset ? (sigset_t __force __user *) &s : NULL,
sigsetsize);
set_fs (old_fs);
if (ret) return ret;
if (oset) {
switch (_NSIG_WORDS) {
case 4: s32.sig[7] = (s.sig[3] >> 32); s32.sig[6] = s.sig[3];
case 3: s32.sig[5] = (s.sig[2] >> 32); s32.sig[4] = s.sig[2];
case 2: s32.sig[3] = (s.sig[1] >> 32); s32.sig[2] = s.sig[1];
case 1: s32.sig[1] = (s.sig[0] >> 32); s32.sig[0] = s.sig[0];
}
if (copy_to_user (oset, &s32, sizeof(compat_sigset_t)))
return -EFAULT;
}
return 0;
}
asmlinkage long sys32_rt_sigpending(compat_sigset_t __user *set,
size_t sigsetsize)
{
sigset_t s;
compat_sigset_t s32;
int ret;
mm_segment_t old_fs = get_fs();
set_fs (KERNEL_DS);
ret = sys_rt_sigpending((sigset_t __force __user *) &s, sigsetsize);
set_fs (old_fs);
if (!ret) {
switch (_NSIG_WORDS) {
case 4: s32.sig[7] = (s.sig[3] >> 32); s32.sig[6] = s.sig[3];
case 3: s32.sig[5] = (s.sig[2] >> 32); s32.sig[4] = s.sig[2];
case 2: s32.sig[3] = (s.sig[1] >> 32); s32.sig[2] = s.sig[1];
case 1: s32.sig[1] = (s.sig[0] >> 32); s32.sig[0] = s.sig[0];
}
if (copy_to_user (set, &s32, sizeof(compat_sigset_t)))
return -EFAULT;
}
return ret;
}
asmlinkage long
sys32_rt_sigqueueinfo(int pid, int sig, compat_siginfo_t __user *uinfo)
{
siginfo_t info;
int ret;
mm_segment_t old_fs = get_fs();
if (copy_siginfo_from_user32(&info, uinfo))
return -EFAULT;
set_fs (KERNEL_DS);
ret = sys_rt_sigqueueinfo(pid, sig, (siginfo_t __force __user *) &info);
set_fs (old_fs);
return ret;
}
/*
* sys32_execve() executes a new program after the asm stub has set
* things up for us. This should basically do what I want it to.
*/
asmlinkage long sys32_execve(const char __user *name, compat_uptr_t __user *argv,
compat_uptr_t __user *envp)
{
struct pt_regs *regs = task_pt_regs(current);
char *filename;
long rc;
filename = getname(name);
rc = PTR_ERR(filename);
if (IS_ERR(filename))
return rc;
rc = compat_do_execve(filename, argv, envp, regs);
if (rc)
goto out;
current->thread.fp_regs.fpc=0;
asm volatile("sfpc %0,0" : : "d" (0));
rc = regs->gprs[2];
out:
putname(filename);
return rc;
}
asmlinkage long sys32_pread64(unsigned int fd, char __user *ubuf,
size_t count, u32 poshi, u32 poslo)
{
if ((compat_ssize_t) count < 0)
return -EINVAL;
return sys_pread64(fd, ubuf, count, ((loff_t)AA(poshi) << 32) | AA(poslo));
}
asmlinkage long sys32_pwrite64(unsigned int fd, const char __user *ubuf,
size_t count, u32 poshi, u32 poslo)
{
if ((compat_ssize_t) count < 0)
return -EINVAL;
return sys_pwrite64(fd, ubuf, count, ((loff_t)AA(poshi) << 32) | AA(poslo));
}
asmlinkage compat_ssize_t sys32_readahead(int fd, u32 offhi, u32 offlo, s32 count)
{
return sys_readahead(fd, ((loff_t)AA(offhi) << 32) | AA(offlo), count);
}
asmlinkage long sys32_sendfile(int out_fd, int in_fd, compat_off_t __user *offset, size_t count)
{
mm_segment_t old_fs = get_fs();
int ret;
off_t of;
if (offset && get_user(of, offset))
return -EFAULT;
set_fs(KERNEL_DS);
ret = sys_sendfile(out_fd, in_fd,
offset ? (off_t __force __user *) &of : NULL, count);
set_fs(old_fs);
if (offset && put_user(of, offset))
return -EFAULT;
return ret;
}
asmlinkage long sys32_sendfile64(int out_fd, int in_fd,
compat_loff_t __user *offset, s32 count)
{
mm_segment_t old_fs = get_fs();
int ret;
loff_t lof;
if (offset && get_user(lof, offset))
return -EFAULT;
set_fs(KERNEL_DS);
ret = sys_sendfile64(out_fd, in_fd,
offset ? (loff_t __force __user *) &lof : NULL,
count);
set_fs(old_fs);
if (offset && put_user(lof, offset))
return -EFAULT;
return ret;
}
struct stat64_emu31 {
unsigned long long st_dev;
unsigned int __pad1;
#define STAT64_HAS_BROKEN_ST_INO 1
u32 __st_ino;
unsigned int st_mode;
unsigned int st_nlink;
u32 st_uid;
u32 st_gid;
unsigned long long st_rdev;
unsigned int __pad3;
long st_size;
u32 st_blksize;
unsigned char __pad4[4];
u32 __pad5; /* future possible st_blocks high bits */
u32 st_blocks; /* Number 512-byte blocks allocated. */
u32 st_atime;
u32 __pad6;
u32 st_mtime;
u32 __pad7;
u32 st_ctime;
u32 __pad8; /* will be high 32 bits of ctime someday */
unsigned long st_ino;
};
static int cp_stat64(struct stat64_emu31 __user *ubuf, struct kstat *stat)
{
struct stat64_emu31 tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.st_dev = huge_encode_dev(stat->dev);
tmp.st_ino = stat->ino;
tmp.__st_ino = (u32)stat->ino;
tmp.st_mode = stat->mode;
tmp.st_nlink = (unsigned int)stat->nlink;
tmp.st_uid = stat->uid;
tmp.st_gid = stat->gid;
tmp.st_rdev = huge_encode_dev(stat->rdev);
tmp.st_size = stat->size;
tmp.st_blksize = (u32)stat->blksize;
tmp.st_blocks = (u32)stat->blocks;
tmp.st_atime = (u32)stat->atime.tv_sec;
tmp.st_mtime = (u32)stat->mtime.tv_sec;
tmp.st_ctime = (u32)stat->ctime.tv_sec;
return copy_to_user(ubuf,&tmp,sizeof(tmp)) ? -EFAULT : 0;
}
asmlinkage long sys32_stat64(const char __user * filename, struct stat64_emu31 __user * statbuf)
{
struct kstat stat;
int ret = vfs_stat(filename, &stat);
if (!ret)
ret = cp_stat64(statbuf, &stat);
return ret;
}
asmlinkage long sys32_lstat64(const char __user * filename, struct stat64_emu31 __user * statbuf)
{
struct kstat stat;
int ret = vfs_lstat(filename, &stat);
if (!ret)
ret = cp_stat64(statbuf, &stat);
return ret;
}
asmlinkage long sys32_fstat64(unsigned long fd, struct stat64_emu31 __user * statbuf)
{
struct kstat stat;
int ret = vfs_fstat(fd, &stat);
if (!ret)
ret = cp_stat64(statbuf, &stat);
return ret;
}
asmlinkage long sys32_fstatat64(unsigned int dfd, const char __user *filename,
struct stat64_emu31 __user* statbuf, int flag)
{
struct kstat stat;
int error;
error = vfs_fstatat(dfd, filename, &stat, flag);
if (error)
return error;
return cp_stat64(statbuf, &stat);
}
/*
* Linux/i386 didn't use to be able to handle more than
* 4 system call parameters, so these system calls used a memory
* block for parameter passing..
*/
struct mmap_arg_struct_emu31 {
compat_ulong_t addr;
compat_ulong_t len;
compat_ulong_t prot;
compat_ulong_t flags;
compat_ulong_t fd;
compat_ulong_t offset;
};
asmlinkage unsigned long old32_mmap(struct mmap_arg_struct_emu31 __user *arg)
{
struct mmap_arg_struct_emu31 a;
if (copy_from_user(&a, arg, sizeof(a)))
return -EFAULT;
if (a.offset & ~PAGE_MASK)
return -EINVAL;
a.addr = (unsigned long) compat_ptr(a.addr);
return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
a.offset >> PAGE_SHIFT);
}
asmlinkage long sys32_mmap2(struct mmap_arg_struct_emu31 __user *arg)
{
struct mmap_arg_struct_emu31 a;
if (copy_from_user(&a, arg, sizeof(a)))
return -EFAULT;
a.addr = (unsigned long) compat_ptr(a.addr);
return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd, a.offset);
}
asmlinkage long sys32_read(unsigned int fd, char __user * buf, size_t count)
{
if ((compat_ssize_t) count < 0)
return -EINVAL;
return sys_read(fd, buf, count);
}
asmlinkage long sys32_write(unsigned int fd, const char __user * buf, size_t count)
{
if ((compat_ssize_t) count < 0)
return -EINVAL;
return sys_write(fd, buf, count);
}
/*
* 31 bit emulation wrapper functions for sys_fadvise64/fadvise64_64.
* These need to rewrite the advise values for POSIX_FADV_{DONTNEED,NOREUSE}
* because the 31 bit values differ from the 64 bit values.
*/
asmlinkage long
sys32_fadvise64(int fd, loff_t offset, size_t len, int advise)
{
if (advise == 4)
advise = POSIX_FADV_DONTNEED;
else if (advise == 5)
advise = POSIX_FADV_NOREUSE;
return sys_fadvise64(fd, offset, len, advise);
}
struct fadvise64_64_args {
int fd;
long long offset;
long long len;
int advice;
};
asmlinkage long
sys32_fadvise64_64(struct fadvise64_64_args __user *args)
{
struct fadvise64_64_args a;
if ( copy_from_user(&a, args, sizeof(a)) )
return -EFAULT;
if (a.advice == 4)
a.advice = POSIX_FADV_DONTNEED;
else if (a.advice == 5)
a.advice = POSIX_FADV_NOREUSE;
return sys_fadvise64_64(a.fd, a.offset, a.len, a.advice);
}
| gpl-2.0 |
Dm47021/Linux-kernel_4.1.15-rt17_MusicOS | drivers/s390/char/fs3270.c | 1929 | 13049 | /*
* IBM/3270 Driver - fullscreen driver.
*
* Author(s):
* Original 3270 Code for 2.4 written by Richard Hitt (UTS Global)
* Rewritten for 2.5/2.6 by Martin Schwidefsky <schwidefsky@de.ibm.com>
* Copyright IBM Corp. 2003, 2009
*/
#include <linux/bootmem.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/compat.h>
#include <linux/module.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <asm/compat.h>
#include <asm/ccwdev.h>
#include <asm/cio.h>
#include <asm/ebcdic.h>
#include <asm/idals.h>
#include "raw3270.h"
#include "ctrlchar.h"
static struct raw3270_fn fs3270_fn;
struct fs3270 {
struct raw3270_view view;
struct pid *fs_pid; /* Pid of controlling program. */
int read_command; /* ccw command to use for reads. */
int write_command; /* ccw command to use for writes. */
int attention; /* Got attention. */
int active; /* Fullscreen view is active. */
struct raw3270_request *init; /* single init request. */
wait_queue_head_t wait; /* Init & attention wait queue. */
struct idal_buffer *rdbuf; /* full-screen-deactivate buffer */
size_t rdbuf_size; /* size of data returned by RDBUF */
};
static DEFINE_MUTEX(fs3270_mutex);
static void
fs3270_wake_up(struct raw3270_request *rq, void *data)
{
wake_up((wait_queue_head_t *) data);
}
static inline int
fs3270_working(struct fs3270 *fp)
{
/*
* The fullscreen view is in working order if the view
* has been activated AND the initial request is finished.
*/
return fp->active && raw3270_request_final(fp->init);
}
static int
fs3270_do_io(struct raw3270_view *view, struct raw3270_request *rq)
{
struct fs3270 *fp;
int rc;
fp = (struct fs3270 *) view;
rq->callback = fs3270_wake_up;
rq->callback_data = &fp->wait;
do {
if (!fs3270_working(fp)) {
/* Fullscreen view isn't ready yet. */
rc = wait_event_interruptible(fp->wait,
fs3270_working(fp));
if (rc != 0)
break;
}
rc = raw3270_start(view, rq);
if (rc == 0) {
/* Started successfully. Now wait for completion. */
wait_event(fp->wait, raw3270_request_final(rq));
}
} while (rc == -EACCES);
return rc;
}
/*
* Switch to the fullscreen view.
*/
static void
fs3270_reset_callback(struct raw3270_request *rq, void *data)
{
struct fs3270 *fp;
fp = (struct fs3270 *) rq->view;
raw3270_request_reset(rq);
wake_up(&fp->wait);
}
static void
fs3270_restore_callback(struct raw3270_request *rq, void *data)
{
struct fs3270 *fp;
fp = (struct fs3270 *) rq->view;
if (rq->rc != 0 || rq->rescnt != 0) {
if (fp->fs_pid)
kill_pid(fp->fs_pid, SIGHUP, 1);
}
fp->rdbuf_size = 0;
raw3270_request_reset(rq);
wake_up(&fp->wait);
}
static int
fs3270_activate(struct raw3270_view *view)
{
struct fs3270 *fp;
char *cp;
int rc;
fp = (struct fs3270 *) view;
/* If an old init command is still running just return. */
if (!raw3270_request_final(fp->init))
return 0;
if (fp->rdbuf_size == 0) {
/* No saved buffer. Just clear the screen. */
raw3270_request_set_cmd(fp->init, TC_EWRITEA);
fp->init->callback = fs3270_reset_callback;
} else {
/* Restore fullscreen buffer saved by fs3270_deactivate. */
raw3270_request_set_cmd(fp->init, TC_EWRITEA);
raw3270_request_set_idal(fp->init, fp->rdbuf);
fp->init->ccw.count = fp->rdbuf_size;
cp = fp->rdbuf->data[0];
cp[0] = TW_KR;
cp[1] = TO_SBA;
cp[2] = cp[6];
cp[3] = cp[7];
cp[4] = TO_IC;
cp[5] = TO_SBA;
cp[6] = 0x40;
cp[7] = 0x40;
fp->init->rescnt = 0;
fp->init->callback = fs3270_restore_callback;
}
rc = fp->init->rc = raw3270_start_locked(view, fp->init);
if (rc)
fp->init->callback(fp->init, NULL);
else
fp->active = 1;
return rc;
}
/*
* Shutdown fullscreen view.
*/
static void
fs3270_save_callback(struct raw3270_request *rq, void *data)
{
struct fs3270 *fp;
fp = (struct fs3270 *) rq->view;
/* Correct idal buffer element 0 address. */
fp->rdbuf->data[0] -= 5;
fp->rdbuf->size += 5;
/*
* If the rdbuf command failed or the idal buffer is
* to small for the amount of data returned by the
* rdbuf command, then we have no choice but to send
* a SIGHUP to the application.
*/
if (rq->rc != 0 || rq->rescnt == 0) {
if (fp->fs_pid)
kill_pid(fp->fs_pid, SIGHUP, 1);
fp->rdbuf_size = 0;
} else
fp->rdbuf_size = fp->rdbuf->size - rq->rescnt;
raw3270_request_reset(rq);
wake_up(&fp->wait);
}
static void
fs3270_deactivate(struct raw3270_view *view)
{
struct fs3270 *fp;
fp = (struct fs3270 *) view;
fp->active = 0;
/* If an old init command is still running just return. */
if (!raw3270_request_final(fp->init))
return;
/* Prepare read-buffer request. */
raw3270_request_set_cmd(fp->init, TC_RDBUF);
/*
* Hackish: skip first 5 bytes of the idal buffer to make
* room for the TW_KR/TO_SBA/<address>/<address>/TO_IC sequence
* in the activation command.
*/
fp->rdbuf->data[0] += 5;
fp->rdbuf->size -= 5;
raw3270_request_set_idal(fp->init, fp->rdbuf);
fp->init->rescnt = 0;
fp->init->callback = fs3270_save_callback;
/* Start I/O to read in the 3270 buffer. */
fp->init->rc = raw3270_start_locked(view, fp->init);
if (fp->init->rc)
fp->init->callback(fp->init, NULL);
}
static int
fs3270_irq(struct fs3270 *fp, struct raw3270_request *rq, struct irb *irb)
{
/* Handle ATTN. Set indication and wake waiters for attention. */
if (irb->scsw.cmd.dstat & DEV_STAT_ATTENTION) {
fp->attention = 1;
wake_up(&fp->wait);
}
if (rq) {
if (irb->scsw.cmd.dstat & DEV_STAT_UNIT_CHECK)
rq->rc = -EIO;
else
/* Normal end. Copy residual count. */
rq->rescnt = irb->scsw.cmd.count;
}
return RAW3270_IO_DONE;
}
/*
* Process reads from fullscreen 3270.
*/
static ssize_t
fs3270_read(struct file *filp, char __user *data, size_t count, loff_t *off)
{
struct fs3270 *fp;
struct raw3270_request *rq;
struct idal_buffer *ib;
ssize_t rc;
if (count == 0 || count > 65535)
return -EINVAL;
fp = filp->private_data;
if (!fp)
return -ENODEV;
ib = idal_buffer_alloc(count, 0);
if (IS_ERR(ib))
return -ENOMEM;
rq = raw3270_request_alloc(0);
if (!IS_ERR(rq)) {
if (fp->read_command == 0 && fp->write_command != 0)
fp->read_command = 6;
raw3270_request_set_cmd(rq, fp->read_command ? : 2);
raw3270_request_set_idal(rq, ib);
rc = wait_event_interruptible(fp->wait, fp->attention);
fp->attention = 0;
if (rc == 0) {
rc = fs3270_do_io(&fp->view, rq);
if (rc == 0) {
count -= rq->rescnt;
if (idal_buffer_to_user(ib, data, count) != 0)
rc = -EFAULT;
else
rc = count;
}
}
raw3270_request_free(rq);
} else
rc = PTR_ERR(rq);
idal_buffer_free(ib);
return rc;
}
/*
* Process writes to fullscreen 3270.
*/
static ssize_t
fs3270_write(struct file *filp, const char __user *data, size_t count, loff_t *off)
{
struct fs3270 *fp;
struct raw3270_request *rq;
struct idal_buffer *ib;
int write_command;
ssize_t rc;
fp = filp->private_data;
if (!fp)
return -ENODEV;
ib = idal_buffer_alloc(count, 0);
if (IS_ERR(ib))
return -ENOMEM;
rq = raw3270_request_alloc(0);
if (!IS_ERR(rq)) {
if (idal_buffer_from_user(ib, data, count) == 0) {
write_command = fp->write_command ? : 1;
if (write_command == 5)
write_command = 13;
raw3270_request_set_cmd(rq, write_command);
raw3270_request_set_idal(rq, ib);
rc = fs3270_do_io(&fp->view, rq);
if (rc == 0)
rc = count - rq->rescnt;
} else
rc = -EFAULT;
raw3270_request_free(rq);
} else
rc = PTR_ERR(rq);
idal_buffer_free(ib);
return rc;
}
/*
* process ioctl commands for the tube driver
*/
static long
fs3270_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
char __user *argp;
struct fs3270 *fp;
struct raw3270_iocb iocb;
int rc;
fp = filp->private_data;
if (!fp)
return -ENODEV;
if (is_compat_task())
argp = compat_ptr(arg);
else
argp = (char __user *)arg;
rc = 0;
mutex_lock(&fs3270_mutex);
switch (cmd) {
case TUBICMD:
fp->read_command = arg;
break;
case TUBOCMD:
fp->write_command = arg;
break;
case TUBGETI:
rc = put_user(fp->read_command, argp);
break;
case TUBGETO:
rc = put_user(fp->write_command, argp);
break;
case TUBGETMOD:
iocb.model = fp->view.model;
iocb.line_cnt = fp->view.rows;
iocb.col_cnt = fp->view.cols;
iocb.pf_cnt = 24;
iocb.re_cnt = 20;
iocb.map = 0;
if (copy_to_user(argp, &iocb, sizeof(struct raw3270_iocb)))
rc = -EFAULT;
break;
}
mutex_unlock(&fs3270_mutex);
return rc;
}
/*
* Allocate fs3270 structure.
*/
static struct fs3270 *
fs3270_alloc_view(void)
{
struct fs3270 *fp;
fp = kzalloc(sizeof(struct fs3270),GFP_KERNEL);
if (!fp)
return ERR_PTR(-ENOMEM);
fp->init = raw3270_request_alloc(0);
if (IS_ERR(fp->init)) {
kfree(fp);
return ERR_PTR(-ENOMEM);
}
return fp;
}
/*
* Free fs3270 structure.
*/
static void
fs3270_free_view(struct raw3270_view *view)
{
struct fs3270 *fp;
fp = (struct fs3270 *) view;
if (fp->rdbuf)
idal_buffer_free(fp->rdbuf);
raw3270_request_free(((struct fs3270 *) view)->init);
kfree(view);
}
/*
* Unlink fs3270 data structure from filp.
*/
static void
fs3270_release(struct raw3270_view *view)
{
struct fs3270 *fp;
fp = (struct fs3270 *) view;
if (fp->fs_pid)
kill_pid(fp->fs_pid, SIGHUP, 1);
}
/* View to a 3270 device. Can be console, tty or fullscreen. */
static struct raw3270_fn fs3270_fn = {
.activate = fs3270_activate,
.deactivate = fs3270_deactivate,
.intv = (void *) fs3270_irq,
.release = fs3270_release,
.free = fs3270_free_view
};
/*
* This routine is called whenever a 3270 fullscreen device is opened.
*/
static int
fs3270_open(struct inode *inode, struct file *filp)
{
struct fs3270 *fp;
struct idal_buffer *ib;
int minor, rc = 0;
if (imajor(file_inode(filp)) != IBM_FS3270_MAJOR)
return -ENODEV;
minor = iminor(file_inode(filp));
/* Check for minor 0 multiplexer. */
if (minor == 0) {
struct tty_struct *tty = get_current_tty();
if (!tty || tty->driver->major != IBM_TTY3270_MAJOR) {
tty_kref_put(tty);
return -ENODEV;
}
minor = tty->index;
tty_kref_put(tty);
}
mutex_lock(&fs3270_mutex);
/* Check if some other program is already using fullscreen mode. */
fp = (struct fs3270 *) raw3270_find_view(&fs3270_fn, minor);
if (!IS_ERR(fp)) {
raw3270_put_view(&fp->view);
rc = -EBUSY;
goto out;
}
/* Allocate fullscreen view structure. */
fp = fs3270_alloc_view();
if (IS_ERR(fp)) {
rc = PTR_ERR(fp);
goto out;
}
init_waitqueue_head(&fp->wait);
fp->fs_pid = get_pid(task_pid(current));
rc = raw3270_add_view(&fp->view, &fs3270_fn, minor);
if (rc) {
fs3270_free_view(&fp->view);
goto out;
}
/* Allocate idal-buffer. */
ib = idal_buffer_alloc(2*fp->view.rows*fp->view.cols + 5, 0);
if (IS_ERR(ib)) {
raw3270_put_view(&fp->view);
raw3270_del_view(&fp->view);
rc = PTR_ERR(ib);
goto out;
}
fp->rdbuf = ib;
rc = raw3270_activate_view(&fp->view);
if (rc) {
raw3270_put_view(&fp->view);
raw3270_del_view(&fp->view);
goto out;
}
nonseekable_open(inode, filp);
filp->private_data = fp;
out:
mutex_unlock(&fs3270_mutex);
return rc;
}
/*
* This routine is called when the 3270 tty is closed. We wait
* for the remaining request to be completed. Then we clean up.
*/
static int
fs3270_close(struct inode *inode, struct file *filp)
{
struct fs3270 *fp;
fp = filp->private_data;
filp->private_data = NULL;
if (fp) {
put_pid(fp->fs_pid);
fp->fs_pid = NULL;
raw3270_reset(&fp->view);
raw3270_put_view(&fp->view);
raw3270_del_view(&fp->view);
}
return 0;
}
static const struct file_operations fs3270_fops = {
.owner = THIS_MODULE, /* owner */
.read = fs3270_read, /* read */
.write = fs3270_write, /* write */
.unlocked_ioctl = fs3270_ioctl, /* ioctl */
.compat_ioctl = fs3270_ioctl, /* ioctl */
.open = fs3270_open, /* open */
.release = fs3270_close, /* release */
.llseek = no_llseek,
};
static void fs3270_create_cb(int minor)
{
__register_chrdev(IBM_FS3270_MAJOR, minor, 1, "tub", &fs3270_fops);
device_create(class3270, NULL, MKDEV(IBM_FS3270_MAJOR, minor),
NULL, "3270/tub%d", minor);
}
static void fs3270_destroy_cb(int minor)
{
device_destroy(class3270, MKDEV(IBM_FS3270_MAJOR, minor));
__unregister_chrdev(IBM_FS3270_MAJOR, minor, 1, "tub");
}
static struct raw3270_notifier fs3270_notifier =
{
.create = fs3270_create_cb,
.destroy = fs3270_destroy_cb,
};
/*
* 3270 fullscreen driver initialization.
*/
static int __init
fs3270_init(void)
{
int rc;
rc = __register_chrdev(IBM_FS3270_MAJOR, 0, 1, "fs3270", &fs3270_fops);
if (rc)
return rc;
device_create(class3270, NULL, MKDEV(IBM_FS3270_MAJOR, 0),
NULL, "3270/tub");
raw3270_register_notifier(&fs3270_notifier);
return 0;
}
static void __exit
fs3270_exit(void)
{
raw3270_unregister_notifier(&fs3270_notifier);
device_destroy(class3270, MKDEV(IBM_FS3270_MAJOR, 0));
__unregister_chrdev(IBM_FS3270_MAJOR, 0, 1, "fs3270");
}
MODULE_LICENSE("GPL");
MODULE_ALIAS_CHARDEV_MAJOR(IBM_FS3270_MAJOR);
module_init(fs3270_init);
module_exit(fs3270_exit);
| gpl-2.0 |
MaxiCM/Samsung_STE_Kernel | arch/blackfin/mach-bf537/boards/minotaur.c | 2441 | 13444 | /*
* Copyright 2004-2009 Analog Devices Inc.
* 2008-2009 Cambridge Signal Processing
* 2005 National ICT Australia (NICTA)
* Aidan Williams <aidan@nicta.com.au>
*
* Licensed under the GPL-2 or later.
*/
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/spi/spi.h>
#include <linux/spi/flash.h>
#if defined(CONFIG_USB_ISP1362_HCD) || defined(CONFIG_USB_ISP1362_HCD_MODULE)
#include <linux/usb/isp1362.h>
#endif
#include <linux/ata_platform.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/usb/sl811.h>
#include <asm/dma.h>
#include <asm/bfin5xx_spi.h>
#include <asm/reboot.h>
#include <asm/portmux.h>
#include <linux/spi/ad7877.h>
/*
* Name the Board for the /proc/cpuinfo
*/
const char bfin_board_name[] = "CamSig Minotaur BF537";
#if defined(CONFIG_BFIN_CFPCMCIA) || defined(CONFIG_BFIN_CFPCMCIA_MODULE)
static struct resource bfin_pcmcia_cf_resources[] = {
{
.start = 0x20310000, /* IO PORT */
.end = 0x20312000,
.flags = IORESOURCE_MEM,
}, {
.start = 0x20311000, /* Attribute Memory */
.end = 0x20311FFF,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_PF4,
.end = IRQ_PF4,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWLEVEL,
}, {
.start = IRQ_PF6, /* Card Detect PF6 */
.end = IRQ_PF6,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bfin_pcmcia_cf_device = {
.name = "bfin_cf_pcmcia",
.id = -1,
.num_resources = ARRAY_SIZE(bfin_pcmcia_cf_resources),
.resource = bfin_pcmcia_cf_resources,
};
#endif
#if defined(CONFIG_RTC_DRV_BFIN) || defined(CONFIG_RTC_DRV_BFIN_MODULE)
static struct platform_device rtc_device = {
.name = "rtc-bfin",
.id = -1,
};
#endif
#if defined(CONFIG_BFIN_MAC) || defined(CONFIG_BFIN_MAC_MODULE)
#include <linux/bfin_mac.h>
static const unsigned short bfin_mac_peripherals[] = P_MII0;
static struct bfin_phydev_platform_data bfin_phydev_data[] = {
{
.addr = 1,
.irq = IRQ_MAC_PHYINT,
},
};
static struct bfin_mii_bus_platform_data bfin_mii_bus_data = {
.phydev_number = 1,
.phydev_data = bfin_phydev_data,
.phy_mode = PHY_INTERFACE_MODE_MII,
.mac_peripherals = bfin_mac_peripherals,
};
static struct platform_device bfin_mii_bus = {
.name = "bfin_mii_bus",
.dev = {
.platform_data = &bfin_mii_bus_data,
}
};
static struct platform_device bfin_mac_device = {
.name = "bfin_mac",
.dev = {
.platform_data = &bfin_mii_bus,
}
};
#endif
#if defined(CONFIG_USB_NET2272) || defined(CONFIG_USB_NET2272_MODULE)
static struct resource net2272_bfin_resources[] = {
{
.start = 0x20300000,
.end = 0x20300000 + 0x100,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_PF7,
.end = IRQ_PF7,
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHLEVEL,
},
};
static struct platform_device net2272_bfin_device = {
.name = "net2272",
.id = -1,
.num_resources = ARRAY_SIZE(net2272_bfin_resources),
.resource = net2272_bfin_resources,
};
#endif
#if defined(CONFIG_SPI_BFIN) || defined(CONFIG_SPI_BFIN_MODULE)
/* all SPI peripherals info goes here */
#if defined(CONFIG_MTD_M25P80) \
|| defined(CONFIG_MTD_M25P80_MODULE)
/* Partition sizes */
#define FLASH_SIZE 0x00400000
#define PSIZE_UBOOT 0x00030000
#define PSIZE_INITRAMFS 0x00240000
static struct mtd_partition bfin_spi_flash_partitions[] = {
{
.name = "bootloader(spi)",
.size = PSIZE_UBOOT,
.offset = 0x000000,
.mask_flags = MTD_CAP_ROM
}, {
.name = "initramfs(spi)",
.size = PSIZE_INITRAMFS,
.offset = PSIZE_UBOOT
}, {
.name = "opt(spi)",
.size = FLASH_SIZE - (PSIZE_UBOOT + PSIZE_INITRAMFS),
.offset = PSIZE_UBOOT + PSIZE_INITRAMFS,
}
};
static struct flash_platform_data bfin_spi_flash_data = {
.name = "m25p80",
.parts = bfin_spi_flash_partitions,
.nr_parts = ARRAY_SIZE(bfin_spi_flash_partitions),
.type = "m25p64",
};
/* SPI flash chip (m25p64) */
static struct bfin5xx_spi_chip spi_flash_chip_info = {
.enable_dma = 0, /* use dma transfer with this chip*/
.bits_per_word = 8,
};
#endif
#if defined(CONFIG_MMC_SPI) || defined(CONFIG_MMC_SPI_MODULE)
static struct bfin5xx_spi_chip mmc_spi_chip_info = {
.enable_dma = 0,
.bits_per_word = 8,
};
#endif
static struct spi_board_info bfin_spi_board_info[] __initdata = {
#if defined(CONFIG_MTD_M25P80) \
|| defined(CONFIG_MTD_M25P80_MODULE)
{
/* the modalias must be the same as spi device driver name */
.modalias = "m25p80", /* Name of spi_driver for this device */
.max_speed_hz = 25000000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0, /* Framework bus number */
.chip_select = 1, /* Framework chip select. On STAMP537 it is SPISSEL1*/
.platform_data = &bfin_spi_flash_data,
.controller_data = &spi_flash_chip_info,
.mode = SPI_MODE_3,
},
#endif
#if defined(CONFIG_MMC_SPI) || defined(CONFIG_MMC_SPI_MODULE)
{
.modalias = "mmc_spi",
.max_speed_hz = 5000000, /* max spi clock (SCK) speed in HZ */
.bus_num = 0,
.chip_select = 5,
.controller_data = &mmc_spi_chip_info,
.mode = SPI_MODE_3,
},
#endif
};
/* SPI controller data */
static struct bfin5xx_spi_master bfin_spi0_info = {
.num_chipselect = 8,
.enable_dma = 1, /* master has the ability to do dma transfer */
};
/* SPI (0) */
static struct resource bfin_spi0_resource[] = {
[0] = {
.start = SPI0_REGBASE,
.end = SPI0_REGBASE + 0xFF,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = CH_SPI,
.end = CH_SPI,
.flags = IORESOURCE_DMA,
},
[2] = {
.start = IRQ_SPI,
.end = IRQ_SPI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device bfin_spi0_device = {
.name = "bfin-spi",
.id = 0, /* Bus number */
.num_resources = ARRAY_SIZE(bfin_spi0_resource),
.resource = bfin_spi0_resource,
.dev = {
.platform_data = &bfin_spi0_info, /* Passed to driver */
},
};
#endif /* spi master and devices */
#if defined(CONFIG_SERIAL_BFIN) || defined(CONFIG_SERIAL_BFIN_MODULE)
#ifdef CONFIG_SERIAL_BFIN_UART0
static struct resource bfin_uart0_resources[] = {
{
.start = UART0_THR,
.end = UART0_GCTL+2,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART0_RX,
.end = IRQ_UART0_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART0_ERROR,
.end = IRQ_UART0_ERROR,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART0_TX,
.end = CH_UART0_TX,
.flags = IORESOURCE_DMA,
},
{
.start = CH_UART0_RX,
.end = CH_UART0_RX,
.flags = IORESOURCE_DMA,
},
};
static unsigned short bfin_uart0_peripherals[] = {
P_UART0_TX, P_UART0_RX, 0
};
static struct platform_device bfin_uart0_device = {
.name = "bfin-uart",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_uart0_resources),
.resource = bfin_uart0_resources,
.dev = {
.platform_data = &bfin_uart0_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_UART1
static struct resource bfin_uart1_resources[] = {
{
.start = UART1_THR,
.end = UART1_GCTL+2,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART1_RX,
.end = IRQ_UART1_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_UART1_ERROR,
.end = IRQ_UART1_ERROR,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART1_TX,
.end = CH_UART1_TX,
.flags = IORESOURCE_DMA,
},
{
.start = CH_UART1_RX,
.end = CH_UART1_RX,
.flags = IORESOURCE_DMA,
},
};
static unsigned short bfin_uart1_peripherals[] = {
P_UART1_TX, P_UART1_RX, 0
};
static struct platform_device bfin_uart1_device = {
.name = "bfin-uart",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_uart1_resources),
.resource = bfin_uart1_resources,
.dev = {
.platform_data = &bfin_uart1_peripherals, /* Passed to driver */
},
};
#endif
#endif
#if defined(CONFIG_BFIN_SIR) || defined(CONFIG_BFIN_SIR_MODULE)
#ifdef CONFIG_BFIN_SIR0
static struct resource bfin_sir0_resources[] = {
{
.start = 0xFFC00400,
.end = 0xFFC004FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART0_RX,
.end = IRQ_UART0_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART0_RX,
.end = CH_UART0_RX+1,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device bfin_sir0_device = {
.name = "bfin_sir",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_sir0_resources),
.resource = bfin_sir0_resources,
};
#endif
#ifdef CONFIG_BFIN_SIR1
static struct resource bfin_sir1_resources[] = {
{
.start = 0xFFC02000,
.end = 0xFFC020FF,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_UART1_RX,
.end = IRQ_UART1_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = CH_UART1_RX,
.end = CH_UART1_RX+1,
.flags = IORESOURCE_DMA,
},
};
static struct platform_device bfin_sir1_device = {
.name = "bfin_sir",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_sir1_resources),
.resource = bfin_sir1_resources,
};
#endif
#endif
#if defined(CONFIG_I2C_BLACKFIN_TWI) || defined(CONFIG_I2C_BLACKFIN_TWI_MODULE)
static struct resource bfin_twi0_resource[] = {
[0] = {
.start = TWI0_REGBASE,
.end = TWI0_REGBASE + 0xFF,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_TWI,
.end = IRQ_TWI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device i2c_bfin_twi_device = {
.name = "i2c-bfin-twi",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_twi0_resource),
.resource = bfin_twi0_resource,
};
#endif
#if defined(CONFIG_SERIAL_BFIN_SPORT) || defined(CONFIG_SERIAL_BFIN_SPORT_MODULE)
#ifdef CONFIG_SERIAL_BFIN_SPORT0_UART
static struct resource bfin_sport0_uart_resources[] = {
{
.start = SPORT0_TCR1,
.end = SPORT0_MRCS3+4,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_SPORT0_RX,
.end = IRQ_SPORT0_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_SPORT0_ERROR,
.end = IRQ_SPORT0_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static unsigned short bfin_sport0_peripherals[] = {
P_SPORT0_TFS, P_SPORT0_DTPRI, P_SPORT0_TSCLK, P_SPORT0_RFS,
P_SPORT0_DRPRI, P_SPORT0_RSCLK, 0
};
static struct platform_device bfin_sport0_uart_device = {
.name = "bfin-sport-uart",
.id = 0,
.num_resources = ARRAY_SIZE(bfin_sport0_uart_resources),
.resource = bfin_sport0_uart_resources,
.dev = {
.platform_data = &bfin_sport0_peripherals, /* Passed to driver */
},
};
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT1_UART
static struct resource bfin_sport1_uart_resources[] = {
{
.start = SPORT1_TCR1,
.end = SPORT1_MRCS3+4,
.flags = IORESOURCE_MEM,
},
{
.start = IRQ_SPORT1_RX,
.end = IRQ_SPORT1_RX+1,
.flags = IORESOURCE_IRQ,
},
{
.start = IRQ_SPORT1_ERROR,
.end = IRQ_SPORT1_ERROR,
.flags = IORESOURCE_IRQ,
},
};
static unsigned short bfin_sport1_peripherals[] = {
P_SPORT1_TFS, P_SPORT1_DTPRI, P_SPORT1_TSCLK, P_SPORT1_RFS,
P_SPORT1_DRPRI, P_SPORT1_RSCLK, 0
};
static struct platform_device bfin_sport1_uart_device = {
.name = "bfin-sport-uart",
.id = 1,
.num_resources = ARRAY_SIZE(bfin_sport1_uart_resources),
.resource = bfin_sport1_uart_resources,
.dev = {
.platform_data = &bfin_sport1_peripherals, /* Passed to driver */
},
};
#endif
#endif
static struct platform_device *minotaur_devices[] __initdata = {
#if defined(CONFIG_BFIN_CFPCMCIA) || defined(CONFIG_BFIN_CFPCMCIA_MODULE)
&bfin_pcmcia_cf_device,
#endif
#if defined(CONFIG_RTC_DRV_BFIN) || defined(CONFIG_RTC_DRV_BFIN_MODULE)
&rtc_device,
#endif
#if defined(CONFIG_BFIN_MAC) || defined(CONFIG_BFIN_MAC_MODULE)
&bfin_mii_bus,
&bfin_mac_device,
#endif
#if defined(CONFIG_USB_NET2272) || defined(CONFIG_USB_NET2272_MODULE)
&net2272_bfin_device,
#endif
#if defined(CONFIG_SPI_BFIN) || defined(CONFIG_SPI_BFIN_MODULE)
&bfin_spi0_device,
#endif
#if defined(CONFIG_SERIAL_BFIN) || defined(CONFIG_SERIAL_BFIN_MODULE)
#ifdef CONFIG_SERIAL_BFIN_UART0
&bfin_uart0_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART1
&bfin_uart1_device,
#endif
#endif
#if defined(CONFIG_BFIN_SIR) || defined(CONFIG_BFIN_SIR_MODULE)
#ifdef CONFIG_BFIN_SIR0
&bfin_sir0_device,
#endif
#ifdef CONFIG_BFIN_SIR1
&bfin_sir1_device,
#endif
#endif
#if defined(CONFIG_I2C_BLACKFIN_TWI) || defined(CONFIG_I2C_BLACKFIN_TWI_MODULE)
&i2c_bfin_twi_device,
#endif
#if defined(CONFIG_SERIAL_BFIN_SPORT) || defined(CONFIG_SERIAL_BFIN_SPORT_MODULE)
#ifdef CONFIG_SERIAL_BFIN_SPORT0_UART
&bfin_sport0_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT1_UART
&bfin_sport1_uart_device,
#endif
#endif
};
static int __init minotaur_init(void)
{
printk(KERN_INFO "%s(): registering device resources\n", __func__);
platform_add_devices(minotaur_devices, ARRAY_SIZE(minotaur_devices));
#if defined(CONFIG_SPI_BFIN) || defined(CONFIG_SPI_BFIN_MODULE)
spi_register_board_info(bfin_spi_board_info,
ARRAY_SIZE(bfin_spi_board_info));
#endif
return 0;
}
arch_initcall(minotaur_init);
static struct platform_device *minotaur_early_devices[] __initdata = {
#if defined(CONFIG_SERIAL_BFIN_CONSOLE) || defined(CONFIG_EARLY_PRINTK)
#ifdef CONFIG_SERIAL_BFIN_UART0
&bfin_uart0_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_UART1
&bfin_uart1_device,
#endif
#endif
#if defined(CONFIG_SERIAL_BFIN_SPORT_CONSOLE)
#ifdef CONFIG_SERIAL_BFIN_SPORT0_UART
&bfin_sport0_uart_device,
#endif
#ifdef CONFIG_SERIAL_BFIN_SPORT1_UART
&bfin_sport1_uart_device,
#endif
#endif
};
void __init native_machine_early_platform_add_devices(void)
{
printk(KERN_INFO "register early platform devices\n");
early_platform_add_devices(minotaur_early_devices,
ARRAY_SIZE(minotaur_early_devices));
}
void native_machine_restart(char *cmd)
{
/* workaround reboot hang when booting from SPI */
if ((bfin_read_SYSCR() & 0x7) == 0x3)
bfin_reset_boot_spi_cs(P_DEFAULT_BOOT_SPI_CS);
}
| gpl-2.0 |
bigzz/sc7715-kernel | drivers/mfd/wm8350-i2c.c | 2441 | 2220 | /*
* wm8350-i2c.c -- Generic I2C driver for Wolfson WM8350 PMIC
*
* Copyright 2007, 2008 Wolfson Microelectronics PLC.
*
* Author: Liam Girdwood
* linux@wolfsonmicro.com
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/platform_device.h>
#include <linux/mfd/wm8350/core.h>
#include <linux/regmap.h>
#include <linux/slab.h>
static int wm8350_i2c_probe(struct i2c_client *i2c,
const struct i2c_device_id *id)
{
struct wm8350 *wm8350;
int ret = 0;
wm8350 = devm_kzalloc(&i2c->dev, sizeof(struct wm8350), GFP_KERNEL);
if (wm8350 == NULL)
return -ENOMEM;
wm8350->regmap = devm_regmap_init_i2c(i2c, &wm8350_regmap);
if (IS_ERR(wm8350->regmap)) {
ret = PTR_ERR(wm8350->regmap);
dev_err(&i2c->dev, "Failed to allocate register map: %d\n",
ret);
return ret;
}
i2c_set_clientdata(i2c, wm8350);
wm8350->dev = &i2c->dev;
return wm8350_device_init(wm8350, i2c->irq, i2c->dev.platform_data);
}
static int wm8350_i2c_remove(struct i2c_client *i2c)
{
struct wm8350 *wm8350 = i2c_get_clientdata(i2c);
wm8350_device_exit(wm8350);
return 0;
}
static const struct i2c_device_id wm8350_i2c_id[] = {
{ "wm8350", 0 },
{ "wm8351", 0 },
{ "wm8352", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, wm8350_i2c_id);
static struct i2c_driver wm8350_i2c_driver = {
.driver = {
.name = "wm8350",
.owner = THIS_MODULE,
},
.probe = wm8350_i2c_probe,
.remove = wm8350_i2c_remove,
.id_table = wm8350_i2c_id,
};
static int __init wm8350_i2c_init(void)
{
return i2c_add_driver(&wm8350_i2c_driver);
}
/* init early so consumer devices can complete system boot */
subsys_initcall(wm8350_i2c_init);
static void __exit wm8350_i2c_exit(void)
{
i2c_del_driver(&wm8350_i2c_driver);
}
module_exit(wm8350_i2c_exit);
MODULE_DESCRIPTION("I2C support for the WM8350 AudioPlus PMIC");
MODULE_LICENSE("GPL");
| gpl-2.0 |
iconia-dev/android_kernel_acer_t20-common | tools/perf/util/usage.c | 4745 | 1690 | /*
* GIT - The information manager from hell
*
* Copyright (C) Linus Torvalds, 2005
*/
#include "util.h"
static void report(const char *prefix, const char *err, va_list params)
{
char msg[1024];
vsnprintf(msg, sizeof(msg), err, params);
fprintf(stderr, " %s%s\n", prefix, msg);
}
static NORETURN void usage_builtin(const char *err)
{
fprintf(stderr, "\n Usage: %s\n", err);
exit(129);
}
static NORETURN void die_builtin(const char *err, va_list params)
{
report(" Fatal: ", err, params);
exit(128);
}
static void error_builtin(const char *err, va_list params)
{
report(" Error: ", err, params);
}
static void warn_builtin(const char *warn, va_list params)
{
report(" Warning: ", warn, params);
}
/* If we are in a dlopen()ed .so write to a global variable would segfault
* (ugh), so keep things static. */
static void (*usage_routine)(const char *err) NORETURN = usage_builtin;
static void (*die_routine)(const char *err, va_list params) NORETURN = die_builtin;
static void (*error_routine)(const char *err, va_list params) = error_builtin;
static void (*warn_routine)(const char *err, va_list params) = warn_builtin;
void set_die_routine(void (*routine)(const char *err, va_list params) NORETURN)
{
die_routine = routine;
}
void usage(const char *err)
{
usage_routine(err);
}
void die(const char *err, ...)
{
va_list params;
va_start(params, err);
die_routine(err, params);
va_end(params);
}
int error(const char *err, ...)
{
va_list params;
va_start(params, err);
error_routine(err, params);
va_end(params);
return -1;
}
void warning(const char *warn, ...)
{
va_list params;
va_start(params, warn);
warn_routine(warn, params);
va_end(params);
}
| gpl-2.0 |
iDroid-Project/iDroid-kernel | crypto/ccm.c | 5001 | 22059 | /*
* CCM: Counter with CBC-MAC
*
* (C) Copyright IBM Corp. 2007 - Joy Latten <latten@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.
*
*/
#include <crypto/internal/aead.h>
#include <crypto/internal/skcipher.h>
#include <crypto/scatterwalk.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include "internal.h"
struct ccm_instance_ctx {
struct crypto_skcipher_spawn ctr;
struct crypto_spawn cipher;
};
struct crypto_ccm_ctx {
struct crypto_cipher *cipher;
struct crypto_ablkcipher *ctr;
};
struct crypto_rfc4309_ctx {
struct crypto_aead *child;
u8 nonce[3];
};
struct crypto_ccm_req_priv_ctx {
u8 odata[16];
u8 idata[16];
u8 auth_tag[16];
u32 ilen;
u32 flags;
struct scatterlist src[2];
struct scatterlist dst[2];
struct ablkcipher_request abreq;
};
static inline struct crypto_ccm_req_priv_ctx *crypto_ccm_reqctx(
struct aead_request *req)
{
unsigned long align = crypto_aead_alignmask(crypto_aead_reqtfm(req));
return (void *)PTR_ALIGN((u8 *)aead_request_ctx(req), align + 1);
}
static int set_msg_len(u8 *block, unsigned int msglen, int csize)
{
__be32 data;
memset(block, 0, csize);
block += csize;
if (csize >= 4)
csize = 4;
else if (msglen > (1 << (8 * csize)))
return -EOVERFLOW;
data = cpu_to_be32(msglen);
memcpy(block - csize, (u8 *)&data + 4 - csize, csize);
return 0;
}
static int crypto_ccm_setkey(struct crypto_aead *aead, const u8 *key,
unsigned int keylen)
{
struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead);
struct crypto_ablkcipher *ctr = ctx->ctr;
struct crypto_cipher *tfm = ctx->cipher;
int err = 0;
crypto_ablkcipher_clear_flags(ctr, CRYPTO_TFM_REQ_MASK);
crypto_ablkcipher_set_flags(ctr, crypto_aead_get_flags(aead) &
CRYPTO_TFM_REQ_MASK);
err = crypto_ablkcipher_setkey(ctr, key, keylen);
crypto_aead_set_flags(aead, crypto_ablkcipher_get_flags(ctr) &
CRYPTO_TFM_RES_MASK);
if (err)
goto out;
crypto_cipher_clear_flags(tfm, CRYPTO_TFM_REQ_MASK);
crypto_cipher_set_flags(tfm, crypto_aead_get_flags(aead) &
CRYPTO_TFM_REQ_MASK);
err = crypto_cipher_setkey(tfm, key, keylen);
crypto_aead_set_flags(aead, crypto_cipher_get_flags(tfm) &
CRYPTO_TFM_RES_MASK);
out:
return err;
}
static int crypto_ccm_setauthsize(struct crypto_aead *tfm,
unsigned int authsize)
{
switch (authsize) {
case 4:
case 6:
case 8:
case 10:
case 12:
case 14:
case 16:
break;
default:
return -EINVAL;
}
return 0;
}
static int format_input(u8 *info, struct aead_request *req,
unsigned int cryptlen)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
unsigned int lp = req->iv[0];
unsigned int l = lp + 1;
unsigned int m;
m = crypto_aead_authsize(aead);
memcpy(info, req->iv, 16);
/* format control info per RFC 3610 and
* NIST Special Publication 800-38C
*/
*info |= (8 * ((m - 2) / 2));
if (req->assoclen)
*info |= 64;
return set_msg_len(info + 16 - l, cryptlen, l);
}
static int format_adata(u8 *adata, unsigned int a)
{
int len = 0;
/* add control info for associated data
* RFC 3610 and NIST Special Publication 800-38C
*/
if (a < 65280) {
*(__be16 *)adata = cpu_to_be16(a);
len = 2;
} else {
*(__be16 *)adata = cpu_to_be16(0xfffe);
*(__be32 *)&adata[2] = cpu_to_be32(a);
len = 6;
}
return len;
}
static void compute_mac(struct crypto_cipher *tfm, u8 *data, int n,
struct crypto_ccm_req_priv_ctx *pctx)
{
unsigned int bs = 16;
u8 *odata = pctx->odata;
u8 *idata = pctx->idata;
int datalen, getlen;
datalen = n;
/* first time in here, block may be partially filled. */
getlen = bs - pctx->ilen;
if (datalen >= getlen) {
memcpy(idata + pctx->ilen, data, getlen);
crypto_xor(odata, idata, bs);
crypto_cipher_encrypt_one(tfm, odata, odata);
datalen -= getlen;
data += getlen;
pctx->ilen = 0;
}
/* now encrypt rest of data */
while (datalen >= bs) {
crypto_xor(odata, data, bs);
crypto_cipher_encrypt_one(tfm, odata, odata);
datalen -= bs;
data += bs;
}
/* check and see if there's leftover data that wasn't
* enough to fill a block.
*/
if (datalen) {
memcpy(idata + pctx->ilen, data, datalen);
pctx->ilen += datalen;
}
}
static void get_data_to_compute(struct crypto_cipher *tfm,
struct crypto_ccm_req_priv_ctx *pctx,
struct scatterlist *sg, unsigned int len)
{
struct scatter_walk walk;
u8 *data_src;
int n;
scatterwalk_start(&walk, sg);
while (len) {
n = scatterwalk_clamp(&walk, len);
if (!n) {
scatterwalk_start(&walk, sg_next(walk.sg));
n = scatterwalk_clamp(&walk, len);
}
data_src = scatterwalk_map(&walk, 0);
compute_mac(tfm, data_src, n, pctx);
len -= n;
scatterwalk_unmap(data_src, 0);
scatterwalk_advance(&walk, n);
scatterwalk_done(&walk, 0, len);
if (len)
crypto_yield(pctx->flags);
}
/* any leftover needs padding and then encrypted */
if (pctx->ilen) {
int padlen;
u8 *odata = pctx->odata;
u8 *idata = pctx->idata;
padlen = 16 - pctx->ilen;
memset(idata + pctx->ilen, 0, padlen);
crypto_xor(odata, idata, 16);
crypto_cipher_encrypt_one(tfm, odata, odata);
pctx->ilen = 0;
}
}
static int crypto_ccm_auth(struct aead_request *req, struct scatterlist *plain,
unsigned int cryptlen)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead);
struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req);
struct crypto_cipher *cipher = ctx->cipher;
unsigned int assoclen = req->assoclen;
u8 *odata = pctx->odata;
u8 *idata = pctx->idata;
int err;
/* format control data for input */
err = format_input(odata, req, cryptlen);
if (err)
goto out;
/* encrypt first block to use as start in computing mac */
crypto_cipher_encrypt_one(cipher, odata, odata);
/* format associated data and compute into mac */
if (assoclen) {
pctx->ilen = format_adata(idata, assoclen);
get_data_to_compute(cipher, pctx, req->assoc, req->assoclen);
} else {
pctx->ilen = 0;
}
/* compute plaintext into mac */
get_data_to_compute(cipher, pctx, plain, cryptlen);
out:
return err;
}
static void crypto_ccm_encrypt_done(struct crypto_async_request *areq, int err)
{
struct aead_request *req = areq->data;
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req);
u8 *odata = pctx->odata;
if (!err)
scatterwalk_map_and_copy(odata, req->dst, req->cryptlen,
crypto_aead_authsize(aead), 1);
aead_request_complete(req, err);
}
static inline int crypto_ccm_check_iv(const u8 *iv)
{
/* 2 <= L <= 8, so 1 <= L' <= 7. */
if (1 > iv[0] || iv[0] > 7)
return -EINVAL;
return 0;
}
static int crypto_ccm_encrypt(struct aead_request *req)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead);
struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req);
struct ablkcipher_request *abreq = &pctx->abreq;
struct scatterlist *dst;
unsigned int cryptlen = req->cryptlen;
u8 *odata = pctx->odata;
u8 *iv = req->iv;
int err;
err = crypto_ccm_check_iv(iv);
if (err)
return err;
pctx->flags = aead_request_flags(req);
err = crypto_ccm_auth(req, req->src, cryptlen);
if (err)
return err;
/* Note: rfc 3610 and NIST 800-38C require counter of
* zero to encrypt auth tag.
*/
memset(iv + 15 - iv[0], 0, iv[0] + 1);
sg_init_table(pctx->src, 2);
sg_set_buf(pctx->src, odata, 16);
scatterwalk_sg_chain(pctx->src, 2, req->src);
dst = pctx->src;
if (req->src != req->dst) {
sg_init_table(pctx->dst, 2);
sg_set_buf(pctx->dst, odata, 16);
scatterwalk_sg_chain(pctx->dst, 2, req->dst);
dst = pctx->dst;
}
ablkcipher_request_set_tfm(abreq, ctx->ctr);
ablkcipher_request_set_callback(abreq, pctx->flags,
crypto_ccm_encrypt_done, req);
ablkcipher_request_set_crypt(abreq, pctx->src, dst, cryptlen + 16, iv);
err = crypto_ablkcipher_encrypt(abreq);
if (err)
return err;
/* copy authtag to end of dst */
scatterwalk_map_and_copy(odata, req->dst, cryptlen,
crypto_aead_authsize(aead), 1);
return err;
}
static void crypto_ccm_decrypt_done(struct crypto_async_request *areq,
int err)
{
struct aead_request *req = areq->data;
struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req);
struct crypto_aead *aead = crypto_aead_reqtfm(req);
unsigned int authsize = crypto_aead_authsize(aead);
unsigned int cryptlen = req->cryptlen - authsize;
if (!err) {
err = crypto_ccm_auth(req, req->dst, cryptlen);
if (!err && memcmp(pctx->auth_tag, pctx->odata, authsize))
err = -EBADMSG;
}
aead_request_complete(req, err);
}
static int crypto_ccm_decrypt(struct aead_request *req)
{
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_ccm_ctx *ctx = crypto_aead_ctx(aead);
struct crypto_ccm_req_priv_ctx *pctx = crypto_ccm_reqctx(req);
struct ablkcipher_request *abreq = &pctx->abreq;
struct scatterlist *dst;
unsigned int authsize = crypto_aead_authsize(aead);
unsigned int cryptlen = req->cryptlen;
u8 *authtag = pctx->auth_tag;
u8 *odata = pctx->odata;
u8 *iv = req->iv;
int err;
if (cryptlen < authsize)
return -EINVAL;
cryptlen -= authsize;
err = crypto_ccm_check_iv(iv);
if (err)
return err;
pctx->flags = aead_request_flags(req);
scatterwalk_map_and_copy(authtag, req->src, cryptlen, authsize, 0);
memset(iv + 15 - iv[0], 0, iv[0] + 1);
sg_init_table(pctx->src, 2);
sg_set_buf(pctx->src, authtag, 16);
scatterwalk_sg_chain(pctx->src, 2, req->src);
dst = pctx->src;
if (req->src != req->dst) {
sg_init_table(pctx->dst, 2);
sg_set_buf(pctx->dst, authtag, 16);
scatterwalk_sg_chain(pctx->dst, 2, req->dst);
dst = pctx->dst;
}
ablkcipher_request_set_tfm(abreq, ctx->ctr);
ablkcipher_request_set_callback(abreq, pctx->flags,
crypto_ccm_decrypt_done, req);
ablkcipher_request_set_crypt(abreq, pctx->src, dst, cryptlen + 16, iv);
err = crypto_ablkcipher_decrypt(abreq);
if (err)
return err;
err = crypto_ccm_auth(req, req->dst, cryptlen);
if (err)
return err;
/* verify */
if (memcmp(authtag, odata, authsize))
return -EBADMSG;
return err;
}
static int crypto_ccm_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_instance *inst = (void *)tfm->__crt_alg;
struct ccm_instance_ctx *ictx = crypto_instance_ctx(inst);
struct crypto_ccm_ctx *ctx = crypto_tfm_ctx(tfm);
struct crypto_cipher *cipher;
struct crypto_ablkcipher *ctr;
unsigned long align;
int err;
cipher = crypto_spawn_cipher(&ictx->cipher);
if (IS_ERR(cipher))
return PTR_ERR(cipher);
ctr = crypto_spawn_skcipher(&ictx->ctr);
err = PTR_ERR(ctr);
if (IS_ERR(ctr))
goto err_free_cipher;
ctx->cipher = cipher;
ctx->ctr = ctr;
align = crypto_tfm_alg_alignmask(tfm);
align &= ~(crypto_tfm_ctx_alignment() - 1);
tfm->crt_aead.reqsize = align +
sizeof(struct crypto_ccm_req_priv_ctx) +
crypto_ablkcipher_reqsize(ctr);
return 0;
err_free_cipher:
crypto_free_cipher(cipher);
return err;
}
static void crypto_ccm_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_ccm_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_cipher(ctx->cipher);
crypto_free_ablkcipher(ctx->ctr);
}
static struct crypto_instance *crypto_ccm_alloc_common(struct rtattr **tb,
const char *full_name,
const char *ctr_name,
const char *cipher_name)
{
struct crypto_attr_type *algt;
struct crypto_instance *inst;
struct crypto_alg *ctr;
struct crypto_alg *cipher;
struct ccm_instance_ctx *ictx;
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) & algt->mask)
return ERR_PTR(-EINVAL);
cipher = crypto_alg_mod_lookup(cipher_name, CRYPTO_ALG_TYPE_CIPHER,
CRYPTO_ALG_TYPE_MASK);
err = PTR_ERR(cipher);
if (IS_ERR(cipher))
return ERR_PTR(err);
err = -EINVAL;
if (cipher->cra_blocksize != 16)
goto out_put_cipher;
inst = kzalloc(sizeof(*inst) + sizeof(*ictx), GFP_KERNEL);
err = -ENOMEM;
if (!inst)
goto out_put_cipher;
ictx = crypto_instance_ctx(inst);
err = crypto_init_spawn(&ictx->cipher, cipher, inst,
CRYPTO_ALG_TYPE_MASK);
if (err)
goto err_free_inst;
crypto_set_skcipher_spawn(&ictx->ctr, inst);
err = crypto_grab_skcipher(&ictx->ctr, ctr_name, 0,
crypto_requires_sync(algt->type,
algt->mask));
if (err)
goto err_drop_cipher;
ctr = crypto_skcipher_spawn_alg(&ictx->ctr);
/* Not a stream cipher? */
err = -EINVAL;
if (ctr->cra_blocksize != 1)
goto err_drop_ctr;
/* We want the real thing! */
if (ctr->cra_ablkcipher.ivsize != 16)
goto err_drop_ctr;
err = -ENAMETOOLONG;
if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME,
"ccm_base(%s,%s)", ctr->cra_driver_name,
cipher->cra_driver_name) >= CRYPTO_MAX_ALG_NAME)
goto err_drop_ctr;
memcpy(inst->alg.cra_name, full_name, CRYPTO_MAX_ALG_NAME);
inst->alg.cra_flags = CRYPTO_ALG_TYPE_AEAD;
inst->alg.cra_flags |= ctr->cra_flags & CRYPTO_ALG_ASYNC;
inst->alg.cra_priority = cipher->cra_priority + ctr->cra_priority;
inst->alg.cra_blocksize = 1;
inst->alg.cra_alignmask = cipher->cra_alignmask | ctr->cra_alignmask |
(__alignof__(u32) - 1);
inst->alg.cra_type = &crypto_aead_type;
inst->alg.cra_aead.ivsize = 16;
inst->alg.cra_aead.maxauthsize = 16;
inst->alg.cra_ctxsize = sizeof(struct crypto_ccm_ctx);
inst->alg.cra_init = crypto_ccm_init_tfm;
inst->alg.cra_exit = crypto_ccm_exit_tfm;
inst->alg.cra_aead.setkey = crypto_ccm_setkey;
inst->alg.cra_aead.setauthsize = crypto_ccm_setauthsize;
inst->alg.cra_aead.encrypt = crypto_ccm_encrypt;
inst->alg.cra_aead.decrypt = crypto_ccm_decrypt;
out:
crypto_mod_put(cipher);
return inst;
err_drop_ctr:
crypto_drop_skcipher(&ictx->ctr);
err_drop_cipher:
crypto_drop_spawn(&ictx->cipher);
err_free_inst:
kfree(inst);
out_put_cipher:
inst = ERR_PTR(err);
goto out;
}
static struct crypto_instance *crypto_ccm_alloc(struct rtattr **tb)
{
int err;
const char *cipher_name;
char ctr_name[CRYPTO_MAX_ALG_NAME];
char full_name[CRYPTO_MAX_ALG_NAME];
cipher_name = crypto_attr_alg_name(tb[1]);
err = PTR_ERR(cipher_name);
if (IS_ERR(cipher_name))
return ERR_PTR(err);
if (snprintf(ctr_name, CRYPTO_MAX_ALG_NAME, "ctr(%s)",
cipher_name) >= CRYPTO_MAX_ALG_NAME)
return ERR_PTR(-ENAMETOOLONG);
if (snprintf(full_name, CRYPTO_MAX_ALG_NAME, "ccm(%s)", cipher_name) >=
CRYPTO_MAX_ALG_NAME)
return ERR_PTR(-ENAMETOOLONG);
return crypto_ccm_alloc_common(tb, full_name, ctr_name, cipher_name);
}
static void crypto_ccm_free(struct crypto_instance *inst)
{
struct ccm_instance_ctx *ctx = crypto_instance_ctx(inst);
crypto_drop_spawn(&ctx->cipher);
crypto_drop_skcipher(&ctx->ctr);
kfree(inst);
}
static struct crypto_template crypto_ccm_tmpl = {
.name = "ccm",
.alloc = crypto_ccm_alloc,
.free = crypto_ccm_free,
.module = THIS_MODULE,
};
static struct crypto_instance *crypto_ccm_base_alloc(struct rtattr **tb)
{
int err;
const char *ctr_name;
const char *cipher_name;
char full_name[CRYPTO_MAX_ALG_NAME];
ctr_name = crypto_attr_alg_name(tb[1]);
err = PTR_ERR(ctr_name);
if (IS_ERR(ctr_name))
return ERR_PTR(err);
cipher_name = crypto_attr_alg_name(tb[2]);
err = PTR_ERR(cipher_name);
if (IS_ERR(cipher_name))
return ERR_PTR(err);
if (snprintf(full_name, CRYPTO_MAX_ALG_NAME, "ccm_base(%s,%s)",
ctr_name, cipher_name) >= CRYPTO_MAX_ALG_NAME)
return ERR_PTR(-ENAMETOOLONG);
return crypto_ccm_alloc_common(tb, full_name, ctr_name, cipher_name);
}
static struct crypto_template crypto_ccm_base_tmpl = {
.name = "ccm_base",
.alloc = crypto_ccm_base_alloc,
.free = crypto_ccm_free,
.module = THIS_MODULE,
};
static int crypto_rfc4309_setkey(struct crypto_aead *parent, const u8 *key,
unsigned int keylen)
{
struct crypto_rfc4309_ctx *ctx = crypto_aead_ctx(parent);
struct crypto_aead *child = ctx->child;
int err;
if (keylen < 3)
return -EINVAL;
keylen -= 3;
memcpy(ctx->nonce, key + keylen, 3);
crypto_aead_clear_flags(child, CRYPTO_TFM_REQ_MASK);
crypto_aead_set_flags(child, crypto_aead_get_flags(parent) &
CRYPTO_TFM_REQ_MASK);
err = crypto_aead_setkey(child, key, keylen);
crypto_aead_set_flags(parent, crypto_aead_get_flags(child) &
CRYPTO_TFM_RES_MASK);
return err;
}
static int crypto_rfc4309_setauthsize(struct crypto_aead *parent,
unsigned int authsize)
{
struct crypto_rfc4309_ctx *ctx = crypto_aead_ctx(parent);
switch (authsize) {
case 8:
case 12:
case 16:
break;
default:
return -EINVAL;
}
return crypto_aead_setauthsize(ctx->child, authsize);
}
static struct aead_request *crypto_rfc4309_crypt(struct aead_request *req)
{
struct aead_request *subreq = aead_request_ctx(req);
struct crypto_aead *aead = crypto_aead_reqtfm(req);
struct crypto_rfc4309_ctx *ctx = crypto_aead_ctx(aead);
struct crypto_aead *child = ctx->child;
u8 *iv = PTR_ALIGN((u8 *)(subreq + 1) + crypto_aead_reqsize(child),
crypto_aead_alignmask(child) + 1);
/* L' */
iv[0] = 3;
memcpy(iv + 1, ctx->nonce, 3);
memcpy(iv + 4, req->iv, 8);
aead_request_set_tfm(subreq, child);
aead_request_set_callback(subreq, req->base.flags, req->base.complete,
req->base.data);
aead_request_set_crypt(subreq, req->src, req->dst, req->cryptlen, iv);
aead_request_set_assoc(subreq, req->assoc, req->assoclen);
return subreq;
}
static int crypto_rfc4309_encrypt(struct aead_request *req)
{
req = crypto_rfc4309_crypt(req);
return crypto_aead_encrypt(req);
}
static int crypto_rfc4309_decrypt(struct aead_request *req)
{
req = crypto_rfc4309_crypt(req);
return crypto_aead_decrypt(req);
}
static int crypto_rfc4309_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_instance *inst = (void *)tfm->__crt_alg;
struct crypto_aead_spawn *spawn = crypto_instance_ctx(inst);
struct crypto_rfc4309_ctx *ctx = crypto_tfm_ctx(tfm);
struct crypto_aead *aead;
unsigned long align;
aead = crypto_spawn_aead(spawn);
if (IS_ERR(aead))
return PTR_ERR(aead);
ctx->child = aead;
align = crypto_aead_alignmask(aead);
align &= ~(crypto_tfm_ctx_alignment() - 1);
tfm->crt_aead.reqsize = sizeof(struct aead_request) +
ALIGN(crypto_aead_reqsize(aead),
crypto_tfm_ctx_alignment()) +
align + 16;
return 0;
}
static void crypto_rfc4309_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_rfc4309_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_aead(ctx->child);
}
static struct crypto_instance *crypto_rfc4309_alloc(struct rtattr **tb)
{
struct crypto_attr_type *algt;
struct crypto_instance *inst;
struct crypto_aead_spawn *spawn;
struct crypto_alg *alg;
const char *ccm_name;
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) & algt->mask)
return ERR_PTR(-EINVAL);
ccm_name = crypto_attr_alg_name(tb[1]);
err = PTR_ERR(ccm_name);
if (IS_ERR(ccm_name))
return ERR_PTR(err);
inst = kzalloc(sizeof(*inst) + sizeof(*spawn), GFP_KERNEL);
if (!inst)
return ERR_PTR(-ENOMEM);
spawn = crypto_instance_ctx(inst);
crypto_set_aead_spawn(spawn, inst);
err = crypto_grab_aead(spawn, ccm_name, 0,
crypto_requires_sync(algt->type, algt->mask));
if (err)
goto out_free_inst;
alg = crypto_aead_spawn_alg(spawn);
err = -EINVAL;
/* We only support 16-byte blocks. */
if (alg->cra_aead.ivsize != 16)
goto out_drop_alg;
/* Not a stream cipher? */
if (alg->cra_blocksize != 1)
goto out_drop_alg;
err = -ENAMETOOLONG;
if (snprintf(inst->alg.cra_name, CRYPTO_MAX_ALG_NAME,
"rfc4309(%s)", alg->cra_name) >= CRYPTO_MAX_ALG_NAME ||
snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME,
"rfc4309(%s)", alg->cra_driver_name) >=
CRYPTO_MAX_ALG_NAME)
goto out_drop_alg;
inst->alg.cra_flags = CRYPTO_ALG_TYPE_AEAD;
inst->alg.cra_flags |= alg->cra_flags & CRYPTO_ALG_ASYNC;
inst->alg.cra_priority = alg->cra_priority;
inst->alg.cra_blocksize = 1;
inst->alg.cra_alignmask = alg->cra_alignmask;
inst->alg.cra_type = &crypto_nivaead_type;
inst->alg.cra_aead.ivsize = 8;
inst->alg.cra_aead.maxauthsize = 16;
inst->alg.cra_ctxsize = sizeof(struct crypto_rfc4309_ctx);
inst->alg.cra_init = crypto_rfc4309_init_tfm;
inst->alg.cra_exit = crypto_rfc4309_exit_tfm;
inst->alg.cra_aead.setkey = crypto_rfc4309_setkey;
inst->alg.cra_aead.setauthsize = crypto_rfc4309_setauthsize;
inst->alg.cra_aead.encrypt = crypto_rfc4309_encrypt;
inst->alg.cra_aead.decrypt = crypto_rfc4309_decrypt;
inst->alg.cra_aead.geniv = "seqiv";
out:
return inst;
out_drop_alg:
crypto_drop_aead(spawn);
out_free_inst:
kfree(inst);
inst = ERR_PTR(err);
goto out;
}
static void crypto_rfc4309_free(struct crypto_instance *inst)
{
crypto_drop_spawn(crypto_instance_ctx(inst));
kfree(inst);
}
static struct crypto_template crypto_rfc4309_tmpl = {
.name = "rfc4309",
.alloc = crypto_rfc4309_alloc,
.free = crypto_rfc4309_free,
.module = THIS_MODULE,
};
static int __init crypto_ccm_module_init(void)
{
int err;
err = crypto_register_template(&crypto_ccm_base_tmpl);
if (err)
goto out;
err = crypto_register_template(&crypto_ccm_tmpl);
if (err)
goto out_undo_base;
err = crypto_register_template(&crypto_rfc4309_tmpl);
if (err)
goto out_undo_ccm;
out:
return err;
out_undo_ccm:
crypto_unregister_template(&crypto_ccm_tmpl);
out_undo_base:
crypto_unregister_template(&crypto_ccm_base_tmpl);
goto out;
}
static void __exit crypto_ccm_module_exit(void)
{
crypto_unregister_template(&crypto_rfc4309_tmpl);
crypto_unregister_template(&crypto_ccm_tmpl);
crypto_unregister_template(&crypto_ccm_base_tmpl);
}
module_init(crypto_ccm_module_init);
module_exit(crypto_ccm_module_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Counter with CBC MAC");
MODULE_ALIAS("ccm_base");
MODULE_ALIAS("rfc4309");
| gpl-2.0 |
kallaballa/linux-sunxi | arch/powerpc/platforms/chrp/smp.c | 5257 | 1210 | /*
* Smp support for CHRP machines.
*
* Written by Cort Dougan (cort@cs.nmt.edu) borrowing a great
* deal of code from the sparc and intel versions.
*
* Copyright (C) 1999 Cort Dougan <cort@cs.nmt.edu>
*
*/
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <asm/ptrace.h>
#include <linux/atomic.h>
#include <asm/irq.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/sections.h>
#include <asm/io.h>
#include <asm/prom.h>
#include <asm/smp.h>
#include <asm/machdep.h>
#include <asm/mpic.h>
#include <asm/rtas.h>
static int __devinit smp_chrp_kick_cpu(int nr)
{
*(unsigned long *)KERNELBASE = nr;
asm volatile("dcbf 0,%0"::"r"(KERNELBASE):"memory");
return 0;
}
static void __devinit smp_chrp_setup_cpu(int cpu_nr)
{
mpic_setup_this_cpu();
}
/* CHRP with openpic */
struct smp_ops_t chrp_smp_ops = {
.message_pass = smp_mpic_message_pass,
.probe = smp_mpic_probe,
.kick_cpu = smp_chrp_kick_cpu,
.setup_cpu = smp_chrp_setup_cpu,
.give_timebase = rtas_give_timebase,
.take_timebase = rtas_take_timebase,
};
| gpl-2.0 |
AndropaX/Resurrected-Kernel | drivers/net/wan/hdlc_fr.c | 7817 | 29896 | /*
* Generic HDLC support routines for Linux
* Frame Relay support
*
* Copyright (C) 1999 - 2006 Krzysztof Halasa <khc@pm.waw.pl>
*
* 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.
*
Theory of PVC state
DCE mode:
(exist,new) -> 0,0 when "PVC create" or if "link unreliable"
0,x -> 1,1 if "link reliable" when sending FULL STATUS
1,1 -> 1,0 if received FULL STATUS ACK
(active) -> 0 when "ifconfig PVC down" or "link unreliable" or "PVC create"
-> 1 when "PVC up" and (exist,new) = 1,0
DTE mode:
(exist,new,active) = FULL STATUS if "link reliable"
= 0, 0, 0 if "link unreliable"
No LMI:
active = open and "link reliable"
exist = new = not used
CCITT LMI: ITU-T Q.933 Annex A
ANSI LMI: ANSI T1.617 Annex D
CISCO LMI: the original, aka "Gang of Four" LMI
*/
#include <linux/errno.h>
#include <linux/etherdevice.h>
#include <linux/hdlc.h>
#include <linux/if_arp.h>
#include <linux/inetdevice.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pkt_sched.h>
#include <linux/poll.h>
#include <linux/rtnetlink.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#undef DEBUG_PKT
#undef DEBUG_ECN
#undef DEBUG_LINK
#undef DEBUG_PROTO
#undef DEBUG_PVC
#define FR_UI 0x03
#define FR_PAD 0x00
#define NLPID_IP 0xCC
#define NLPID_IPV6 0x8E
#define NLPID_SNAP 0x80
#define NLPID_PAD 0x00
#define NLPID_CCITT_ANSI_LMI 0x08
#define NLPID_CISCO_LMI 0x09
#define LMI_CCITT_ANSI_DLCI 0 /* LMI DLCI */
#define LMI_CISCO_DLCI 1023
#define LMI_CALLREF 0x00 /* Call Reference */
#define LMI_ANSI_LOCKSHIFT 0x95 /* ANSI locking shift */
#define LMI_ANSI_CISCO_REPTYPE 0x01 /* report type */
#define LMI_CCITT_REPTYPE 0x51
#define LMI_ANSI_CISCO_ALIVE 0x03 /* keep alive */
#define LMI_CCITT_ALIVE 0x53
#define LMI_ANSI_CISCO_PVCSTAT 0x07 /* PVC status */
#define LMI_CCITT_PVCSTAT 0x57
#define LMI_FULLREP 0x00 /* full report */
#define LMI_INTEGRITY 0x01 /* link integrity report */
#define LMI_SINGLE 0x02 /* single PVC report */
#define LMI_STATUS_ENQUIRY 0x75
#define LMI_STATUS 0x7D /* reply */
#define LMI_REPT_LEN 1 /* report type element length */
#define LMI_INTEG_LEN 2 /* link integrity element length */
#define LMI_CCITT_CISCO_LENGTH 13 /* LMI frame lengths */
#define LMI_ANSI_LENGTH 14
typedef struct {
#if defined(__LITTLE_ENDIAN_BITFIELD)
unsigned ea1: 1;
unsigned cr: 1;
unsigned dlcih: 6;
unsigned ea2: 1;
unsigned de: 1;
unsigned becn: 1;
unsigned fecn: 1;
unsigned dlcil: 4;
#else
unsigned dlcih: 6;
unsigned cr: 1;
unsigned ea1: 1;
unsigned dlcil: 4;
unsigned fecn: 1;
unsigned becn: 1;
unsigned de: 1;
unsigned ea2: 1;
#endif
}__packed fr_hdr;
typedef struct pvc_device_struct {
struct net_device *frad;
struct net_device *main;
struct net_device *ether; /* bridged Ethernet interface */
struct pvc_device_struct *next; /* Sorted in ascending DLCI order */
int dlci;
int open_count;
struct {
unsigned int new: 1;
unsigned int active: 1;
unsigned int exist: 1;
unsigned int deleted: 1;
unsigned int fecn: 1;
unsigned int becn: 1;
unsigned int bandwidth; /* Cisco LMI reporting only */
}state;
}pvc_device;
struct frad_state {
fr_proto settings;
pvc_device *first_pvc;
int dce_pvc_count;
struct timer_list timer;
unsigned long last_poll;
int reliable;
int dce_changed;
int request;
int fullrep_sent;
u32 last_errors; /* last errors bit list */
u8 n391cnt;
u8 txseq; /* TX sequence number */
u8 rxseq; /* RX sequence number */
};
static int fr_ioctl(struct net_device *dev, struct ifreq *ifr);
static inline u16 q922_to_dlci(u8 *hdr)
{
return ((hdr[0] & 0xFC) << 2) | ((hdr[1] & 0xF0) >> 4);
}
static inline void dlci_to_q922(u8 *hdr, u16 dlci)
{
hdr[0] = (dlci >> 2) & 0xFC;
hdr[1] = ((dlci << 4) & 0xF0) | 0x01;
}
static inline struct frad_state* state(hdlc_device *hdlc)
{
return(struct frad_state *)(hdlc->state);
}
static inline pvc_device* find_pvc(hdlc_device *hdlc, u16 dlci)
{
pvc_device *pvc = state(hdlc)->first_pvc;
while (pvc) {
if (pvc->dlci == dlci)
return pvc;
if (pvc->dlci > dlci)
return NULL; /* the list is sorted */
pvc = pvc->next;
}
return NULL;
}
static pvc_device* add_pvc(struct net_device *dev, u16 dlci)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
pvc_device *pvc, **pvc_p = &state(hdlc)->first_pvc;
while (*pvc_p) {
if ((*pvc_p)->dlci == dlci)
return *pvc_p;
if ((*pvc_p)->dlci > dlci)
break; /* the list is sorted */
pvc_p = &(*pvc_p)->next;
}
pvc = kzalloc(sizeof(pvc_device), GFP_ATOMIC);
#ifdef DEBUG_PVC
printk(KERN_DEBUG "add_pvc: allocated pvc %p, frad %p\n", pvc, dev);
#endif
if (!pvc)
return NULL;
pvc->dlci = dlci;
pvc->frad = dev;
pvc->next = *pvc_p; /* Put it in the chain */
*pvc_p = pvc;
return pvc;
}
static inline int pvc_is_used(pvc_device *pvc)
{
return pvc->main || pvc->ether;
}
static inline void pvc_carrier(int on, pvc_device *pvc)
{
if (on) {
if (pvc->main)
if (!netif_carrier_ok(pvc->main))
netif_carrier_on(pvc->main);
if (pvc->ether)
if (!netif_carrier_ok(pvc->ether))
netif_carrier_on(pvc->ether);
} else {
if (pvc->main)
if (netif_carrier_ok(pvc->main))
netif_carrier_off(pvc->main);
if (pvc->ether)
if (netif_carrier_ok(pvc->ether))
netif_carrier_off(pvc->ether);
}
}
static inline void delete_unused_pvcs(hdlc_device *hdlc)
{
pvc_device **pvc_p = &state(hdlc)->first_pvc;
while (*pvc_p) {
if (!pvc_is_used(*pvc_p)) {
pvc_device *pvc = *pvc_p;
#ifdef DEBUG_PVC
printk(KERN_DEBUG "freeing unused pvc: %p\n", pvc);
#endif
*pvc_p = pvc->next;
kfree(pvc);
continue;
}
pvc_p = &(*pvc_p)->next;
}
}
static inline struct net_device** get_dev_p(pvc_device *pvc, int type)
{
if (type == ARPHRD_ETHER)
return &pvc->ether;
else
return &pvc->main;
}
static int fr_hard_header(struct sk_buff **skb_p, u16 dlci)
{
u16 head_len;
struct sk_buff *skb = *skb_p;
switch (skb->protocol) {
case cpu_to_be16(NLPID_CCITT_ANSI_LMI):
head_len = 4;
skb_push(skb, head_len);
skb->data[3] = NLPID_CCITT_ANSI_LMI;
break;
case cpu_to_be16(NLPID_CISCO_LMI):
head_len = 4;
skb_push(skb, head_len);
skb->data[3] = NLPID_CISCO_LMI;
break;
case cpu_to_be16(ETH_P_IP):
head_len = 4;
skb_push(skb, head_len);
skb->data[3] = NLPID_IP;
break;
case cpu_to_be16(ETH_P_IPV6):
head_len = 4;
skb_push(skb, head_len);
skb->data[3] = NLPID_IPV6;
break;
case cpu_to_be16(ETH_P_802_3):
head_len = 10;
if (skb_headroom(skb) < head_len) {
struct sk_buff *skb2 = skb_realloc_headroom(skb,
head_len);
if (!skb2)
return -ENOBUFS;
dev_kfree_skb(skb);
skb = *skb_p = skb2;
}
skb_push(skb, head_len);
skb->data[3] = FR_PAD;
skb->data[4] = NLPID_SNAP;
skb->data[5] = FR_PAD;
skb->data[6] = 0x80;
skb->data[7] = 0xC2;
skb->data[8] = 0x00;
skb->data[9] = 0x07; /* bridged Ethernet frame w/out FCS */
break;
default:
head_len = 10;
skb_push(skb, head_len);
skb->data[3] = FR_PAD;
skb->data[4] = NLPID_SNAP;
skb->data[5] = FR_PAD;
skb->data[6] = FR_PAD;
skb->data[7] = FR_PAD;
*(__be16*)(skb->data + 8) = skb->protocol;
}
dlci_to_q922(skb->data, dlci);
skb->data[2] = FR_UI;
return 0;
}
static int pvc_open(struct net_device *dev)
{
pvc_device *pvc = dev->ml_priv;
if ((pvc->frad->flags & IFF_UP) == 0)
return -EIO; /* Frad must be UP in order to activate PVC */
if (pvc->open_count++ == 0) {
hdlc_device *hdlc = dev_to_hdlc(pvc->frad);
if (state(hdlc)->settings.lmi == LMI_NONE)
pvc->state.active = netif_carrier_ok(pvc->frad);
pvc_carrier(pvc->state.active, pvc);
state(hdlc)->dce_changed = 1;
}
return 0;
}
static int pvc_close(struct net_device *dev)
{
pvc_device *pvc = dev->ml_priv;
if (--pvc->open_count == 0) {
hdlc_device *hdlc = dev_to_hdlc(pvc->frad);
if (state(hdlc)->settings.lmi == LMI_NONE)
pvc->state.active = 0;
if (state(hdlc)->settings.dce) {
state(hdlc)->dce_changed = 1;
pvc->state.active = 0;
}
}
return 0;
}
static int pvc_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
pvc_device *pvc = dev->ml_priv;
fr_proto_pvc_info info;
if (ifr->ifr_settings.type == IF_GET_PROTO) {
if (dev->type == ARPHRD_ETHER)
ifr->ifr_settings.type = IF_PROTO_FR_ETH_PVC;
else
ifr->ifr_settings.type = IF_PROTO_FR_PVC;
if (ifr->ifr_settings.size < sizeof(info)) {
/* data size wanted */
ifr->ifr_settings.size = sizeof(info);
return -ENOBUFS;
}
info.dlci = pvc->dlci;
memcpy(info.master, pvc->frad->name, IFNAMSIZ);
if (copy_to_user(ifr->ifr_settings.ifs_ifsu.fr_pvc_info,
&info, sizeof(info)))
return -EFAULT;
return 0;
}
return -EINVAL;
}
static netdev_tx_t pvc_xmit(struct sk_buff *skb, struct net_device *dev)
{
pvc_device *pvc = dev->ml_priv;
if (pvc->state.active) {
if (dev->type == ARPHRD_ETHER) {
int pad = ETH_ZLEN - skb->len;
if (pad > 0) { /* Pad the frame with zeros */
int len = skb->len;
if (skb_tailroom(skb) < pad)
if (pskb_expand_head(skb, 0, pad,
GFP_ATOMIC)) {
dev->stats.tx_dropped++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
skb_put(skb, pad);
memset(skb->data + len, 0, pad);
}
skb->protocol = cpu_to_be16(ETH_P_802_3);
}
if (!fr_hard_header(&skb, pvc->dlci)) {
dev->stats.tx_bytes += skb->len;
dev->stats.tx_packets++;
if (pvc->state.fecn) /* TX Congestion counter */
dev->stats.tx_compressed++;
skb->dev = pvc->frad;
dev_queue_xmit(skb);
return NETDEV_TX_OK;
}
}
dev->stats.tx_dropped++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static inline void fr_log_dlci_active(pvc_device *pvc)
{
netdev_info(pvc->frad, "DLCI %d [%s%s%s]%s %s\n",
pvc->dlci,
pvc->main ? pvc->main->name : "",
pvc->main && pvc->ether ? " " : "",
pvc->ether ? pvc->ether->name : "",
pvc->state.new ? " new" : "",
!pvc->state.exist ? "deleted" :
pvc->state.active ? "active" : "inactive");
}
static inline u8 fr_lmi_nextseq(u8 x)
{
x++;
return x ? x : 1;
}
static void fr_lmi_send(struct net_device *dev, int fullrep)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
struct sk_buff *skb;
pvc_device *pvc = state(hdlc)->first_pvc;
int lmi = state(hdlc)->settings.lmi;
int dce = state(hdlc)->settings.dce;
int len = lmi == LMI_ANSI ? LMI_ANSI_LENGTH : LMI_CCITT_CISCO_LENGTH;
int stat_len = (lmi == LMI_CISCO) ? 6 : 3;
u8 *data;
int i = 0;
if (dce && fullrep) {
len += state(hdlc)->dce_pvc_count * (2 + stat_len);
if (len > HDLC_MAX_MRU) {
netdev_warn(dev, "Too many PVCs while sending LMI full report\n");
return;
}
}
skb = dev_alloc_skb(len);
if (!skb) {
netdev_warn(dev, "Memory squeeze on fr_lmi_send()\n");
return;
}
memset(skb->data, 0, len);
skb_reserve(skb, 4);
if (lmi == LMI_CISCO) {
skb->protocol = cpu_to_be16(NLPID_CISCO_LMI);
fr_hard_header(&skb, LMI_CISCO_DLCI);
} else {
skb->protocol = cpu_to_be16(NLPID_CCITT_ANSI_LMI);
fr_hard_header(&skb, LMI_CCITT_ANSI_DLCI);
}
data = skb_tail_pointer(skb);
data[i++] = LMI_CALLREF;
data[i++] = dce ? LMI_STATUS : LMI_STATUS_ENQUIRY;
if (lmi == LMI_ANSI)
data[i++] = LMI_ANSI_LOCKSHIFT;
data[i++] = lmi == LMI_CCITT ? LMI_CCITT_REPTYPE :
LMI_ANSI_CISCO_REPTYPE;
data[i++] = LMI_REPT_LEN;
data[i++] = fullrep ? LMI_FULLREP : LMI_INTEGRITY;
data[i++] = lmi == LMI_CCITT ? LMI_CCITT_ALIVE : LMI_ANSI_CISCO_ALIVE;
data[i++] = LMI_INTEG_LEN;
data[i++] = state(hdlc)->txseq =
fr_lmi_nextseq(state(hdlc)->txseq);
data[i++] = state(hdlc)->rxseq;
if (dce && fullrep) {
while (pvc) {
data[i++] = lmi == LMI_CCITT ? LMI_CCITT_PVCSTAT :
LMI_ANSI_CISCO_PVCSTAT;
data[i++] = stat_len;
/* LMI start/restart */
if (state(hdlc)->reliable && !pvc->state.exist) {
pvc->state.exist = pvc->state.new = 1;
fr_log_dlci_active(pvc);
}
/* ifconfig PVC up */
if (pvc->open_count && !pvc->state.active &&
pvc->state.exist && !pvc->state.new) {
pvc_carrier(1, pvc);
pvc->state.active = 1;
fr_log_dlci_active(pvc);
}
if (lmi == LMI_CISCO) {
data[i] = pvc->dlci >> 8;
data[i + 1] = pvc->dlci & 0xFF;
} else {
data[i] = (pvc->dlci >> 4) & 0x3F;
data[i + 1] = ((pvc->dlci << 3) & 0x78) | 0x80;
data[i + 2] = 0x80;
}
if (pvc->state.new)
data[i + 2] |= 0x08;
else if (pvc->state.active)
data[i + 2] |= 0x02;
i += stat_len;
pvc = pvc->next;
}
}
skb_put(skb, i);
skb->priority = TC_PRIO_CONTROL;
skb->dev = dev;
skb_reset_network_header(skb);
dev_queue_xmit(skb);
}
static void fr_set_link_state(int reliable, struct net_device *dev)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
pvc_device *pvc = state(hdlc)->first_pvc;
state(hdlc)->reliable = reliable;
if (reliable) {
netif_dormant_off(dev);
state(hdlc)->n391cnt = 0; /* Request full status */
state(hdlc)->dce_changed = 1;
if (state(hdlc)->settings.lmi == LMI_NONE) {
while (pvc) { /* Activate all PVCs */
pvc_carrier(1, pvc);
pvc->state.exist = pvc->state.active = 1;
pvc->state.new = 0;
pvc = pvc->next;
}
}
} else {
netif_dormant_on(dev);
while (pvc) { /* Deactivate all PVCs */
pvc_carrier(0, pvc);
pvc->state.exist = pvc->state.active = 0;
pvc->state.new = 0;
if (!state(hdlc)->settings.dce)
pvc->state.bandwidth = 0;
pvc = pvc->next;
}
}
}
static void fr_timer(unsigned long arg)
{
struct net_device *dev = (struct net_device *)arg;
hdlc_device *hdlc = dev_to_hdlc(dev);
int i, cnt = 0, reliable;
u32 list;
if (state(hdlc)->settings.dce) {
reliable = state(hdlc)->request &&
time_before(jiffies, state(hdlc)->last_poll +
state(hdlc)->settings.t392 * HZ);
state(hdlc)->request = 0;
} else {
state(hdlc)->last_errors <<= 1; /* Shift the list */
if (state(hdlc)->request) {
if (state(hdlc)->reliable)
netdev_info(dev, "No LMI status reply received\n");
state(hdlc)->last_errors |= 1;
}
list = state(hdlc)->last_errors;
for (i = 0; i < state(hdlc)->settings.n393; i++, list >>= 1)
cnt += (list & 1); /* errors count */
reliable = (cnt < state(hdlc)->settings.n392);
}
if (state(hdlc)->reliable != reliable) {
netdev_info(dev, "Link %sreliable\n", reliable ? "" : "un");
fr_set_link_state(reliable, dev);
}
if (state(hdlc)->settings.dce)
state(hdlc)->timer.expires = jiffies +
state(hdlc)->settings.t392 * HZ;
else {
if (state(hdlc)->n391cnt)
state(hdlc)->n391cnt--;
fr_lmi_send(dev, state(hdlc)->n391cnt == 0);
state(hdlc)->last_poll = jiffies;
state(hdlc)->request = 1;
state(hdlc)->timer.expires = jiffies +
state(hdlc)->settings.t391 * HZ;
}
state(hdlc)->timer.function = fr_timer;
state(hdlc)->timer.data = arg;
add_timer(&state(hdlc)->timer);
}
static int fr_lmi_recv(struct net_device *dev, struct sk_buff *skb)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
pvc_device *pvc;
u8 rxseq, txseq;
int lmi = state(hdlc)->settings.lmi;
int dce = state(hdlc)->settings.dce;
int stat_len = (lmi == LMI_CISCO) ? 6 : 3, reptype, error, no_ram, i;
if (skb->len < (lmi == LMI_ANSI ? LMI_ANSI_LENGTH :
LMI_CCITT_CISCO_LENGTH)) {
netdev_info(dev, "Short LMI frame\n");
return 1;
}
if (skb->data[3] != (lmi == LMI_CISCO ? NLPID_CISCO_LMI :
NLPID_CCITT_ANSI_LMI)) {
netdev_info(dev, "Received non-LMI frame with LMI DLCI\n");
return 1;
}
if (skb->data[4] != LMI_CALLREF) {
netdev_info(dev, "Invalid LMI Call reference (0x%02X)\n",
skb->data[4]);
return 1;
}
if (skb->data[5] != (dce ? LMI_STATUS_ENQUIRY : LMI_STATUS)) {
netdev_info(dev, "Invalid LMI Message type (0x%02X)\n",
skb->data[5]);
return 1;
}
if (lmi == LMI_ANSI) {
if (skb->data[6] != LMI_ANSI_LOCKSHIFT) {
netdev_info(dev, "Not ANSI locking shift in LMI message (0x%02X)\n",
skb->data[6]);
return 1;
}
i = 7;
} else
i = 6;
if (skb->data[i] != (lmi == LMI_CCITT ? LMI_CCITT_REPTYPE :
LMI_ANSI_CISCO_REPTYPE)) {
netdev_info(dev, "Not an LMI Report type IE (0x%02X)\n",
skb->data[i]);
return 1;
}
if (skb->data[++i] != LMI_REPT_LEN) {
netdev_info(dev, "Invalid LMI Report type IE length (%u)\n",
skb->data[i]);
return 1;
}
reptype = skb->data[++i];
if (reptype != LMI_INTEGRITY && reptype != LMI_FULLREP) {
netdev_info(dev, "Unsupported LMI Report type (0x%02X)\n",
reptype);
return 1;
}
if (skb->data[++i] != (lmi == LMI_CCITT ? LMI_CCITT_ALIVE :
LMI_ANSI_CISCO_ALIVE)) {
netdev_info(dev, "Not an LMI Link integrity verification IE (0x%02X)\n",
skb->data[i]);
return 1;
}
if (skb->data[++i] != LMI_INTEG_LEN) {
netdev_info(dev, "Invalid LMI Link integrity verification IE length (%u)\n",
skb->data[i]);
return 1;
}
i++;
state(hdlc)->rxseq = skb->data[i++]; /* TX sequence from peer */
rxseq = skb->data[i++]; /* Should confirm our sequence */
txseq = state(hdlc)->txseq;
if (dce)
state(hdlc)->last_poll = jiffies;
error = 0;
if (!state(hdlc)->reliable)
error = 1;
if (rxseq == 0 || rxseq != txseq) { /* Ask for full report next time */
state(hdlc)->n391cnt = 0;
error = 1;
}
if (dce) {
if (state(hdlc)->fullrep_sent && !error) {
/* Stop sending full report - the last one has been confirmed by DTE */
state(hdlc)->fullrep_sent = 0;
pvc = state(hdlc)->first_pvc;
while (pvc) {
if (pvc->state.new) {
pvc->state.new = 0;
/* Tell DTE that new PVC is now active */
state(hdlc)->dce_changed = 1;
}
pvc = pvc->next;
}
}
if (state(hdlc)->dce_changed) {
reptype = LMI_FULLREP;
state(hdlc)->fullrep_sent = 1;
state(hdlc)->dce_changed = 0;
}
state(hdlc)->request = 1; /* got request */
fr_lmi_send(dev, reptype == LMI_FULLREP ? 1 : 0);
return 0;
}
/* DTE */
state(hdlc)->request = 0; /* got response, no request pending */
if (error)
return 0;
if (reptype != LMI_FULLREP)
return 0;
pvc = state(hdlc)->first_pvc;
while (pvc) {
pvc->state.deleted = 1;
pvc = pvc->next;
}
no_ram = 0;
while (skb->len >= i + 2 + stat_len) {
u16 dlci;
u32 bw;
unsigned int active, new;
if (skb->data[i] != (lmi == LMI_CCITT ? LMI_CCITT_PVCSTAT :
LMI_ANSI_CISCO_PVCSTAT)) {
netdev_info(dev, "Not an LMI PVC status IE (0x%02X)\n",
skb->data[i]);
return 1;
}
if (skb->data[++i] != stat_len) {
netdev_info(dev, "Invalid LMI PVC status IE length (%u)\n",
skb->data[i]);
return 1;
}
i++;
new = !! (skb->data[i + 2] & 0x08);
active = !! (skb->data[i + 2] & 0x02);
if (lmi == LMI_CISCO) {
dlci = (skb->data[i] << 8) | skb->data[i + 1];
bw = (skb->data[i + 3] << 16) |
(skb->data[i + 4] << 8) |
(skb->data[i + 5]);
} else {
dlci = ((skb->data[i] & 0x3F) << 4) |
((skb->data[i + 1] & 0x78) >> 3);
bw = 0;
}
pvc = add_pvc(dev, dlci);
if (!pvc && !no_ram) {
netdev_warn(dev, "Memory squeeze on fr_lmi_recv()\n");
no_ram = 1;
}
if (pvc) {
pvc->state.exist = 1;
pvc->state.deleted = 0;
if (active != pvc->state.active ||
new != pvc->state.new ||
bw != pvc->state.bandwidth ||
!pvc->state.exist) {
pvc->state.new = new;
pvc->state.active = active;
pvc->state.bandwidth = bw;
pvc_carrier(active, pvc);
fr_log_dlci_active(pvc);
}
}
i += stat_len;
}
pvc = state(hdlc)->first_pvc;
while (pvc) {
if (pvc->state.deleted && pvc->state.exist) {
pvc_carrier(0, pvc);
pvc->state.active = pvc->state.new = 0;
pvc->state.exist = 0;
pvc->state.bandwidth = 0;
fr_log_dlci_active(pvc);
}
pvc = pvc->next;
}
/* Next full report after N391 polls */
state(hdlc)->n391cnt = state(hdlc)->settings.n391;
return 0;
}
static int fr_rx(struct sk_buff *skb)
{
struct net_device *frad = skb->dev;
hdlc_device *hdlc = dev_to_hdlc(frad);
fr_hdr *fh = (fr_hdr*)skb->data;
u8 *data = skb->data;
u16 dlci;
pvc_device *pvc;
struct net_device *dev = NULL;
if (skb->len <= 4 || fh->ea1 || data[2] != FR_UI)
goto rx_error;
dlci = q922_to_dlci(skb->data);
if ((dlci == LMI_CCITT_ANSI_DLCI &&
(state(hdlc)->settings.lmi == LMI_ANSI ||
state(hdlc)->settings.lmi == LMI_CCITT)) ||
(dlci == LMI_CISCO_DLCI &&
state(hdlc)->settings.lmi == LMI_CISCO)) {
if (fr_lmi_recv(frad, skb))
goto rx_error;
dev_kfree_skb_any(skb);
return NET_RX_SUCCESS;
}
pvc = find_pvc(hdlc, dlci);
if (!pvc) {
#ifdef DEBUG_PKT
netdev_info(frad, "No PVC for received frame's DLCI %d\n",
dlci);
#endif
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
if (pvc->state.fecn != fh->fecn) {
#ifdef DEBUG_ECN
printk(KERN_DEBUG "%s: DLCI %d FECN O%s\n", frad->name,
dlci, fh->fecn ? "N" : "FF");
#endif
pvc->state.fecn ^= 1;
}
if (pvc->state.becn != fh->becn) {
#ifdef DEBUG_ECN
printk(KERN_DEBUG "%s: DLCI %d BECN O%s\n", frad->name,
dlci, fh->becn ? "N" : "FF");
#endif
pvc->state.becn ^= 1;
}
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL) {
frad->stats.rx_dropped++;
return NET_RX_DROP;
}
if (data[3] == NLPID_IP) {
skb_pull(skb, 4); /* Remove 4-byte header (hdr, UI, NLPID) */
dev = pvc->main;
skb->protocol = htons(ETH_P_IP);
} else if (data[3] == NLPID_IPV6) {
skb_pull(skb, 4); /* Remove 4-byte header (hdr, UI, NLPID) */
dev = pvc->main;
skb->protocol = htons(ETH_P_IPV6);
} else if (skb->len > 10 && data[3] == FR_PAD &&
data[4] == NLPID_SNAP && data[5] == FR_PAD) {
u16 oui = ntohs(*(__be16*)(data + 6));
u16 pid = ntohs(*(__be16*)(data + 8));
skb_pull(skb, 10);
switch ((((u32)oui) << 16) | pid) {
case ETH_P_ARP: /* routed frame with SNAP */
case ETH_P_IPX:
case ETH_P_IP: /* a long variant */
case ETH_P_IPV6:
dev = pvc->main;
skb->protocol = htons(pid);
break;
case 0x80C20007: /* bridged Ethernet frame */
if ((dev = pvc->ether) != NULL)
skb->protocol = eth_type_trans(skb, dev);
break;
default:
netdev_info(frad, "Unsupported protocol, OUI=%x PID=%x\n",
oui, pid);
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
} else {
netdev_info(frad, "Unsupported protocol, NLPID=%x length=%i\n",
data[3], skb->len);
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
if (dev) {
dev->stats.rx_packets++; /* PVC traffic */
dev->stats.rx_bytes += skb->len;
if (pvc->state.becn)
dev->stats.rx_compressed++;
skb->dev = dev;
netif_rx(skb);
return NET_RX_SUCCESS;
} else {
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
rx_error:
frad->stats.rx_errors++; /* Mark error */
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
static void fr_start(struct net_device *dev)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
#ifdef DEBUG_LINK
printk(KERN_DEBUG "fr_start\n");
#endif
if (state(hdlc)->settings.lmi != LMI_NONE) {
state(hdlc)->reliable = 0;
state(hdlc)->dce_changed = 1;
state(hdlc)->request = 0;
state(hdlc)->fullrep_sent = 0;
state(hdlc)->last_errors = 0xFFFFFFFF;
state(hdlc)->n391cnt = 0;
state(hdlc)->txseq = state(hdlc)->rxseq = 0;
init_timer(&state(hdlc)->timer);
/* First poll after 1 s */
state(hdlc)->timer.expires = jiffies + HZ;
state(hdlc)->timer.function = fr_timer;
state(hdlc)->timer.data = (unsigned long)dev;
add_timer(&state(hdlc)->timer);
} else
fr_set_link_state(1, dev);
}
static void fr_stop(struct net_device *dev)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
#ifdef DEBUG_LINK
printk(KERN_DEBUG "fr_stop\n");
#endif
if (state(hdlc)->settings.lmi != LMI_NONE)
del_timer_sync(&state(hdlc)->timer);
fr_set_link_state(0, dev);
}
static void fr_close(struct net_device *dev)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
pvc_device *pvc = state(hdlc)->first_pvc;
while (pvc) { /* Shutdown all PVCs for this FRAD */
if (pvc->main)
dev_close(pvc->main);
if (pvc->ether)
dev_close(pvc->ether);
pvc = pvc->next;
}
}
static void pvc_setup(struct net_device *dev)
{
dev->type = ARPHRD_DLCI;
dev->flags = IFF_POINTOPOINT;
dev->hard_header_len = 10;
dev->addr_len = 2;
dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
}
static const struct net_device_ops pvc_ops = {
.ndo_open = pvc_open,
.ndo_stop = pvc_close,
.ndo_change_mtu = hdlc_change_mtu,
.ndo_start_xmit = pvc_xmit,
.ndo_do_ioctl = pvc_ioctl,
};
static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc;
struct net_device *dev;
int used;
if ((pvc = add_pvc(frad, dlci)) == NULL) {
netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n");
return -ENOBUFS;
}
if (*get_dev_p(pvc, type))
return -EEXIST;
used = pvc_is_used(pvc);
if (type == ARPHRD_ETHER) {
dev = alloc_netdev(0, "pvceth%d", ether_setup);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
} else
dev = alloc_netdev(0, "pvc%d", pvc_setup);
if (!dev) {
netdev_warn(frad, "Memory squeeze on fr_pvc()\n");
delete_unused_pvcs(hdlc);
return -ENOBUFS;
}
if (type == ARPHRD_ETHER)
eth_hw_addr_random(dev);
else {
*(__be16*)dev->dev_addr = htons(dlci);
dlci_to_q922(dev->broadcast, dlci);
}
dev->netdev_ops = &pvc_ops;
dev->mtu = HDLC_MAX_MTU;
dev->tx_queue_len = 0;
dev->ml_priv = pvc;
if (register_netdevice(dev) != 0) {
free_netdev(dev);
delete_unused_pvcs(hdlc);
return -EIO;
}
dev->destructor = free_netdev;
*get_dev_p(pvc, type) = dev;
if (!used) {
state(hdlc)->dce_changed = 1;
state(hdlc)->dce_pvc_count++;
}
return 0;
}
static int fr_del_pvc(hdlc_device *hdlc, unsigned int dlci, int type)
{
pvc_device *pvc;
struct net_device *dev;
if ((pvc = find_pvc(hdlc, dlci)) == NULL)
return -ENOENT;
if ((dev = *get_dev_p(pvc, type)) == NULL)
return -ENOENT;
if (dev->flags & IFF_UP)
return -EBUSY; /* PVC in use */
unregister_netdevice(dev); /* the destructor will free_netdev(dev) */
*get_dev_p(pvc, type) = NULL;
if (!pvc_is_used(pvc)) {
state(hdlc)->dce_pvc_count--;
state(hdlc)->dce_changed = 1;
}
delete_unused_pvcs(hdlc);
return 0;
}
static void fr_destroy(struct net_device *frad)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc = state(hdlc)->first_pvc;
state(hdlc)->first_pvc = NULL; /* All PVCs destroyed */
state(hdlc)->dce_pvc_count = 0;
state(hdlc)->dce_changed = 1;
while (pvc) {
pvc_device *next = pvc->next;
/* destructors will free_netdev() main and ether */
if (pvc->main)
unregister_netdevice(pvc->main);
if (pvc->ether)
unregister_netdevice(pvc->ether);
kfree(pvc);
pvc = next;
}
}
static struct hdlc_proto proto = {
.close = fr_close,
.start = fr_start,
.stop = fr_stop,
.detach = fr_destroy,
.ioctl = fr_ioctl,
.netif_rx = fr_rx,
.module = THIS_MODULE,
};
static int fr_ioctl(struct net_device *dev, struct ifreq *ifr)
{
fr_proto __user *fr_s = ifr->ifr_settings.ifs_ifsu.fr;
const size_t size = sizeof(fr_proto);
fr_proto new_settings;
hdlc_device *hdlc = dev_to_hdlc(dev);
fr_proto_pvc pvc;
int result;
switch (ifr->ifr_settings.type) {
case IF_GET_PROTO:
if (dev_to_hdlc(dev)->proto != &proto) /* Different proto */
return -EINVAL;
ifr->ifr_settings.type = IF_PROTO_FR;
if (ifr->ifr_settings.size < size) {
ifr->ifr_settings.size = size; /* data size wanted */
return -ENOBUFS;
}
if (copy_to_user(fr_s, &state(hdlc)->settings, size))
return -EFAULT;
return 0;
case IF_PROTO_FR:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (dev->flags & IFF_UP)
return -EBUSY;
if (copy_from_user(&new_settings, fr_s, size))
return -EFAULT;
if (new_settings.lmi == LMI_DEFAULT)
new_settings.lmi = LMI_ANSI;
if ((new_settings.lmi != LMI_NONE &&
new_settings.lmi != LMI_ANSI &&
new_settings.lmi != LMI_CCITT &&
new_settings.lmi != LMI_CISCO) ||
new_settings.t391 < 1 ||
new_settings.t392 < 2 ||
new_settings.n391 < 1 ||
new_settings.n392 < 1 ||
new_settings.n393 < new_settings.n392 ||
new_settings.n393 > 32 ||
(new_settings.dce != 0 &&
new_settings.dce != 1))
return -EINVAL;
result=hdlc->attach(dev, ENCODING_NRZ,PARITY_CRC16_PR1_CCITT);
if (result)
return result;
if (dev_to_hdlc(dev)->proto != &proto) { /* Different proto */
result = attach_hdlc_protocol(dev, &proto,
sizeof(struct frad_state));
if (result)
return result;
state(hdlc)->first_pvc = NULL;
state(hdlc)->dce_pvc_count = 0;
}
memcpy(&state(hdlc)->settings, &new_settings, size);
dev->type = ARPHRD_FRAD;
return 0;
case IF_PROTO_FR_ADD_PVC:
case IF_PROTO_FR_DEL_PVC:
case IF_PROTO_FR_ADD_ETH_PVC:
case IF_PROTO_FR_DEL_ETH_PVC:
if (dev_to_hdlc(dev)->proto != &proto) /* Different proto */
return -EINVAL;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&pvc, ifr->ifr_settings.ifs_ifsu.fr_pvc,
sizeof(fr_proto_pvc)))
return -EFAULT;
if (pvc.dlci <= 0 || pvc.dlci >= 1024)
return -EINVAL; /* Only 10 bits, DLCI 0 reserved */
if (ifr->ifr_settings.type == IF_PROTO_FR_ADD_ETH_PVC ||
ifr->ifr_settings.type == IF_PROTO_FR_DEL_ETH_PVC)
result = ARPHRD_ETHER; /* bridged Ethernet device */
else
result = ARPHRD_DLCI;
if (ifr->ifr_settings.type == IF_PROTO_FR_ADD_PVC ||
ifr->ifr_settings.type == IF_PROTO_FR_ADD_ETH_PVC)
return fr_add_pvc(dev, pvc.dlci, result);
else
return fr_del_pvc(hdlc, pvc.dlci, result);
}
return -EINVAL;
}
static int __init mod_init(void)
{
register_hdlc_protocol(&proto);
return 0;
}
static void __exit mod_exit(void)
{
unregister_hdlc_protocol(&proto);
}
module_init(mod_init);
module_exit(mod_exit);
MODULE_AUTHOR("Krzysztof Halasa <khc@pm.waw.pl>");
MODULE_DESCRIPTION("Frame-Relay protocol support for generic HDLC");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
arnet95/linux | drivers/net/wan/hdlc_fr.c | 7817 | 29896 | /*
* Generic HDLC support routines for Linux
* Frame Relay support
*
* Copyright (C) 1999 - 2006 Krzysztof Halasa <khc@pm.waw.pl>
*
* 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.
*
Theory of PVC state
DCE mode:
(exist,new) -> 0,0 when "PVC create" or if "link unreliable"
0,x -> 1,1 if "link reliable" when sending FULL STATUS
1,1 -> 1,0 if received FULL STATUS ACK
(active) -> 0 when "ifconfig PVC down" or "link unreliable" or "PVC create"
-> 1 when "PVC up" and (exist,new) = 1,0
DTE mode:
(exist,new,active) = FULL STATUS if "link reliable"
= 0, 0, 0 if "link unreliable"
No LMI:
active = open and "link reliable"
exist = new = not used
CCITT LMI: ITU-T Q.933 Annex A
ANSI LMI: ANSI T1.617 Annex D
CISCO LMI: the original, aka "Gang of Four" LMI
*/
#include <linux/errno.h>
#include <linux/etherdevice.h>
#include <linux/hdlc.h>
#include <linux/if_arp.h>
#include <linux/inetdevice.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pkt_sched.h>
#include <linux/poll.h>
#include <linux/rtnetlink.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#undef DEBUG_PKT
#undef DEBUG_ECN
#undef DEBUG_LINK
#undef DEBUG_PROTO
#undef DEBUG_PVC
#define FR_UI 0x03
#define FR_PAD 0x00
#define NLPID_IP 0xCC
#define NLPID_IPV6 0x8E
#define NLPID_SNAP 0x80
#define NLPID_PAD 0x00
#define NLPID_CCITT_ANSI_LMI 0x08
#define NLPID_CISCO_LMI 0x09
#define LMI_CCITT_ANSI_DLCI 0 /* LMI DLCI */
#define LMI_CISCO_DLCI 1023
#define LMI_CALLREF 0x00 /* Call Reference */
#define LMI_ANSI_LOCKSHIFT 0x95 /* ANSI locking shift */
#define LMI_ANSI_CISCO_REPTYPE 0x01 /* report type */
#define LMI_CCITT_REPTYPE 0x51
#define LMI_ANSI_CISCO_ALIVE 0x03 /* keep alive */
#define LMI_CCITT_ALIVE 0x53
#define LMI_ANSI_CISCO_PVCSTAT 0x07 /* PVC status */
#define LMI_CCITT_PVCSTAT 0x57
#define LMI_FULLREP 0x00 /* full report */
#define LMI_INTEGRITY 0x01 /* link integrity report */
#define LMI_SINGLE 0x02 /* single PVC report */
#define LMI_STATUS_ENQUIRY 0x75
#define LMI_STATUS 0x7D /* reply */
#define LMI_REPT_LEN 1 /* report type element length */
#define LMI_INTEG_LEN 2 /* link integrity element length */
#define LMI_CCITT_CISCO_LENGTH 13 /* LMI frame lengths */
#define LMI_ANSI_LENGTH 14
typedef struct {
#if defined(__LITTLE_ENDIAN_BITFIELD)
unsigned ea1: 1;
unsigned cr: 1;
unsigned dlcih: 6;
unsigned ea2: 1;
unsigned de: 1;
unsigned becn: 1;
unsigned fecn: 1;
unsigned dlcil: 4;
#else
unsigned dlcih: 6;
unsigned cr: 1;
unsigned ea1: 1;
unsigned dlcil: 4;
unsigned fecn: 1;
unsigned becn: 1;
unsigned de: 1;
unsigned ea2: 1;
#endif
}__packed fr_hdr;
typedef struct pvc_device_struct {
struct net_device *frad;
struct net_device *main;
struct net_device *ether; /* bridged Ethernet interface */
struct pvc_device_struct *next; /* Sorted in ascending DLCI order */
int dlci;
int open_count;
struct {
unsigned int new: 1;
unsigned int active: 1;
unsigned int exist: 1;
unsigned int deleted: 1;
unsigned int fecn: 1;
unsigned int becn: 1;
unsigned int bandwidth; /* Cisco LMI reporting only */
}state;
}pvc_device;
struct frad_state {
fr_proto settings;
pvc_device *first_pvc;
int dce_pvc_count;
struct timer_list timer;
unsigned long last_poll;
int reliable;
int dce_changed;
int request;
int fullrep_sent;
u32 last_errors; /* last errors bit list */
u8 n391cnt;
u8 txseq; /* TX sequence number */
u8 rxseq; /* RX sequence number */
};
static int fr_ioctl(struct net_device *dev, struct ifreq *ifr);
static inline u16 q922_to_dlci(u8 *hdr)
{
return ((hdr[0] & 0xFC) << 2) | ((hdr[1] & 0xF0) >> 4);
}
static inline void dlci_to_q922(u8 *hdr, u16 dlci)
{
hdr[0] = (dlci >> 2) & 0xFC;
hdr[1] = ((dlci << 4) & 0xF0) | 0x01;
}
static inline struct frad_state* state(hdlc_device *hdlc)
{
return(struct frad_state *)(hdlc->state);
}
static inline pvc_device* find_pvc(hdlc_device *hdlc, u16 dlci)
{
pvc_device *pvc = state(hdlc)->first_pvc;
while (pvc) {
if (pvc->dlci == dlci)
return pvc;
if (pvc->dlci > dlci)
return NULL; /* the list is sorted */
pvc = pvc->next;
}
return NULL;
}
static pvc_device* add_pvc(struct net_device *dev, u16 dlci)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
pvc_device *pvc, **pvc_p = &state(hdlc)->first_pvc;
while (*pvc_p) {
if ((*pvc_p)->dlci == dlci)
return *pvc_p;
if ((*pvc_p)->dlci > dlci)
break; /* the list is sorted */
pvc_p = &(*pvc_p)->next;
}
pvc = kzalloc(sizeof(pvc_device), GFP_ATOMIC);
#ifdef DEBUG_PVC
printk(KERN_DEBUG "add_pvc: allocated pvc %p, frad %p\n", pvc, dev);
#endif
if (!pvc)
return NULL;
pvc->dlci = dlci;
pvc->frad = dev;
pvc->next = *pvc_p; /* Put it in the chain */
*pvc_p = pvc;
return pvc;
}
static inline int pvc_is_used(pvc_device *pvc)
{
return pvc->main || pvc->ether;
}
static inline void pvc_carrier(int on, pvc_device *pvc)
{
if (on) {
if (pvc->main)
if (!netif_carrier_ok(pvc->main))
netif_carrier_on(pvc->main);
if (pvc->ether)
if (!netif_carrier_ok(pvc->ether))
netif_carrier_on(pvc->ether);
} else {
if (pvc->main)
if (netif_carrier_ok(pvc->main))
netif_carrier_off(pvc->main);
if (pvc->ether)
if (netif_carrier_ok(pvc->ether))
netif_carrier_off(pvc->ether);
}
}
static inline void delete_unused_pvcs(hdlc_device *hdlc)
{
pvc_device **pvc_p = &state(hdlc)->first_pvc;
while (*pvc_p) {
if (!pvc_is_used(*pvc_p)) {
pvc_device *pvc = *pvc_p;
#ifdef DEBUG_PVC
printk(KERN_DEBUG "freeing unused pvc: %p\n", pvc);
#endif
*pvc_p = pvc->next;
kfree(pvc);
continue;
}
pvc_p = &(*pvc_p)->next;
}
}
static inline struct net_device** get_dev_p(pvc_device *pvc, int type)
{
if (type == ARPHRD_ETHER)
return &pvc->ether;
else
return &pvc->main;
}
static int fr_hard_header(struct sk_buff **skb_p, u16 dlci)
{
u16 head_len;
struct sk_buff *skb = *skb_p;
switch (skb->protocol) {
case cpu_to_be16(NLPID_CCITT_ANSI_LMI):
head_len = 4;
skb_push(skb, head_len);
skb->data[3] = NLPID_CCITT_ANSI_LMI;
break;
case cpu_to_be16(NLPID_CISCO_LMI):
head_len = 4;
skb_push(skb, head_len);
skb->data[3] = NLPID_CISCO_LMI;
break;
case cpu_to_be16(ETH_P_IP):
head_len = 4;
skb_push(skb, head_len);
skb->data[3] = NLPID_IP;
break;
case cpu_to_be16(ETH_P_IPV6):
head_len = 4;
skb_push(skb, head_len);
skb->data[3] = NLPID_IPV6;
break;
case cpu_to_be16(ETH_P_802_3):
head_len = 10;
if (skb_headroom(skb) < head_len) {
struct sk_buff *skb2 = skb_realloc_headroom(skb,
head_len);
if (!skb2)
return -ENOBUFS;
dev_kfree_skb(skb);
skb = *skb_p = skb2;
}
skb_push(skb, head_len);
skb->data[3] = FR_PAD;
skb->data[4] = NLPID_SNAP;
skb->data[5] = FR_PAD;
skb->data[6] = 0x80;
skb->data[7] = 0xC2;
skb->data[8] = 0x00;
skb->data[9] = 0x07; /* bridged Ethernet frame w/out FCS */
break;
default:
head_len = 10;
skb_push(skb, head_len);
skb->data[3] = FR_PAD;
skb->data[4] = NLPID_SNAP;
skb->data[5] = FR_PAD;
skb->data[6] = FR_PAD;
skb->data[7] = FR_PAD;
*(__be16*)(skb->data + 8) = skb->protocol;
}
dlci_to_q922(skb->data, dlci);
skb->data[2] = FR_UI;
return 0;
}
static int pvc_open(struct net_device *dev)
{
pvc_device *pvc = dev->ml_priv;
if ((pvc->frad->flags & IFF_UP) == 0)
return -EIO; /* Frad must be UP in order to activate PVC */
if (pvc->open_count++ == 0) {
hdlc_device *hdlc = dev_to_hdlc(pvc->frad);
if (state(hdlc)->settings.lmi == LMI_NONE)
pvc->state.active = netif_carrier_ok(pvc->frad);
pvc_carrier(pvc->state.active, pvc);
state(hdlc)->dce_changed = 1;
}
return 0;
}
static int pvc_close(struct net_device *dev)
{
pvc_device *pvc = dev->ml_priv;
if (--pvc->open_count == 0) {
hdlc_device *hdlc = dev_to_hdlc(pvc->frad);
if (state(hdlc)->settings.lmi == LMI_NONE)
pvc->state.active = 0;
if (state(hdlc)->settings.dce) {
state(hdlc)->dce_changed = 1;
pvc->state.active = 0;
}
}
return 0;
}
static int pvc_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
pvc_device *pvc = dev->ml_priv;
fr_proto_pvc_info info;
if (ifr->ifr_settings.type == IF_GET_PROTO) {
if (dev->type == ARPHRD_ETHER)
ifr->ifr_settings.type = IF_PROTO_FR_ETH_PVC;
else
ifr->ifr_settings.type = IF_PROTO_FR_PVC;
if (ifr->ifr_settings.size < sizeof(info)) {
/* data size wanted */
ifr->ifr_settings.size = sizeof(info);
return -ENOBUFS;
}
info.dlci = pvc->dlci;
memcpy(info.master, pvc->frad->name, IFNAMSIZ);
if (copy_to_user(ifr->ifr_settings.ifs_ifsu.fr_pvc_info,
&info, sizeof(info)))
return -EFAULT;
return 0;
}
return -EINVAL;
}
static netdev_tx_t pvc_xmit(struct sk_buff *skb, struct net_device *dev)
{
pvc_device *pvc = dev->ml_priv;
if (pvc->state.active) {
if (dev->type == ARPHRD_ETHER) {
int pad = ETH_ZLEN - skb->len;
if (pad > 0) { /* Pad the frame with zeros */
int len = skb->len;
if (skb_tailroom(skb) < pad)
if (pskb_expand_head(skb, 0, pad,
GFP_ATOMIC)) {
dev->stats.tx_dropped++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
skb_put(skb, pad);
memset(skb->data + len, 0, pad);
}
skb->protocol = cpu_to_be16(ETH_P_802_3);
}
if (!fr_hard_header(&skb, pvc->dlci)) {
dev->stats.tx_bytes += skb->len;
dev->stats.tx_packets++;
if (pvc->state.fecn) /* TX Congestion counter */
dev->stats.tx_compressed++;
skb->dev = pvc->frad;
dev_queue_xmit(skb);
return NETDEV_TX_OK;
}
}
dev->stats.tx_dropped++;
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static inline void fr_log_dlci_active(pvc_device *pvc)
{
netdev_info(pvc->frad, "DLCI %d [%s%s%s]%s %s\n",
pvc->dlci,
pvc->main ? pvc->main->name : "",
pvc->main && pvc->ether ? " " : "",
pvc->ether ? pvc->ether->name : "",
pvc->state.new ? " new" : "",
!pvc->state.exist ? "deleted" :
pvc->state.active ? "active" : "inactive");
}
static inline u8 fr_lmi_nextseq(u8 x)
{
x++;
return x ? x : 1;
}
static void fr_lmi_send(struct net_device *dev, int fullrep)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
struct sk_buff *skb;
pvc_device *pvc = state(hdlc)->first_pvc;
int lmi = state(hdlc)->settings.lmi;
int dce = state(hdlc)->settings.dce;
int len = lmi == LMI_ANSI ? LMI_ANSI_LENGTH : LMI_CCITT_CISCO_LENGTH;
int stat_len = (lmi == LMI_CISCO) ? 6 : 3;
u8 *data;
int i = 0;
if (dce && fullrep) {
len += state(hdlc)->dce_pvc_count * (2 + stat_len);
if (len > HDLC_MAX_MRU) {
netdev_warn(dev, "Too many PVCs while sending LMI full report\n");
return;
}
}
skb = dev_alloc_skb(len);
if (!skb) {
netdev_warn(dev, "Memory squeeze on fr_lmi_send()\n");
return;
}
memset(skb->data, 0, len);
skb_reserve(skb, 4);
if (lmi == LMI_CISCO) {
skb->protocol = cpu_to_be16(NLPID_CISCO_LMI);
fr_hard_header(&skb, LMI_CISCO_DLCI);
} else {
skb->protocol = cpu_to_be16(NLPID_CCITT_ANSI_LMI);
fr_hard_header(&skb, LMI_CCITT_ANSI_DLCI);
}
data = skb_tail_pointer(skb);
data[i++] = LMI_CALLREF;
data[i++] = dce ? LMI_STATUS : LMI_STATUS_ENQUIRY;
if (lmi == LMI_ANSI)
data[i++] = LMI_ANSI_LOCKSHIFT;
data[i++] = lmi == LMI_CCITT ? LMI_CCITT_REPTYPE :
LMI_ANSI_CISCO_REPTYPE;
data[i++] = LMI_REPT_LEN;
data[i++] = fullrep ? LMI_FULLREP : LMI_INTEGRITY;
data[i++] = lmi == LMI_CCITT ? LMI_CCITT_ALIVE : LMI_ANSI_CISCO_ALIVE;
data[i++] = LMI_INTEG_LEN;
data[i++] = state(hdlc)->txseq =
fr_lmi_nextseq(state(hdlc)->txseq);
data[i++] = state(hdlc)->rxseq;
if (dce && fullrep) {
while (pvc) {
data[i++] = lmi == LMI_CCITT ? LMI_CCITT_PVCSTAT :
LMI_ANSI_CISCO_PVCSTAT;
data[i++] = stat_len;
/* LMI start/restart */
if (state(hdlc)->reliable && !pvc->state.exist) {
pvc->state.exist = pvc->state.new = 1;
fr_log_dlci_active(pvc);
}
/* ifconfig PVC up */
if (pvc->open_count && !pvc->state.active &&
pvc->state.exist && !pvc->state.new) {
pvc_carrier(1, pvc);
pvc->state.active = 1;
fr_log_dlci_active(pvc);
}
if (lmi == LMI_CISCO) {
data[i] = pvc->dlci >> 8;
data[i + 1] = pvc->dlci & 0xFF;
} else {
data[i] = (pvc->dlci >> 4) & 0x3F;
data[i + 1] = ((pvc->dlci << 3) & 0x78) | 0x80;
data[i + 2] = 0x80;
}
if (pvc->state.new)
data[i + 2] |= 0x08;
else if (pvc->state.active)
data[i + 2] |= 0x02;
i += stat_len;
pvc = pvc->next;
}
}
skb_put(skb, i);
skb->priority = TC_PRIO_CONTROL;
skb->dev = dev;
skb_reset_network_header(skb);
dev_queue_xmit(skb);
}
static void fr_set_link_state(int reliable, struct net_device *dev)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
pvc_device *pvc = state(hdlc)->first_pvc;
state(hdlc)->reliable = reliable;
if (reliable) {
netif_dormant_off(dev);
state(hdlc)->n391cnt = 0; /* Request full status */
state(hdlc)->dce_changed = 1;
if (state(hdlc)->settings.lmi == LMI_NONE) {
while (pvc) { /* Activate all PVCs */
pvc_carrier(1, pvc);
pvc->state.exist = pvc->state.active = 1;
pvc->state.new = 0;
pvc = pvc->next;
}
}
} else {
netif_dormant_on(dev);
while (pvc) { /* Deactivate all PVCs */
pvc_carrier(0, pvc);
pvc->state.exist = pvc->state.active = 0;
pvc->state.new = 0;
if (!state(hdlc)->settings.dce)
pvc->state.bandwidth = 0;
pvc = pvc->next;
}
}
}
static void fr_timer(unsigned long arg)
{
struct net_device *dev = (struct net_device *)arg;
hdlc_device *hdlc = dev_to_hdlc(dev);
int i, cnt = 0, reliable;
u32 list;
if (state(hdlc)->settings.dce) {
reliable = state(hdlc)->request &&
time_before(jiffies, state(hdlc)->last_poll +
state(hdlc)->settings.t392 * HZ);
state(hdlc)->request = 0;
} else {
state(hdlc)->last_errors <<= 1; /* Shift the list */
if (state(hdlc)->request) {
if (state(hdlc)->reliable)
netdev_info(dev, "No LMI status reply received\n");
state(hdlc)->last_errors |= 1;
}
list = state(hdlc)->last_errors;
for (i = 0; i < state(hdlc)->settings.n393; i++, list >>= 1)
cnt += (list & 1); /* errors count */
reliable = (cnt < state(hdlc)->settings.n392);
}
if (state(hdlc)->reliable != reliable) {
netdev_info(dev, "Link %sreliable\n", reliable ? "" : "un");
fr_set_link_state(reliable, dev);
}
if (state(hdlc)->settings.dce)
state(hdlc)->timer.expires = jiffies +
state(hdlc)->settings.t392 * HZ;
else {
if (state(hdlc)->n391cnt)
state(hdlc)->n391cnt--;
fr_lmi_send(dev, state(hdlc)->n391cnt == 0);
state(hdlc)->last_poll = jiffies;
state(hdlc)->request = 1;
state(hdlc)->timer.expires = jiffies +
state(hdlc)->settings.t391 * HZ;
}
state(hdlc)->timer.function = fr_timer;
state(hdlc)->timer.data = arg;
add_timer(&state(hdlc)->timer);
}
static int fr_lmi_recv(struct net_device *dev, struct sk_buff *skb)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
pvc_device *pvc;
u8 rxseq, txseq;
int lmi = state(hdlc)->settings.lmi;
int dce = state(hdlc)->settings.dce;
int stat_len = (lmi == LMI_CISCO) ? 6 : 3, reptype, error, no_ram, i;
if (skb->len < (lmi == LMI_ANSI ? LMI_ANSI_LENGTH :
LMI_CCITT_CISCO_LENGTH)) {
netdev_info(dev, "Short LMI frame\n");
return 1;
}
if (skb->data[3] != (lmi == LMI_CISCO ? NLPID_CISCO_LMI :
NLPID_CCITT_ANSI_LMI)) {
netdev_info(dev, "Received non-LMI frame with LMI DLCI\n");
return 1;
}
if (skb->data[4] != LMI_CALLREF) {
netdev_info(dev, "Invalid LMI Call reference (0x%02X)\n",
skb->data[4]);
return 1;
}
if (skb->data[5] != (dce ? LMI_STATUS_ENQUIRY : LMI_STATUS)) {
netdev_info(dev, "Invalid LMI Message type (0x%02X)\n",
skb->data[5]);
return 1;
}
if (lmi == LMI_ANSI) {
if (skb->data[6] != LMI_ANSI_LOCKSHIFT) {
netdev_info(dev, "Not ANSI locking shift in LMI message (0x%02X)\n",
skb->data[6]);
return 1;
}
i = 7;
} else
i = 6;
if (skb->data[i] != (lmi == LMI_CCITT ? LMI_CCITT_REPTYPE :
LMI_ANSI_CISCO_REPTYPE)) {
netdev_info(dev, "Not an LMI Report type IE (0x%02X)\n",
skb->data[i]);
return 1;
}
if (skb->data[++i] != LMI_REPT_LEN) {
netdev_info(dev, "Invalid LMI Report type IE length (%u)\n",
skb->data[i]);
return 1;
}
reptype = skb->data[++i];
if (reptype != LMI_INTEGRITY && reptype != LMI_FULLREP) {
netdev_info(dev, "Unsupported LMI Report type (0x%02X)\n",
reptype);
return 1;
}
if (skb->data[++i] != (lmi == LMI_CCITT ? LMI_CCITT_ALIVE :
LMI_ANSI_CISCO_ALIVE)) {
netdev_info(dev, "Not an LMI Link integrity verification IE (0x%02X)\n",
skb->data[i]);
return 1;
}
if (skb->data[++i] != LMI_INTEG_LEN) {
netdev_info(dev, "Invalid LMI Link integrity verification IE length (%u)\n",
skb->data[i]);
return 1;
}
i++;
state(hdlc)->rxseq = skb->data[i++]; /* TX sequence from peer */
rxseq = skb->data[i++]; /* Should confirm our sequence */
txseq = state(hdlc)->txseq;
if (dce)
state(hdlc)->last_poll = jiffies;
error = 0;
if (!state(hdlc)->reliable)
error = 1;
if (rxseq == 0 || rxseq != txseq) { /* Ask for full report next time */
state(hdlc)->n391cnt = 0;
error = 1;
}
if (dce) {
if (state(hdlc)->fullrep_sent && !error) {
/* Stop sending full report - the last one has been confirmed by DTE */
state(hdlc)->fullrep_sent = 0;
pvc = state(hdlc)->first_pvc;
while (pvc) {
if (pvc->state.new) {
pvc->state.new = 0;
/* Tell DTE that new PVC is now active */
state(hdlc)->dce_changed = 1;
}
pvc = pvc->next;
}
}
if (state(hdlc)->dce_changed) {
reptype = LMI_FULLREP;
state(hdlc)->fullrep_sent = 1;
state(hdlc)->dce_changed = 0;
}
state(hdlc)->request = 1; /* got request */
fr_lmi_send(dev, reptype == LMI_FULLREP ? 1 : 0);
return 0;
}
/* DTE */
state(hdlc)->request = 0; /* got response, no request pending */
if (error)
return 0;
if (reptype != LMI_FULLREP)
return 0;
pvc = state(hdlc)->first_pvc;
while (pvc) {
pvc->state.deleted = 1;
pvc = pvc->next;
}
no_ram = 0;
while (skb->len >= i + 2 + stat_len) {
u16 dlci;
u32 bw;
unsigned int active, new;
if (skb->data[i] != (lmi == LMI_CCITT ? LMI_CCITT_PVCSTAT :
LMI_ANSI_CISCO_PVCSTAT)) {
netdev_info(dev, "Not an LMI PVC status IE (0x%02X)\n",
skb->data[i]);
return 1;
}
if (skb->data[++i] != stat_len) {
netdev_info(dev, "Invalid LMI PVC status IE length (%u)\n",
skb->data[i]);
return 1;
}
i++;
new = !! (skb->data[i + 2] & 0x08);
active = !! (skb->data[i + 2] & 0x02);
if (lmi == LMI_CISCO) {
dlci = (skb->data[i] << 8) | skb->data[i + 1];
bw = (skb->data[i + 3] << 16) |
(skb->data[i + 4] << 8) |
(skb->data[i + 5]);
} else {
dlci = ((skb->data[i] & 0x3F) << 4) |
((skb->data[i + 1] & 0x78) >> 3);
bw = 0;
}
pvc = add_pvc(dev, dlci);
if (!pvc && !no_ram) {
netdev_warn(dev, "Memory squeeze on fr_lmi_recv()\n");
no_ram = 1;
}
if (pvc) {
pvc->state.exist = 1;
pvc->state.deleted = 0;
if (active != pvc->state.active ||
new != pvc->state.new ||
bw != pvc->state.bandwidth ||
!pvc->state.exist) {
pvc->state.new = new;
pvc->state.active = active;
pvc->state.bandwidth = bw;
pvc_carrier(active, pvc);
fr_log_dlci_active(pvc);
}
}
i += stat_len;
}
pvc = state(hdlc)->first_pvc;
while (pvc) {
if (pvc->state.deleted && pvc->state.exist) {
pvc_carrier(0, pvc);
pvc->state.active = pvc->state.new = 0;
pvc->state.exist = 0;
pvc->state.bandwidth = 0;
fr_log_dlci_active(pvc);
}
pvc = pvc->next;
}
/* Next full report after N391 polls */
state(hdlc)->n391cnt = state(hdlc)->settings.n391;
return 0;
}
static int fr_rx(struct sk_buff *skb)
{
struct net_device *frad = skb->dev;
hdlc_device *hdlc = dev_to_hdlc(frad);
fr_hdr *fh = (fr_hdr*)skb->data;
u8 *data = skb->data;
u16 dlci;
pvc_device *pvc;
struct net_device *dev = NULL;
if (skb->len <= 4 || fh->ea1 || data[2] != FR_UI)
goto rx_error;
dlci = q922_to_dlci(skb->data);
if ((dlci == LMI_CCITT_ANSI_DLCI &&
(state(hdlc)->settings.lmi == LMI_ANSI ||
state(hdlc)->settings.lmi == LMI_CCITT)) ||
(dlci == LMI_CISCO_DLCI &&
state(hdlc)->settings.lmi == LMI_CISCO)) {
if (fr_lmi_recv(frad, skb))
goto rx_error;
dev_kfree_skb_any(skb);
return NET_RX_SUCCESS;
}
pvc = find_pvc(hdlc, dlci);
if (!pvc) {
#ifdef DEBUG_PKT
netdev_info(frad, "No PVC for received frame's DLCI %d\n",
dlci);
#endif
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
if (pvc->state.fecn != fh->fecn) {
#ifdef DEBUG_ECN
printk(KERN_DEBUG "%s: DLCI %d FECN O%s\n", frad->name,
dlci, fh->fecn ? "N" : "FF");
#endif
pvc->state.fecn ^= 1;
}
if (pvc->state.becn != fh->becn) {
#ifdef DEBUG_ECN
printk(KERN_DEBUG "%s: DLCI %d BECN O%s\n", frad->name,
dlci, fh->becn ? "N" : "FF");
#endif
pvc->state.becn ^= 1;
}
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL) {
frad->stats.rx_dropped++;
return NET_RX_DROP;
}
if (data[3] == NLPID_IP) {
skb_pull(skb, 4); /* Remove 4-byte header (hdr, UI, NLPID) */
dev = pvc->main;
skb->protocol = htons(ETH_P_IP);
} else if (data[3] == NLPID_IPV6) {
skb_pull(skb, 4); /* Remove 4-byte header (hdr, UI, NLPID) */
dev = pvc->main;
skb->protocol = htons(ETH_P_IPV6);
} else if (skb->len > 10 && data[3] == FR_PAD &&
data[4] == NLPID_SNAP && data[5] == FR_PAD) {
u16 oui = ntohs(*(__be16*)(data + 6));
u16 pid = ntohs(*(__be16*)(data + 8));
skb_pull(skb, 10);
switch ((((u32)oui) << 16) | pid) {
case ETH_P_ARP: /* routed frame with SNAP */
case ETH_P_IPX:
case ETH_P_IP: /* a long variant */
case ETH_P_IPV6:
dev = pvc->main;
skb->protocol = htons(pid);
break;
case 0x80C20007: /* bridged Ethernet frame */
if ((dev = pvc->ether) != NULL)
skb->protocol = eth_type_trans(skb, dev);
break;
default:
netdev_info(frad, "Unsupported protocol, OUI=%x PID=%x\n",
oui, pid);
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
} else {
netdev_info(frad, "Unsupported protocol, NLPID=%x length=%i\n",
data[3], skb->len);
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
if (dev) {
dev->stats.rx_packets++; /* PVC traffic */
dev->stats.rx_bytes += skb->len;
if (pvc->state.becn)
dev->stats.rx_compressed++;
skb->dev = dev;
netif_rx(skb);
return NET_RX_SUCCESS;
} else {
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
rx_error:
frad->stats.rx_errors++; /* Mark error */
dev_kfree_skb_any(skb);
return NET_RX_DROP;
}
static void fr_start(struct net_device *dev)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
#ifdef DEBUG_LINK
printk(KERN_DEBUG "fr_start\n");
#endif
if (state(hdlc)->settings.lmi != LMI_NONE) {
state(hdlc)->reliable = 0;
state(hdlc)->dce_changed = 1;
state(hdlc)->request = 0;
state(hdlc)->fullrep_sent = 0;
state(hdlc)->last_errors = 0xFFFFFFFF;
state(hdlc)->n391cnt = 0;
state(hdlc)->txseq = state(hdlc)->rxseq = 0;
init_timer(&state(hdlc)->timer);
/* First poll after 1 s */
state(hdlc)->timer.expires = jiffies + HZ;
state(hdlc)->timer.function = fr_timer;
state(hdlc)->timer.data = (unsigned long)dev;
add_timer(&state(hdlc)->timer);
} else
fr_set_link_state(1, dev);
}
static void fr_stop(struct net_device *dev)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
#ifdef DEBUG_LINK
printk(KERN_DEBUG "fr_stop\n");
#endif
if (state(hdlc)->settings.lmi != LMI_NONE)
del_timer_sync(&state(hdlc)->timer);
fr_set_link_state(0, dev);
}
static void fr_close(struct net_device *dev)
{
hdlc_device *hdlc = dev_to_hdlc(dev);
pvc_device *pvc = state(hdlc)->first_pvc;
while (pvc) { /* Shutdown all PVCs for this FRAD */
if (pvc->main)
dev_close(pvc->main);
if (pvc->ether)
dev_close(pvc->ether);
pvc = pvc->next;
}
}
static void pvc_setup(struct net_device *dev)
{
dev->type = ARPHRD_DLCI;
dev->flags = IFF_POINTOPOINT;
dev->hard_header_len = 10;
dev->addr_len = 2;
dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
}
static const struct net_device_ops pvc_ops = {
.ndo_open = pvc_open,
.ndo_stop = pvc_close,
.ndo_change_mtu = hdlc_change_mtu,
.ndo_start_xmit = pvc_xmit,
.ndo_do_ioctl = pvc_ioctl,
};
static int fr_add_pvc(struct net_device *frad, unsigned int dlci, int type)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc;
struct net_device *dev;
int used;
if ((pvc = add_pvc(frad, dlci)) == NULL) {
netdev_warn(frad, "Memory squeeze on fr_add_pvc()\n");
return -ENOBUFS;
}
if (*get_dev_p(pvc, type))
return -EEXIST;
used = pvc_is_used(pvc);
if (type == ARPHRD_ETHER) {
dev = alloc_netdev(0, "pvceth%d", ether_setup);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
} else
dev = alloc_netdev(0, "pvc%d", pvc_setup);
if (!dev) {
netdev_warn(frad, "Memory squeeze on fr_pvc()\n");
delete_unused_pvcs(hdlc);
return -ENOBUFS;
}
if (type == ARPHRD_ETHER)
eth_hw_addr_random(dev);
else {
*(__be16*)dev->dev_addr = htons(dlci);
dlci_to_q922(dev->broadcast, dlci);
}
dev->netdev_ops = &pvc_ops;
dev->mtu = HDLC_MAX_MTU;
dev->tx_queue_len = 0;
dev->ml_priv = pvc;
if (register_netdevice(dev) != 0) {
free_netdev(dev);
delete_unused_pvcs(hdlc);
return -EIO;
}
dev->destructor = free_netdev;
*get_dev_p(pvc, type) = dev;
if (!used) {
state(hdlc)->dce_changed = 1;
state(hdlc)->dce_pvc_count++;
}
return 0;
}
static int fr_del_pvc(hdlc_device *hdlc, unsigned int dlci, int type)
{
pvc_device *pvc;
struct net_device *dev;
if ((pvc = find_pvc(hdlc, dlci)) == NULL)
return -ENOENT;
if ((dev = *get_dev_p(pvc, type)) == NULL)
return -ENOENT;
if (dev->flags & IFF_UP)
return -EBUSY; /* PVC in use */
unregister_netdevice(dev); /* the destructor will free_netdev(dev) */
*get_dev_p(pvc, type) = NULL;
if (!pvc_is_used(pvc)) {
state(hdlc)->dce_pvc_count--;
state(hdlc)->dce_changed = 1;
}
delete_unused_pvcs(hdlc);
return 0;
}
static void fr_destroy(struct net_device *frad)
{
hdlc_device *hdlc = dev_to_hdlc(frad);
pvc_device *pvc = state(hdlc)->first_pvc;
state(hdlc)->first_pvc = NULL; /* All PVCs destroyed */
state(hdlc)->dce_pvc_count = 0;
state(hdlc)->dce_changed = 1;
while (pvc) {
pvc_device *next = pvc->next;
/* destructors will free_netdev() main and ether */
if (pvc->main)
unregister_netdevice(pvc->main);
if (pvc->ether)
unregister_netdevice(pvc->ether);
kfree(pvc);
pvc = next;
}
}
static struct hdlc_proto proto = {
.close = fr_close,
.start = fr_start,
.stop = fr_stop,
.detach = fr_destroy,
.ioctl = fr_ioctl,
.netif_rx = fr_rx,
.module = THIS_MODULE,
};
static int fr_ioctl(struct net_device *dev, struct ifreq *ifr)
{
fr_proto __user *fr_s = ifr->ifr_settings.ifs_ifsu.fr;
const size_t size = sizeof(fr_proto);
fr_proto new_settings;
hdlc_device *hdlc = dev_to_hdlc(dev);
fr_proto_pvc pvc;
int result;
switch (ifr->ifr_settings.type) {
case IF_GET_PROTO:
if (dev_to_hdlc(dev)->proto != &proto) /* Different proto */
return -EINVAL;
ifr->ifr_settings.type = IF_PROTO_FR;
if (ifr->ifr_settings.size < size) {
ifr->ifr_settings.size = size; /* data size wanted */
return -ENOBUFS;
}
if (copy_to_user(fr_s, &state(hdlc)->settings, size))
return -EFAULT;
return 0;
case IF_PROTO_FR:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (dev->flags & IFF_UP)
return -EBUSY;
if (copy_from_user(&new_settings, fr_s, size))
return -EFAULT;
if (new_settings.lmi == LMI_DEFAULT)
new_settings.lmi = LMI_ANSI;
if ((new_settings.lmi != LMI_NONE &&
new_settings.lmi != LMI_ANSI &&
new_settings.lmi != LMI_CCITT &&
new_settings.lmi != LMI_CISCO) ||
new_settings.t391 < 1 ||
new_settings.t392 < 2 ||
new_settings.n391 < 1 ||
new_settings.n392 < 1 ||
new_settings.n393 < new_settings.n392 ||
new_settings.n393 > 32 ||
(new_settings.dce != 0 &&
new_settings.dce != 1))
return -EINVAL;
result=hdlc->attach(dev, ENCODING_NRZ,PARITY_CRC16_PR1_CCITT);
if (result)
return result;
if (dev_to_hdlc(dev)->proto != &proto) { /* Different proto */
result = attach_hdlc_protocol(dev, &proto,
sizeof(struct frad_state));
if (result)
return result;
state(hdlc)->first_pvc = NULL;
state(hdlc)->dce_pvc_count = 0;
}
memcpy(&state(hdlc)->settings, &new_settings, size);
dev->type = ARPHRD_FRAD;
return 0;
case IF_PROTO_FR_ADD_PVC:
case IF_PROTO_FR_DEL_PVC:
case IF_PROTO_FR_ADD_ETH_PVC:
case IF_PROTO_FR_DEL_ETH_PVC:
if (dev_to_hdlc(dev)->proto != &proto) /* Different proto */
return -EINVAL;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&pvc, ifr->ifr_settings.ifs_ifsu.fr_pvc,
sizeof(fr_proto_pvc)))
return -EFAULT;
if (pvc.dlci <= 0 || pvc.dlci >= 1024)
return -EINVAL; /* Only 10 bits, DLCI 0 reserved */
if (ifr->ifr_settings.type == IF_PROTO_FR_ADD_ETH_PVC ||
ifr->ifr_settings.type == IF_PROTO_FR_DEL_ETH_PVC)
result = ARPHRD_ETHER; /* bridged Ethernet device */
else
result = ARPHRD_DLCI;
if (ifr->ifr_settings.type == IF_PROTO_FR_ADD_PVC ||
ifr->ifr_settings.type == IF_PROTO_FR_ADD_ETH_PVC)
return fr_add_pvc(dev, pvc.dlci, result);
else
return fr_del_pvc(hdlc, pvc.dlci, result);
}
return -EINVAL;
}
static int __init mod_init(void)
{
register_hdlc_protocol(&proto);
return 0;
}
static void __exit mod_exit(void)
{
unregister_hdlc_protocol(&proto);
}
module_init(mod_init);
module_exit(mod_exit);
MODULE_AUTHOR("Krzysztof Halasa <khc@pm.waw.pl>");
MODULE_DESCRIPTION("Frame-Relay protocol support for generic HDLC");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.